1 //===--- Bitcode/Writer/Writer.cpp - Bitcode Writer -----------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by Chris Lattner and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Bitcode writer implementation.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Bitcode/ReaderWriter.h"
15 #include "llvm/Bitcode/BitstreamWriter.h"
16 #include "llvm/Bitcode/LLVMBitCodes.h"
17 #include "ValueEnumerator.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/Module.h"
20 #include "llvm/TypeSymbolTable.h"
21 #include "llvm/Support/MathExtras.h"
24 static const unsigned CurVersion = 0;
26 static void WriteStringRecord(unsigned Code, const std::string &Str,
27 unsigned AbbrevToUse, BitstreamWriter &Stream) {
28 SmallVector<unsigned, 64> Vals;
30 // Code: [strlen, strchar x N]
31 Vals.push_back(Str.size());
32 for (unsigned i = 0, e = Str.size(); i != e; ++i)
33 Vals.push_back(Str[i]);
35 // Emit the finished record.
36 Stream.EmitRecord(Code, Vals, AbbrevToUse);
40 /// WriteTypeTable - Write out the type table for a module.
41 static void WriteTypeTable(const ValueEnumerator &VE, BitstreamWriter &Stream) {
42 const ValueEnumerator::TypeList &TypeList = VE.getTypes();
44 Stream.EnterSubblock(bitc::TYPE_BLOCK_ID, 4 /*count from # abbrevs */);
45 SmallVector<uint64_t, 64> TypeVals;
47 // FIXME: Set up abbrevs now that we know the width of the type fields, etc.
49 // Emit an entry count so the reader can reserve space.
50 TypeVals.push_back(TypeList.size());
51 Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals);
54 // Loop over all of the types, emitting each in turn.
55 for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
56 const Type *T = TypeList[i].first;
60 switch (T->getTypeID()) {
61 case Type::PackedStructTyID: // FIXME: Delete Type::PackedStructTyID.
62 default: assert(0 && "Unknown type!");
63 case Type::VoidTyID: Code = bitc::TYPE_CODE_VOID; break;
64 case Type::FloatTyID: Code = bitc::TYPE_CODE_FLOAT; break;
65 case Type::DoubleTyID: Code = bitc::TYPE_CODE_DOUBLE; break;
66 case Type::LabelTyID: Code = bitc::TYPE_CODE_LABEL; break;
67 case Type::OpaqueTyID: Code = bitc::TYPE_CODE_OPAQUE; break;
68 case Type::IntegerTyID:
70 Code = bitc::TYPE_CODE_INTEGER;
71 TypeVals.push_back(cast<IntegerType>(T)->getBitWidth());
73 case Type::PointerTyID:
74 // POINTER: [pointee type]
75 Code = bitc::TYPE_CODE_POINTER;
76 TypeVals.push_back(VE.getTypeID(cast<PointerType>(T)->getElementType()));
79 case Type::FunctionTyID: {
80 const FunctionType *FT = cast<FunctionType>(T);
81 // FUNCTION: [isvararg, #pararms, paramty x N]
82 Code = bitc::TYPE_CODE_FUNCTION;
83 TypeVals.push_back(FT->isVarArg());
84 TypeVals.push_back(VE.getTypeID(FT->getReturnType()));
85 // FIXME: PARAM ATTR ID!
86 TypeVals.push_back(FT->getNumParams());
87 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
88 TypeVals.push_back(VE.getTypeID(FT->getParamType(i)));
91 case Type::StructTyID: {
92 const StructType *ST = cast<StructType>(T);
93 // STRUCT: [ispacked, #elts, eltty x N]
94 Code = bitc::TYPE_CODE_STRUCT;
95 TypeVals.push_back(ST->isPacked());
96 TypeVals.push_back(ST->getNumElements());
97 // Output all of the element types...
98 for (StructType::element_iterator I = ST->element_begin(),
99 E = ST->element_end(); I != E; ++I)
100 TypeVals.push_back(VE.getTypeID(*I));
103 case Type::ArrayTyID: {
104 const ArrayType *AT = cast<ArrayType>(T);
105 // ARRAY: [numelts, eltty]
106 Code = bitc::TYPE_CODE_ARRAY;
107 TypeVals.push_back(AT->getNumElements());
108 TypeVals.push_back(VE.getTypeID(AT->getElementType()));
111 case Type::VectorTyID: {
112 const VectorType *VT = cast<VectorType>(T);
113 // VECTOR [numelts, eltty]
114 Code = bitc::TYPE_CODE_VECTOR;
115 TypeVals.push_back(VT->getNumElements());
116 TypeVals.push_back(VE.getTypeID(VT->getElementType()));
121 // Emit the finished record.
122 Stream.EmitRecord(Code, TypeVals, AbbrevToUse);
129 /// WriteTypeSymbolTable - Emit a block for the specified type symtab.
130 static void WriteTypeSymbolTable(const TypeSymbolTable &TST,
131 const ValueEnumerator &VE,
132 BitstreamWriter &Stream) {
133 if (TST.empty()) return;
135 Stream.EnterSubblock(bitc::TYPE_SYMTAB_BLOCK_ID, 3);
137 // FIXME: Set up the abbrev, we know how many types there are!
138 // FIXME: We know if the type names can use 7-bit ascii.
140 SmallVector<unsigned, 64> NameVals;
142 for (TypeSymbolTable::const_iterator TI = TST.begin(), TE = TST.end();
144 unsigned AbbrevToUse = 0;
146 // TST_ENTRY: [typeid, namelen, namechar x N]
147 NameVals.push_back(VE.getTypeID(TI->second));
149 const std::string &Str = TI->first;
150 NameVals.push_back(Str.size());
151 for (unsigned i = 0, e = Str.size(); i != e; ++i)
152 NameVals.push_back(Str[i]);
154 // Emit the finished record.
155 Stream.EmitRecord(bitc::TST_ENTRY_CODE, NameVals, AbbrevToUse);
162 static unsigned getEncodedLinkage(const GlobalValue *GV) {
163 switch (GV->getLinkage()) {
164 default: assert(0 && "Invalid linkage!");
165 case GlobalValue::ExternalLinkage: return 0;
166 case GlobalValue::WeakLinkage: return 1;
167 case GlobalValue::AppendingLinkage: return 2;
168 case GlobalValue::InternalLinkage: return 3;
169 case GlobalValue::LinkOnceLinkage: return 4;
170 case GlobalValue::DLLImportLinkage: return 5;
171 case GlobalValue::DLLExportLinkage: return 6;
172 case GlobalValue::ExternalWeakLinkage: return 7;
176 static unsigned getEncodedVisibility(const GlobalValue *GV) {
177 switch (GV->getVisibility()) {
178 default: assert(0 && "Invalid visibility!");
179 case GlobalValue::DefaultVisibility: return 0;
180 case GlobalValue::HiddenVisibility: return 1;
184 // Emit top-level description of module, including target triple, inline asm,
185 // descriptors for global variables, and function prototype info.
186 static void WriteModuleInfo(const Module *M, const ValueEnumerator &VE,
187 BitstreamWriter &Stream) {
188 // Emit the list of dependent libraries for the Module.
189 for (Module::lib_iterator I = M->lib_begin(), E = M->lib_end(); I != E; ++I)
190 WriteStringRecord(bitc::MODULE_CODE_DEPLIB, *I, 0/*TODO*/, Stream);
192 // Emit various pieces of data attached to a module.
193 if (!M->getTargetTriple().empty())
194 WriteStringRecord(bitc::MODULE_CODE_TRIPLE, M->getTargetTriple(),
196 if (!M->getDataLayout().empty())
197 WriteStringRecord(bitc::MODULE_CODE_DATALAYOUT, M->getDataLayout(),
199 if (!M->getModuleInlineAsm().empty())
200 WriteStringRecord(bitc::MODULE_CODE_ASM, M->getModuleInlineAsm(),
203 // Emit information about sections.
204 std::map<std::string, unsigned> SectionMap;
205 for (Module::const_global_iterator GV = M->global_begin(),E = M->global_end();
207 if (!GV->hasSection()) continue;
208 // Give section names unique ID's.
209 unsigned &Entry = SectionMap[GV->getSection()];
210 if (Entry != 0) continue;
211 WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, GV->getSection(),
213 Entry = SectionMap.size();
215 for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) {
216 if (!F->hasSection()) continue;
217 // Give section names unique ID's.
218 unsigned &Entry = SectionMap[F->getSection()];
219 if (Entry != 0) continue;
220 WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, F->getSection(),
222 Entry = SectionMap.size();
225 // TODO: Emit abbrev, now that we know # sections.
227 // Emit the global variable information.
228 SmallVector<unsigned, 64> Vals;
229 for (Module::const_global_iterator GV = M->global_begin(),E = M->global_end();
232 // GLOBALVAR: [type, isconst, initid,
233 // linkage, alignment, section, visibility, threadlocal]
234 Vals.push_back(VE.getTypeID(GV->getType()));
235 Vals.push_back(GV->isConstant());
236 Vals.push_back(GV->isDeclaration() ? 0 :
237 (VE.getValueID(GV->getInitializer()) + 1));
238 Vals.push_back(getEncodedLinkage(GV));
239 Vals.push_back(Log2_32(GV->getAlignment())+1);
240 Vals.push_back(GV->hasSection() ? SectionMap[GV->getSection()] : 0);
241 Vals.push_back(getEncodedVisibility(GV));
242 Vals.push_back(GV->isThreadLocal());
244 unsigned AbbrevToUse = 0;
245 Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse);
249 // Emit the function proto information.
250 for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) {
251 // FUNCTION: [type, callingconv, isproto, linkage, alignment, section,
253 Vals.push_back(VE.getTypeID(F->getType()));
254 Vals.push_back(F->getCallingConv());
255 Vals.push_back(F->isDeclaration());
256 Vals.push_back(getEncodedLinkage(F));
257 Vals.push_back(Log2_32(F->getAlignment())+1);
258 Vals.push_back(F->hasSection() ? SectionMap[F->getSection()] : 0);
259 Vals.push_back(getEncodedVisibility(F));
261 unsigned AbbrevToUse = 0;
262 Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse);
268 /// WriteModule - Emit the specified module to the bitstream.
269 static void WriteModule(const Module *M, BitstreamWriter &Stream) {
270 Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 2);
272 // Emit the version number if it is non-zero.
274 SmallVector<unsigned, 1> VersionVals;
275 VersionVals.push_back(CurVersion);
276 Stream.EmitRecord(bitc::MODULE_CODE_VERSION, VersionVals);
279 // Analyze the module, enumerating globals, functions, etc.
280 ValueEnumerator VE(M);
282 // Emit information describing all of the types in the module.
283 WriteTypeTable(VE, Stream);
285 // FIXME: Emit constants.
287 // Emit top-level description of module, including target triple, inline asm,
288 // descriptors for global variables, and function prototype info.
289 WriteModuleInfo(M, VE, Stream);
291 // Emit the type symbol table information.
292 WriteTypeSymbolTable(M->getTypeSymbolTable(), VE, Stream);
296 /// WriteBitcodeToFile - Write the specified module to the specified output
298 void llvm::WriteBitcodeToFile(const Module *M, std::ostream &Out) {
299 std::vector<unsigned char> Buffer;
300 BitstreamWriter Stream(Buffer);
302 Buffer.reserve(256*1024);
304 // Emit the file header.
305 Stream.Emit((unsigned)'B', 8);
306 Stream.Emit((unsigned)'C', 8);
313 WriteModule(M, Stream);
315 // Write the generated bitstream to "Out".
316 Out.write((char*)&Buffer.front(), Buffer.size());