1 //===--- Bitcode/Writer/BitcodeWriter.cpp - Bitcode Writer ----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // 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/Constants.h"
19 #include "llvm/DerivedTypes.h"
20 #include "llvm/InlineAsm.h"
21 #include "llvm/Instructions.h"
22 #include "llvm/MDNode.h"
23 #include "llvm/Module.h"
24 #include "llvm/TypeSymbolTable.h"
25 #include "llvm/ValueSymbolTable.h"
26 #include "llvm/Support/MathExtras.h"
27 #include "llvm/Support/Streams.h"
28 #include "llvm/Support/raw_ostream.h"
29 #include "llvm/System/Program.h"
32 /// These are manifest constants used by the bitcode writer. They do not need to
33 /// be kept in sync with the reader, but need to be consistent within this file.
37 // VALUE_SYMTAB_BLOCK abbrev id's.
38 VST_ENTRY_8_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
43 // CONSTANTS_BLOCK abbrev id's.
44 CONSTANTS_SETTYPE_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
45 CONSTANTS_INTEGER_ABBREV,
46 CONSTANTS_CE_CAST_Abbrev,
47 CONSTANTS_NULL_Abbrev,
49 // FUNCTION_BLOCK abbrev id's.
50 FUNCTION_INST_LOAD_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
51 FUNCTION_INST_BINOP_ABBREV,
52 FUNCTION_INST_CAST_ABBREV,
53 FUNCTION_INST_RET_VOID_ABBREV,
54 FUNCTION_INST_RET_VAL_ABBREV,
55 FUNCTION_INST_UNREACHABLE_ABBREV
59 static unsigned GetEncodedCastOpcode(unsigned Opcode) {
61 default: assert(0 && "Unknown cast instruction!");
62 case Instruction::Trunc : return bitc::CAST_TRUNC;
63 case Instruction::ZExt : return bitc::CAST_ZEXT;
64 case Instruction::SExt : return bitc::CAST_SEXT;
65 case Instruction::FPToUI : return bitc::CAST_FPTOUI;
66 case Instruction::FPToSI : return bitc::CAST_FPTOSI;
67 case Instruction::UIToFP : return bitc::CAST_UITOFP;
68 case Instruction::SIToFP : return bitc::CAST_SITOFP;
69 case Instruction::FPTrunc : return bitc::CAST_FPTRUNC;
70 case Instruction::FPExt : return bitc::CAST_FPEXT;
71 case Instruction::PtrToInt: return bitc::CAST_PTRTOINT;
72 case Instruction::IntToPtr: return bitc::CAST_INTTOPTR;
73 case Instruction::BitCast : return bitc::CAST_BITCAST;
77 static unsigned GetEncodedBinaryOpcode(unsigned Opcode) {
79 default: assert(0 && "Unknown binary instruction!");
80 case Instruction::Add:
81 case Instruction::FAdd: return bitc::BINOP_ADD;
82 case Instruction::Sub:
83 case Instruction::FSub: return bitc::BINOP_SUB;
84 case Instruction::Mul:
85 case Instruction::FMul: return bitc::BINOP_MUL;
86 case Instruction::UDiv: return bitc::BINOP_UDIV;
87 case Instruction::FDiv:
88 case Instruction::SDiv: return bitc::BINOP_SDIV;
89 case Instruction::URem: return bitc::BINOP_UREM;
90 case Instruction::FRem:
91 case Instruction::SRem: return bitc::BINOP_SREM;
92 case Instruction::Shl: return bitc::BINOP_SHL;
93 case Instruction::LShr: return bitc::BINOP_LSHR;
94 case Instruction::AShr: return bitc::BINOP_ASHR;
95 case Instruction::And: return bitc::BINOP_AND;
96 case Instruction::Or: return bitc::BINOP_OR;
97 case Instruction::Xor: return bitc::BINOP_XOR;
103 static void WriteStringRecord(unsigned Code, const std::string &Str,
104 unsigned AbbrevToUse, BitstreamWriter &Stream) {
105 SmallVector<unsigned, 64> Vals;
107 // Code: [strchar x N]
108 for (unsigned i = 0, e = Str.size(); i != e; ++i)
109 Vals.push_back(Str[i]);
111 // Emit the finished record.
112 Stream.EmitRecord(Code, Vals, AbbrevToUse);
115 // Emit information about parameter attributes.
116 static void WriteAttributeTable(const ValueEnumerator &VE,
117 BitstreamWriter &Stream) {
118 const std::vector<AttrListPtr> &Attrs = VE.getAttributes();
119 if (Attrs.empty()) return;
121 Stream.EnterSubblock(bitc::PARAMATTR_BLOCK_ID, 3);
123 SmallVector<uint64_t, 64> Record;
124 for (unsigned i = 0, e = Attrs.size(); i != e; ++i) {
125 const AttrListPtr &A = Attrs[i];
126 for (unsigned i = 0, e = A.getNumSlots(); i != e; ++i) {
127 const AttributeWithIndex &PAWI = A.getSlot(i);
128 Record.push_back(PAWI.Index);
130 // FIXME: remove in LLVM 3.0
131 // Store the alignment in the bitcode as a 16-bit raw value instead of a
132 // 5-bit log2 encoded value. Shift the bits above the alignment up by
134 uint64_t FauxAttr = PAWI.Attrs & 0xffff;
135 if (PAWI.Attrs & Attribute::Alignment)
136 FauxAttr |= (1ull<<16)<<(((PAWI.Attrs & Attribute::Alignment)-1) >> 16);
137 FauxAttr |= (PAWI.Attrs & (0x3FFull << 21)) << 11;
139 Record.push_back(FauxAttr);
142 Stream.EmitRecord(bitc::PARAMATTR_CODE_ENTRY, Record);
149 /// WriteTypeTable - Write out the type table for a module.
150 static void WriteTypeTable(const ValueEnumerator &VE, BitstreamWriter &Stream) {
151 const ValueEnumerator::TypeList &TypeList = VE.getTypes();
153 Stream.EnterSubblock(bitc::TYPE_BLOCK_ID, 4 /*count from # abbrevs */);
154 SmallVector<uint64_t, 64> TypeVals;
156 // Abbrev for TYPE_CODE_POINTER.
157 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
158 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_POINTER));
159 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
160 Log2_32_Ceil(VE.getTypes().size()+1)));
161 Abbv->Add(BitCodeAbbrevOp(0)); // Addrspace = 0
162 unsigned PtrAbbrev = Stream.EmitAbbrev(Abbv);
164 // Abbrev for TYPE_CODE_FUNCTION.
165 Abbv = new BitCodeAbbrev();
166 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_FUNCTION));
167 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // isvararg
168 Abbv->Add(BitCodeAbbrevOp(0)); // FIXME: DEAD value, remove in LLVM 3.0
169 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
170 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
171 Log2_32_Ceil(VE.getTypes().size()+1)));
172 unsigned FunctionAbbrev = Stream.EmitAbbrev(Abbv);
174 // Abbrev for TYPE_CODE_STRUCT.
175 Abbv = new BitCodeAbbrev();
176 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT));
177 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
178 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
179 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
180 Log2_32_Ceil(VE.getTypes().size()+1)));
181 unsigned StructAbbrev = Stream.EmitAbbrev(Abbv);
183 // Abbrev for TYPE_CODE_ARRAY.
184 Abbv = new BitCodeAbbrev();
185 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_ARRAY));
186 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // size
187 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
188 Log2_32_Ceil(VE.getTypes().size()+1)));
189 unsigned ArrayAbbrev = Stream.EmitAbbrev(Abbv);
191 // Emit an entry count so the reader can reserve space.
192 TypeVals.push_back(TypeList.size());
193 Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals);
196 // Loop over all of the types, emitting each in turn.
197 for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
198 const Type *T = TypeList[i].first;
202 switch (T->getTypeID()) {
203 default: assert(0 && "Unknown type!");
204 case Type::VoidTyID: Code = bitc::TYPE_CODE_VOID; break;
205 case Type::FloatTyID: Code = bitc::TYPE_CODE_FLOAT; break;
206 case Type::DoubleTyID: Code = bitc::TYPE_CODE_DOUBLE; break;
207 case Type::X86_FP80TyID: Code = bitc::TYPE_CODE_X86_FP80; break;
208 case Type::FP128TyID: Code = bitc::TYPE_CODE_FP128; break;
209 case Type::PPC_FP128TyID: Code = bitc::TYPE_CODE_PPC_FP128; break;
210 case Type::LabelTyID: Code = bitc::TYPE_CODE_LABEL; break;
211 case Type::OpaqueTyID: Code = bitc::TYPE_CODE_OPAQUE; break;
212 case Type::MetadataTyID: Code = bitc::TYPE_CODE_METADATA; break;
213 case Type::IntegerTyID:
215 Code = bitc::TYPE_CODE_INTEGER;
216 TypeVals.push_back(cast<IntegerType>(T)->getBitWidth());
218 case Type::PointerTyID: {
219 const PointerType *PTy = cast<PointerType>(T);
220 // POINTER: [pointee type, address space]
221 Code = bitc::TYPE_CODE_POINTER;
222 TypeVals.push_back(VE.getTypeID(PTy->getElementType()));
223 unsigned AddressSpace = PTy->getAddressSpace();
224 TypeVals.push_back(AddressSpace);
225 if (AddressSpace == 0) AbbrevToUse = PtrAbbrev;
228 case Type::FunctionTyID: {
229 const FunctionType *FT = cast<FunctionType>(T);
230 // FUNCTION: [isvararg, attrid, retty, paramty x N]
231 Code = bitc::TYPE_CODE_FUNCTION;
232 TypeVals.push_back(FT->isVarArg());
233 TypeVals.push_back(0); // FIXME: DEAD: remove in llvm 3.0
234 TypeVals.push_back(VE.getTypeID(FT->getReturnType()));
235 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
236 TypeVals.push_back(VE.getTypeID(FT->getParamType(i)));
237 AbbrevToUse = FunctionAbbrev;
240 case Type::StructTyID: {
241 const StructType *ST = cast<StructType>(T);
242 // STRUCT: [ispacked, eltty x N]
243 Code = bitc::TYPE_CODE_STRUCT;
244 TypeVals.push_back(ST->isPacked());
245 // Output all of the element types.
246 for (StructType::element_iterator I = ST->element_begin(),
247 E = ST->element_end(); I != E; ++I)
248 TypeVals.push_back(VE.getTypeID(*I));
249 AbbrevToUse = StructAbbrev;
252 case Type::ArrayTyID: {
253 const ArrayType *AT = cast<ArrayType>(T);
254 // ARRAY: [numelts, eltty]
255 Code = bitc::TYPE_CODE_ARRAY;
256 TypeVals.push_back(AT->getNumElements());
257 TypeVals.push_back(VE.getTypeID(AT->getElementType()));
258 AbbrevToUse = ArrayAbbrev;
261 case Type::VectorTyID: {
262 const VectorType *VT = cast<VectorType>(T);
263 // VECTOR [numelts, eltty]
264 Code = bitc::TYPE_CODE_VECTOR;
265 TypeVals.push_back(VT->getNumElements());
266 TypeVals.push_back(VE.getTypeID(VT->getElementType()));
271 // Emit the finished record.
272 Stream.EmitRecord(Code, TypeVals, AbbrevToUse);
279 static unsigned getEncodedLinkage(const GlobalValue *GV) {
280 switch (GV->getLinkage()) {
281 default: assert(0 && "Invalid linkage!");
282 case GlobalValue::GhostLinkage: // Map ghost linkage onto external.
283 case GlobalValue::ExternalLinkage: return 0;
284 case GlobalValue::WeakAnyLinkage: return 1;
285 case GlobalValue::AppendingLinkage: return 2;
286 case GlobalValue::InternalLinkage: return 3;
287 case GlobalValue::LinkOnceAnyLinkage: return 4;
288 case GlobalValue::DLLImportLinkage: return 5;
289 case GlobalValue::DLLExportLinkage: return 6;
290 case GlobalValue::ExternalWeakLinkage: return 7;
291 case GlobalValue::CommonLinkage: return 8;
292 case GlobalValue::PrivateLinkage: return 9;
293 case GlobalValue::WeakODRLinkage: return 10;
294 case GlobalValue::LinkOnceODRLinkage: return 11;
295 case GlobalValue::AvailableExternallyLinkage: return 12;
299 static unsigned getEncodedVisibility(const GlobalValue *GV) {
300 switch (GV->getVisibility()) {
301 default: assert(0 && "Invalid visibility!");
302 case GlobalValue::DefaultVisibility: return 0;
303 case GlobalValue::HiddenVisibility: return 1;
304 case GlobalValue::ProtectedVisibility: return 2;
308 // Emit top-level description of module, including target triple, inline asm,
309 // descriptors for global variables, and function prototype info.
310 static void WriteModuleInfo(const Module *M, const ValueEnumerator &VE,
311 BitstreamWriter &Stream) {
312 // Emit the list of dependent libraries for the Module.
313 for (Module::lib_iterator I = M->lib_begin(), E = M->lib_end(); I != E; ++I)
314 WriteStringRecord(bitc::MODULE_CODE_DEPLIB, *I, 0/*TODO*/, Stream);
316 // Emit various pieces of data attached to a module.
317 if (!M->getTargetTriple().empty())
318 WriteStringRecord(bitc::MODULE_CODE_TRIPLE, M->getTargetTriple(),
320 if (!M->getDataLayout().empty())
321 WriteStringRecord(bitc::MODULE_CODE_DATALAYOUT, M->getDataLayout(),
323 if (!M->getModuleInlineAsm().empty())
324 WriteStringRecord(bitc::MODULE_CODE_ASM, M->getModuleInlineAsm(),
327 // Emit information about sections and GC, computing how many there are. Also
328 // compute the maximum alignment value.
329 std::map<std::string, unsigned> SectionMap;
330 std::map<std::string, unsigned> GCMap;
331 unsigned MaxAlignment = 0;
332 unsigned MaxGlobalType = 0;
333 for (Module::const_global_iterator GV = M->global_begin(),E = M->global_end();
335 MaxAlignment = std::max(MaxAlignment, GV->getAlignment());
336 MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV->getType()));
338 if (!GV->hasSection()) continue;
339 // Give section names unique ID's.
340 unsigned &Entry = SectionMap[GV->getSection()];
341 if (Entry != 0) continue;
342 WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, GV->getSection(),
344 Entry = SectionMap.size();
346 for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) {
347 MaxAlignment = std::max(MaxAlignment, F->getAlignment());
348 if (F->hasSection()) {
349 // Give section names unique ID's.
350 unsigned &Entry = SectionMap[F->getSection()];
352 WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, F->getSection(),
354 Entry = SectionMap.size();
358 // Same for GC names.
359 unsigned &Entry = GCMap[F->getGC()];
361 WriteStringRecord(bitc::MODULE_CODE_GCNAME, F->getGC(),
363 Entry = GCMap.size();
368 // Emit abbrev for globals, now that we know # sections and max alignment.
369 unsigned SimpleGVarAbbrev = 0;
370 if (!M->global_empty()) {
371 // Add an abbrev for common globals with no visibility or thread localness.
372 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
373 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GLOBALVAR));
374 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
375 Log2_32_Ceil(MaxGlobalType+1)));
376 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Constant.
377 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Initializer.
378 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // Linkage.
379 if (MaxAlignment == 0) // Alignment.
380 Abbv->Add(BitCodeAbbrevOp(0));
382 unsigned MaxEncAlignment = Log2_32(MaxAlignment)+1;
383 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
384 Log2_32_Ceil(MaxEncAlignment+1)));
386 if (SectionMap.empty()) // Section.
387 Abbv->Add(BitCodeAbbrevOp(0));
389 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
390 Log2_32_Ceil(SectionMap.size()+1)));
391 // Don't bother emitting vis + thread local.
392 SimpleGVarAbbrev = Stream.EmitAbbrev(Abbv);
395 // Emit the global variable information.
396 SmallVector<unsigned, 64> Vals;
397 for (Module::const_global_iterator GV = M->global_begin(),E = M->global_end();
399 unsigned AbbrevToUse = 0;
401 // GLOBALVAR: [type, isconst, initid,
402 // linkage, alignment, section, visibility, threadlocal]
403 Vals.push_back(VE.getTypeID(GV->getType()));
404 Vals.push_back(GV->isConstant());
405 Vals.push_back(GV->isDeclaration() ? 0 :
406 (VE.getValueID(GV->getInitializer()) + 1));
407 Vals.push_back(getEncodedLinkage(GV));
408 Vals.push_back(Log2_32(GV->getAlignment())+1);
409 Vals.push_back(GV->hasSection() ? SectionMap[GV->getSection()] : 0);
410 if (GV->isThreadLocal() ||
411 GV->getVisibility() != GlobalValue::DefaultVisibility) {
412 Vals.push_back(getEncodedVisibility(GV));
413 Vals.push_back(GV->isThreadLocal());
415 AbbrevToUse = SimpleGVarAbbrev;
418 Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse);
422 // Emit the function proto information.
423 for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) {
424 // FUNCTION: [type, callingconv, isproto, paramattr,
425 // linkage, alignment, section, visibility, gc]
426 Vals.push_back(VE.getTypeID(F->getType()));
427 Vals.push_back(F->getCallingConv());
428 Vals.push_back(F->isDeclaration());
429 Vals.push_back(getEncodedLinkage(F));
430 Vals.push_back(VE.getAttributeID(F->getAttributes()));
431 Vals.push_back(Log2_32(F->getAlignment())+1);
432 Vals.push_back(F->hasSection() ? SectionMap[F->getSection()] : 0);
433 Vals.push_back(getEncodedVisibility(F));
434 Vals.push_back(F->hasGC() ? GCMap[F->getGC()] : 0);
436 unsigned AbbrevToUse = 0;
437 Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse);
442 // Emit the alias information.
443 for (Module::const_alias_iterator AI = M->alias_begin(), E = M->alias_end();
445 Vals.push_back(VE.getTypeID(AI->getType()));
446 Vals.push_back(VE.getValueID(AI->getAliasee()));
447 Vals.push_back(getEncodedLinkage(AI));
448 Vals.push_back(getEncodedVisibility(AI));
449 unsigned AbbrevToUse = 0;
450 Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse);
456 static void WriteConstants(unsigned FirstVal, unsigned LastVal,
457 const ValueEnumerator &VE,
458 BitstreamWriter &Stream, bool isGlobal) {
459 if (FirstVal == LastVal) return;
461 Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 4);
463 unsigned AggregateAbbrev = 0;
464 unsigned String8Abbrev = 0;
465 unsigned CString7Abbrev = 0;
466 unsigned CString6Abbrev = 0;
467 unsigned MDString8Abbrev = 0;
468 unsigned MDString6Abbrev = 0;
469 // If this is a constant pool for the module, emit module-specific abbrevs.
471 // Abbrev for CST_CODE_AGGREGATE.
472 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
473 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_AGGREGATE));
474 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
475 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal+1)));
476 AggregateAbbrev = Stream.EmitAbbrev(Abbv);
478 // Abbrev for CST_CODE_STRING.
479 Abbv = new BitCodeAbbrev();
480 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_STRING));
481 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
482 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
483 String8Abbrev = Stream.EmitAbbrev(Abbv);
484 // Abbrev for CST_CODE_CSTRING.
485 Abbv = new BitCodeAbbrev();
486 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
487 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
488 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
489 CString7Abbrev = Stream.EmitAbbrev(Abbv);
490 // Abbrev for CST_CODE_CSTRING.
491 Abbv = new BitCodeAbbrev();
492 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
493 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
494 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
495 CString6Abbrev = Stream.EmitAbbrev(Abbv);
497 // Abbrev for CST_CODE_MDSTRING.
498 Abbv = new BitCodeAbbrev();
499 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_MDSTRING));
500 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
501 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
502 MDString8Abbrev = Stream.EmitAbbrev(Abbv);
503 // Abbrev for CST_CODE_MDSTRING.
504 Abbv = new BitCodeAbbrev();
505 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_MDSTRING));
506 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
507 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
508 MDString6Abbrev = Stream.EmitAbbrev(Abbv);
511 SmallVector<uint64_t, 64> Record;
513 const ValueEnumerator::ValueList &Vals = VE.getValues();
514 const Type *LastTy = 0;
515 for (unsigned i = FirstVal; i != LastVal; ++i) {
516 const Value *V = Vals[i].first;
517 // If we need to switch types, do so now.
518 if (V->getType() != LastTy) {
519 LastTy = V->getType();
520 Record.push_back(VE.getTypeID(LastTy));
521 Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record,
522 CONSTANTS_SETTYPE_ABBREV);
526 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
527 Record.push_back(unsigned(IA->hasSideEffects()));
529 // Add the asm string.
530 const std::string &AsmStr = IA->getAsmString();
531 Record.push_back(AsmStr.size());
532 for (unsigned i = 0, e = AsmStr.size(); i != e; ++i)
533 Record.push_back(AsmStr[i]);
535 // Add the constraint string.
536 const std::string &ConstraintStr = IA->getConstraintString();
537 Record.push_back(ConstraintStr.size());
538 for (unsigned i = 0, e = ConstraintStr.size(); i != e; ++i)
539 Record.push_back(ConstraintStr[i]);
540 Stream.EmitRecord(bitc::CST_CODE_INLINEASM, Record);
544 const Constant *C = cast<Constant>(V);
546 unsigned AbbrevToUse = 0;
547 if (C->isNullValue()) {
548 Code = bitc::CST_CODE_NULL;
549 } else if (isa<UndefValue>(C)) {
550 Code = bitc::CST_CODE_UNDEF;
551 } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {
552 if (IV->getBitWidth() <= 64) {
553 int64_t V = IV->getSExtValue();
555 Record.push_back(V << 1);
557 Record.push_back((-V << 1) | 1);
558 Code = bitc::CST_CODE_INTEGER;
559 AbbrevToUse = CONSTANTS_INTEGER_ABBREV;
560 } else { // Wide integers, > 64 bits in size.
561 // We have an arbitrary precision integer value to write whose
562 // bit width is > 64. However, in canonical unsigned integer
563 // format it is likely that the high bits are going to be zero.
564 // So, we only write the number of active words.
565 unsigned NWords = IV->getValue().getActiveWords();
566 const uint64_t *RawWords = IV->getValue().getRawData();
567 for (unsigned i = 0; i != NWords; ++i) {
568 int64_t V = RawWords[i];
570 Record.push_back(V << 1);
572 Record.push_back((-V << 1) | 1);
574 Code = bitc::CST_CODE_WIDE_INTEGER;
576 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
577 Code = bitc::CST_CODE_FLOAT;
578 const Type *Ty = CFP->getType();
579 if (Ty == Type::FloatTy || Ty == Type::DoubleTy) {
580 Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
581 } else if (Ty == Type::X86_FP80Ty) {
582 // api needed to prevent premature destruction
583 // bits are not in the same order as a normal i80 APInt, compensate.
584 APInt api = CFP->getValueAPF().bitcastToAPInt();
585 const uint64_t *p = api.getRawData();
586 Record.push_back((p[1] << 48) | (p[0] >> 16));
587 Record.push_back(p[0] & 0xffffLL);
588 } else if (Ty == Type::FP128Ty || Ty == Type::PPC_FP128Ty) {
589 APInt api = CFP->getValueAPF().bitcastToAPInt();
590 const uint64_t *p = api.getRawData();
591 Record.push_back(p[0]);
592 Record.push_back(p[1]);
594 assert (0 && "Unknown FP type!");
596 } else if (isa<ConstantArray>(C) && cast<ConstantArray>(C)->isString()) {
597 // Emit constant strings specially.
598 unsigned NumOps = C->getNumOperands();
599 // If this is a null-terminated string, use the denser CSTRING encoding.
600 if (C->getOperand(NumOps-1)->isNullValue()) {
601 Code = bitc::CST_CODE_CSTRING;
602 --NumOps; // Don't encode the null, which isn't allowed by char6.
604 Code = bitc::CST_CODE_STRING;
605 AbbrevToUse = String8Abbrev;
607 bool isCStr7 = Code == bitc::CST_CODE_CSTRING;
608 bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING;
609 for (unsigned i = 0; i != NumOps; ++i) {
610 unsigned char V = cast<ConstantInt>(C->getOperand(i))->getZExtValue();
612 isCStr7 &= (V & 128) == 0;
614 isCStrChar6 = BitCodeAbbrevOp::isChar6(V);
618 AbbrevToUse = CString6Abbrev;
620 AbbrevToUse = CString7Abbrev;
621 } else if (isa<ConstantArray>(C) || isa<ConstantStruct>(V) ||
622 isa<ConstantVector>(V)) {
623 Code = bitc::CST_CODE_AGGREGATE;
624 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i)
625 Record.push_back(VE.getValueID(C->getOperand(i)));
626 AbbrevToUse = AggregateAbbrev;
627 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
628 switch (CE->getOpcode()) {
630 if (Instruction::isCast(CE->getOpcode())) {
631 Code = bitc::CST_CODE_CE_CAST;
632 Record.push_back(GetEncodedCastOpcode(CE->getOpcode()));
633 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
634 Record.push_back(VE.getValueID(C->getOperand(0)));
635 AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;
637 assert(CE->getNumOperands() == 2 && "Unknown constant expr!");
638 Code = bitc::CST_CODE_CE_BINOP;
639 Record.push_back(GetEncodedBinaryOpcode(CE->getOpcode()));
640 Record.push_back(VE.getValueID(C->getOperand(0)));
641 Record.push_back(VE.getValueID(C->getOperand(1)));
644 case Instruction::GetElementPtr:
645 Code = bitc::CST_CODE_CE_GEP;
646 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
647 Record.push_back(VE.getTypeID(C->getOperand(i)->getType()));
648 Record.push_back(VE.getValueID(C->getOperand(i)));
651 case Instruction::Select:
652 Code = bitc::CST_CODE_CE_SELECT;
653 Record.push_back(VE.getValueID(C->getOperand(0)));
654 Record.push_back(VE.getValueID(C->getOperand(1)));
655 Record.push_back(VE.getValueID(C->getOperand(2)));
657 case Instruction::ExtractElement:
658 Code = bitc::CST_CODE_CE_EXTRACTELT;
659 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
660 Record.push_back(VE.getValueID(C->getOperand(0)));
661 Record.push_back(VE.getValueID(C->getOperand(1)));
663 case Instruction::InsertElement:
664 Code = bitc::CST_CODE_CE_INSERTELT;
665 Record.push_back(VE.getValueID(C->getOperand(0)));
666 Record.push_back(VE.getValueID(C->getOperand(1)));
667 Record.push_back(VE.getValueID(C->getOperand(2)));
669 case Instruction::ShuffleVector:
670 // If the return type and argument types are the same, this is a
671 // standard shufflevector instruction. If the types are different,
672 // then the shuffle is widening or truncating the input vectors, and
673 // the argument type must also be encoded.
674 if (C->getType() == C->getOperand(0)->getType()) {
675 Code = bitc::CST_CODE_CE_SHUFFLEVEC;
677 Code = bitc::CST_CODE_CE_SHUFVEC_EX;
678 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
680 Record.push_back(VE.getValueID(C->getOperand(0)));
681 Record.push_back(VE.getValueID(C->getOperand(1)));
682 Record.push_back(VE.getValueID(C->getOperand(2)));
684 case Instruction::ICmp:
685 case Instruction::FCmp:
686 case Instruction::VICmp:
687 case Instruction::VFCmp:
688 if (isa<VectorType>(C->getOperand(0)->getType())
689 && (CE->getOpcode() == Instruction::ICmp
690 || CE->getOpcode() == Instruction::FCmp)) {
691 // compare returning vector of Int1Ty
692 assert(0 && "Unsupported constant!");
694 Code = bitc::CST_CODE_CE_CMP;
696 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
697 Record.push_back(VE.getValueID(C->getOperand(0)));
698 Record.push_back(VE.getValueID(C->getOperand(1)));
699 Record.push_back(CE->getPredicate());
702 } else if (const MDString *S = dyn_cast<MDString>(C)) {
703 Code = bitc::CST_CODE_MDSTRING;
704 AbbrevToUse = MDString6Abbrev;
705 for (unsigned i = 0, e = S->size(); i != e; ++i) {
706 char V = S->begin()[i];
709 if (!BitCodeAbbrevOp::isChar6(V))
710 AbbrevToUse = MDString8Abbrev;
712 } else if (const MDNode *N = dyn_cast<MDNode>(C)) {
713 Code = bitc::CST_CODE_MDNODE;
714 for (unsigned i = 0, e = N->getNumElements(); i != e; ++i) {
715 if (N->getElement(i)) {
716 Record.push_back(VE.getTypeID(N->getElement(i)->getType()));
717 Record.push_back(VE.getValueID(N->getElement(i)));
719 Record.push_back(VE.getTypeID(Type::VoidTy));
724 assert(0 && "Unknown constant!");
726 Stream.EmitRecord(Code, Record, AbbrevToUse);
733 static void WriteModuleConstants(const ValueEnumerator &VE,
734 BitstreamWriter &Stream) {
735 const ValueEnumerator::ValueList &Vals = VE.getValues();
737 // Find the first constant to emit, which is the first non-globalvalue value.
738 // We know globalvalues have been emitted by WriteModuleInfo.
739 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
740 if (!isa<GlobalValue>(Vals[i].first)) {
741 WriteConstants(i, Vals.size(), VE, Stream, true);
747 /// PushValueAndType - The file has to encode both the value and type id for
748 /// many values, because we need to know what type to create for forward
749 /// references. However, most operands are not forward references, so this type
750 /// field is not needed.
752 /// This function adds V's value ID to Vals. If the value ID is higher than the
753 /// instruction ID, then it is a forward reference, and it also includes the
755 static bool PushValueAndType(const Value *V, unsigned InstID,
756 SmallVector<unsigned, 64> &Vals,
757 ValueEnumerator &VE) {
758 unsigned ValID = VE.getValueID(V);
759 Vals.push_back(ValID);
760 if (ValID >= InstID) {
761 Vals.push_back(VE.getTypeID(V->getType()));
767 /// WriteInstruction - Emit an instruction to the specified stream.
768 static void WriteInstruction(const Instruction &I, unsigned InstID,
769 ValueEnumerator &VE, BitstreamWriter &Stream,
770 SmallVector<unsigned, 64> &Vals) {
772 unsigned AbbrevToUse = 0;
773 switch (I.getOpcode()) {
775 if (Instruction::isCast(I.getOpcode())) {
776 Code = bitc::FUNC_CODE_INST_CAST;
777 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
778 AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
779 Vals.push_back(VE.getTypeID(I.getType()));
780 Vals.push_back(GetEncodedCastOpcode(I.getOpcode()));
782 assert(isa<BinaryOperator>(I) && "Unknown instruction!");
783 Code = bitc::FUNC_CODE_INST_BINOP;
784 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
785 AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
786 Vals.push_back(VE.getValueID(I.getOperand(1)));
787 Vals.push_back(GetEncodedBinaryOpcode(I.getOpcode()));
791 case Instruction::GetElementPtr:
792 Code = bitc::FUNC_CODE_INST_GEP;
793 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
794 PushValueAndType(I.getOperand(i), InstID, Vals, VE);
796 case Instruction::ExtractValue: {
797 Code = bitc::FUNC_CODE_INST_EXTRACTVAL;
798 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
799 const ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
800 for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
804 case Instruction::InsertValue: {
805 Code = bitc::FUNC_CODE_INST_INSERTVAL;
806 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
807 PushValueAndType(I.getOperand(1), InstID, Vals, VE);
808 const InsertValueInst *IVI = cast<InsertValueInst>(&I);
809 for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
813 case Instruction::Select:
814 Code = bitc::FUNC_CODE_INST_VSELECT;
815 PushValueAndType(I.getOperand(1), InstID, Vals, VE);
816 Vals.push_back(VE.getValueID(I.getOperand(2)));
817 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
819 case Instruction::ExtractElement:
820 Code = bitc::FUNC_CODE_INST_EXTRACTELT;
821 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
822 Vals.push_back(VE.getValueID(I.getOperand(1)));
824 case Instruction::InsertElement:
825 Code = bitc::FUNC_CODE_INST_INSERTELT;
826 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
827 Vals.push_back(VE.getValueID(I.getOperand(1)));
828 Vals.push_back(VE.getValueID(I.getOperand(2)));
830 case Instruction::ShuffleVector:
831 Code = bitc::FUNC_CODE_INST_SHUFFLEVEC;
832 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
833 Vals.push_back(VE.getValueID(I.getOperand(1)));
834 Vals.push_back(VE.getValueID(I.getOperand(2)));
836 case Instruction::ICmp:
837 case Instruction::FCmp:
838 case Instruction::VICmp:
839 case Instruction::VFCmp:
840 if (I.getOpcode() == Instruction::ICmp
841 || I.getOpcode() == Instruction::FCmp) {
842 // compare returning Int1Ty or vector of Int1Ty
843 Code = bitc::FUNC_CODE_INST_CMP2;
845 Code = bitc::FUNC_CODE_INST_CMP;
847 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
848 Vals.push_back(VE.getValueID(I.getOperand(1)));
849 Vals.push_back(cast<CmpInst>(I).getPredicate());
852 case Instruction::Ret:
854 Code = bitc::FUNC_CODE_INST_RET;
855 unsigned NumOperands = I.getNumOperands();
856 if (NumOperands == 0)
857 AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
858 else if (NumOperands == 1) {
859 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
860 AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
862 for (unsigned i = 0, e = NumOperands; i != e; ++i)
863 PushValueAndType(I.getOperand(i), InstID, Vals, VE);
867 case Instruction::Br:
869 Code = bitc::FUNC_CODE_INST_BR;
870 BranchInst &II(cast<BranchInst>(I));
871 Vals.push_back(VE.getValueID(II.getSuccessor(0)));
872 if (II.isConditional()) {
873 Vals.push_back(VE.getValueID(II.getSuccessor(1)));
874 Vals.push_back(VE.getValueID(II.getCondition()));
878 case Instruction::Switch:
879 Code = bitc::FUNC_CODE_INST_SWITCH;
880 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
881 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
882 Vals.push_back(VE.getValueID(I.getOperand(i)));
884 case Instruction::Invoke: {
885 const InvokeInst *II = cast<InvokeInst>(&I);
886 const Value *Callee(II->getCalledValue());
887 const PointerType *PTy = cast<PointerType>(Callee->getType());
888 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
889 Code = bitc::FUNC_CODE_INST_INVOKE;
891 Vals.push_back(VE.getAttributeID(II->getAttributes()));
892 Vals.push_back(II->getCallingConv());
893 Vals.push_back(VE.getValueID(II->getNormalDest()));
894 Vals.push_back(VE.getValueID(II->getUnwindDest()));
895 PushValueAndType(Callee, InstID, Vals, VE);
897 // Emit value #'s for the fixed parameters.
898 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
899 Vals.push_back(VE.getValueID(I.getOperand(i+3))); // fixed param.
901 // Emit type/value pairs for varargs params.
902 if (FTy->isVarArg()) {
903 for (unsigned i = 3+FTy->getNumParams(), e = I.getNumOperands();
905 PushValueAndType(I.getOperand(i), InstID, Vals, VE); // vararg
909 case Instruction::Unwind:
910 Code = bitc::FUNC_CODE_INST_UNWIND;
912 case Instruction::Unreachable:
913 Code = bitc::FUNC_CODE_INST_UNREACHABLE;
914 AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
917 case Instruction::PHI:
918 Code = bitc::FUNC_CODE_INST_PHI;
919 Vals.push_back(VE.getTypeID(I.getType()));
920 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
921 Vals.push_back(VE.getValueID(I.getOperand(i)));
924 case Instruction::Malloc:
925 Code = bitc::FUNC_CODE_INST_MALLOC;
926 Vals.push_back(VE.getTypeID(I.getType()));
927 Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
928 Vals.push_back(Log2_32(cast<MallocInst>(I).getAlignment())+1);
931 case Instruction::Free:
932 Code = bitc::FUNC_CODE_INST_FREE;
933 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
936 case Instruction::Alloca:
937 Code = bitc::FUNC_CODE_INST_ALLOCA;
938 Vals.push_back(VE.getTypeID(I.getType()));
939 Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
940 Vals.push_back(Log2_32(cast<AllocaInst>(I).getAlignment())+1);
943 case Instruction::Load:
944 Code = bitc::FUNC_CODE_INST_LOAD;
945 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE)) // ptr
946 AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
948 Vals.push_back(Log2_32(cast<LoadInst>(I).getAlignment())+1);
949 Vals.push_back(cast<LoadInst>(I).isVolatile());
951 case Instruction::Store:
952 Code = bitc::FUNC_CODE_INST_STORE2;
953 PushValueAndType(I.getOperand(1), InstID, Vals, VE); // ptrty + ptr
954 Vals.push_back(VE.getValueID(I.getOperand(0))); // val.
955 Vals.push_back(Log2_32(cast<StoreInst>(I).getAlignment())+1);
956 Vals.push_back(cast<StoreInst>(I).isVolatile());
958 case Instruction::Call: {
959 const PointerType *PTy = cast<PointerType>(I.getOperand(0)->getType());
960 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
962 Code = bitc::FUNC_CODE_INST_CALL;
964 const CallInst *CI = cast<CallInst>(&I);
965 Vals.push_back(VE.getAttributeID(CI->getAttributes()));
966 Vals.push_back((CI->getCallingConv() << 1) | unsigned(CI->isTailCall()));
967 PushValueAndType(CI->getOperand(0), InstID, Vals, VE); // Callee
969 // Emit value #'s for the fixed parameters.
970 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
971 Vals.push_back(VE.getValueID(I.getOperand(i+1))); // fixed param.
973 // Emit type/value pairs for varargs params.
974 if (FTy->isVarArg()) {
975 unsigned NumVarargs = I.getNumOperands()-1-FTy->getNumParams();
976 for (unsigned i = I.getNumOperands()-NumVarargs, e = I.getNumOperands();
978 PushValueAndType(I.getOperand(i), InstID, Vals, VE); // varargs
982 case Instruction::VAArg:
983 Code = bitc::FUNC_CODE_INST_VAARG;
984 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); // valistty
985 Vals.push_back(VE.getValueID(I.getOperand(0))); // valist.
986 Vals.push_back(VE.getTypeID(I.getType())); // restype.
990 Stream.EmitRecord(Code, Vals, AbbrevToUse);
994 // Emit names for globals/functions etc.
995 static void WriteValueSymbolTable(const ValueSymbolTable &VST,
996 const ValueEnumerator &VE,
997 BitstreamWriter &Stream) {
998 if (VST.empty()) return;
999 Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
1001 // FIXME: Set up the abbrev, we know how many values there are!
1002 // FIXME: We know if the type names can use 7-bit ascii.
1003 SmallVector<unsigned, 64> NameVals;
1005 for (ValueSymbolTable::const_iterator SI = VST.begin(), SE = VST.end();
1008 const ValueName &Name = *SI;
1010 // Figure out the encoding to use for the name.
1012 bool isChar6 = true;
1013 for (const char *C = Name.getKeyData(), *E = C+Name.getKeyLength();
1016 isChar6 = BitCodeAbbrevOp::isChar6(*C);
1017 if ((unsigned char)*C & 128) {
1019 break; // don't bother scanning the rest.
1023 unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
1025 // VST_ENTRY: [valueid, namechar x N]
1026 // VST_BBENTRY: [bbid, namechar x N]
1028 if (isa<BasicBlock>(SI->getValue())) {
1029 Code = bitc::VST_CODE_BBENTRY;
1031 AbbrevToUse = VST_BBENTRY_6_ABBREV;
1033 Code = bitc::VST_CODE_ENTRY;
1035 AbbrevToUse = VST_ENTRY_6_ABBREV;
1037 AbbrevToUse = VST_ENTRY_7_ABBREV;
1040 NameVals.push_back(VE.getValueID(SI->getValue()));
1041 for (const char *P = Name.getKeyData(),
1042 *E = Name.getKeyData()+Name.getKeyLength(); P != E; ++P)
1043 NameVals.push_back((unsigned char)*P);
1045 // Emit the finished record.
1046 Stream.EmitRecord(Code, NameVals, AbbrevToUse);
1052 /// WriteFunction - Emit a function body to the module stream.
1053 static void WriteFunction(const Function &F, ValueEnumerator &VE,
1054 BitstreamWriter &Stream) {
1055 Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 4);
1056 VE.incorporateFunction(F);
1058 SmallVector<unsigned, 64> Vals;
1060 // Emit the number of basic blocks, so the reader can create them ahead of
1062 Vals.push_back(VE.getBasicBlocks().size());
1063 Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals);
1066 // If there are function-local constants, emit them now.
1067 unsigned CstStart, CstEnd;
1068 VE.getFunctionConstantRange(CstStart, CstEnd);
1069 WriteConstants(CstStart, CstEnd, VE, Stream, false);
1071 // Keep a running idea of what the instruction ID is.
1072 unsigned InstID = CstEnd;
1074 // Finally, emit all the instructions, in order.
1075 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1076 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
1078 WriteInstruction(*I, InstID, VE, Stream, Vals);
1079 if (I->getType() != Type::VoidTy)
1083 // Emit names for all the instructions etc.
1084 WriteValueSymbolTable(F.getValueSymbolTable(), VE, Stream);
1090 /// WriteTypeSymbolTable - Emit a block for the specified type symtab.
1091 static void WriteTypeSymbolTable(const TypeSymbolTable &TST,
1092 const ValueEnumerator &VE,
1093 BitstreamWriter &Stream) {
1094 if (TST.empty()) return;
1096 Stream.EnterSubblock(bitc::TYPE_SYMTAB_BLOCK_ID, 3);
1098 // 7-bit fixed width VST_CODE_ENTRY strings.
1099 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1100 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
1101 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
1102 Log2_32_Ceil(VE.getTypes().size()+1)));
1103 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1104 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
1105 unsigned V7Abbrev = Stream.EmitAbbrev(Abbv);
1107 SmallVector<unsigned, 64> NameVals;
1109 for (TypeSymbolTable::const_iterator TI = TST.begin(), TE = TST.end();
1111 // TST_ENTRY: [typeid, namechar x N]
1112 NameVals.push_back(VE.getTypeID(TI->second));
1114 const std::string &Str = TI->first;
1116 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
1117 NameVals.push_back((unsigned char)Str[i]);
1122 // Emit the finished record.
1123 Stream.EmitRecord(bitc::VST_CODE_ENTRY, NameVals, is7Bit ? V7Abbrev : 0);
1130 // Emit blockinfo, which defines the standard abbreviations etc.
1131 static void WriteBlockInfo(const ValueEnumerator &VE, BitstreamWriter &Stream) {
1132 // We only want to emit block info records for blocks that have multiple
1133 // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK. Other
1134 // blocks can defined their abbrevs inline.
1135 Stream.EnterBlockInfoBlock(2);
1137 { // 8-bit fixed-width VST_ENTRY/VST_BBENTRY strings.
1138 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1139 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3));
1140 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1141 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1142 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
1143 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1144 Abbv) != VST_ENTRY_8_ABBREV)
1145 assert(0 && "Unexpected abbrev ordering!");
1148 { // 7-bit fixed width VST_ENTRY strings.
1149 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1150 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
1151 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1152 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1153 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
1154 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1155 Abbv) != VST_ENTRY_7_ABBREV)
1156 assert(0 && "Unexpected abbrev ordering!");
1158 { // 6-bit char6 VST_ENTRY strings.
1159 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1160 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
1161 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1162 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1163 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
1164 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1165 Abbv) != VST_ENTRY_6_ABBREV)
1166 assert(0 && "Unexpected abbrev ordering!");
1168 { // 6-bit char6 VST_BBENTRY strings.
1169 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1170 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY));
1171 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1172 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1173 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
1174 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1175 Abbv) != VST_BBENTRY_6_ABBREV)
1176 assert(0 && "Unexpected abbrev ordering!");
1181 { // SETTYPE abbrev for CONSTANTS_BLOCK.
1182 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1183 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_SETTYPE));
1184 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
1185 Log2_32_Ceil(VE.getTypes().size()+1)));
1186 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1187 Abbv) != CONSTANTS_SETTYPE_ABBREV)
1188 assert(0 && "Unexpected abbrev ordering!");
1191 { // INTEGER abbrev for CONSTANTS_BLOCK.
1192 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1193 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_INTEGER));
1194 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1195 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1196 Abbv) != CONSTANTS_INTEGER_ABBREV)
1197 assert(0 && "Unexpected abbrev ordering!");
1200 { // CE_CAST abbrev for CONSTANTS_BLOCK.
1201 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1202 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CE_CAST));
1203 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // cast opc
1204 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // typeid
1205 Log2_32_Ceil(VE.getTypes().size()+1)));
1206 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
1208 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1209 Abbv) != CONSTANTS_CE_CAST_Abbrev)
1210 assert(0 && "Unexpected abbrev ordering!");
1212 { // NULL abbrev for CONSTANTS_BLOCK.
1213 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1214 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_NULL));
1215 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1216 Abbv) != CONSTANTS_NULL_Abbrev)
1217 assert(0 && "Unexpected abbrev ordering!");
1220 // FIXME: This should only use space for first class types!
1222 { // INST_LOAD abbrev for FUNCTION_BLOCK.
1223 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1224 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_LOAD));
1225 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Ptr
1226 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align
1227 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile
1228 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1229 Abbv) != FUNCTION_INST_LOAD_ABBREV)
1230 assert(0 && "Unexpected abbrev ordering!");
1232 { // INST_BINOP abbrev for FUNCTION_BLOCK.
1233 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1234 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
1235 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
1236 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
1237 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
1238 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1239 Abbv) != FUNCTION_INST_BINOP_ABBREV)
1240 assert(0 && "Unexpected abbrev ordering!");
1242 { // INST_CAST abbrev for FUNCTION_BLOCK.
1243 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1244 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST));
1245 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // OpVal
1246 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
1247 Log2_32_Ceil(VE.getTypes().size()+1)));
1248 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
1249 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1250 Abbv) != FUNCTION_INST_CAST_ABBREV)
1251 assert(0 && "Unexpected abbrev ordering!");
1254 { // INST_RET abbrev for FUNCTION_BLOCK.
1255 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1256 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
1257 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1258 Abbv) != FUNCTION_INST_RET_VOID_ABBREV)
1259 assert(0 && "Unexpected abbrev ordering!");
1261 { // INST_RET abbrev for FUNCTION_BLOCK.
1262 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1263 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
1264 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ValID
1265 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1266 Abbv) != FUNCTION_INST_RET_VAL_ABBREV)
1267 assert(0 && "Unexpected abbrev ordering!");
1269 { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK.
1270 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1271 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNREACHABLE));
1272 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1273 Abbv) != FUNCTION_INST_UNREACHABLE_ABBREV)
1274 assert(0 && "Unexpected abbrev ordering!");
1281 /// WriteModule - Emit the specified module to the bitstream.
1282 static void WriteModule(const Module *M, BitstreamWriter &Stream) {
1283 Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
1285 // Emit the version number if it is non-zero.
1287 SmallVector<unsigned, 1> Vals;
1288 Vals.push_back(CurVersion);
1289 Stream.EmitRecord(bitc::MODULE_CODE_VERSION, Vals);
1292 // Analyze the module, enumerating globals, functions, etc.
1293 ValueEnumerator VE(M);
1295 // Emit blockinfo, which defines the standard abbreviations etc.
1296 WriteBlockInfo(VE, Stream);
1298 // Emit information about parameter attributes.
1299 WriteAttributeTable(VE, Stream);
1301 // Emit information describing all of the types in the module.
1302 WriteTypeTable(VE, Stream);
1304 // Emit top-level description of module, including target triple, inline asm,
1305 // descriptors for global variables, and function prototype info.
1306 WriteModuleInfo(M, VE, Stream);
1309 WriteModuleConstants(VE, Stream);
1311 // If we have any aggregate values in the value table, purge them - these can
1312 // only be used to initialize global variables. Doing so makes the value
1313 // namespace smaller for code in functions.
1314 int NumNonAggregates = VE.PurgeAggregateValues();
1315 if (NumNonAggregates != -1) {
1316 SmallVector<unsigned, 1> Vals;
1317 Vals.push_back(NumNonAggregates);
1318 Stream.EmitRecord(bitc::MODULE_CODE_PURGEVALS, Vals);
1321 // Emit function bodies.
1322 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
1323 if (!I->isDeclaration())
1324 WriteFunction(*I, VE, Stream);
1326 // Emit the type symbol table information.
1327 WriteTypeSymbolTable(M->getTypeSymbolTable(), VE, Stream);
1329 // Emit names for globals/functions etc.
1330 WriteValueSymbolTable(M->getValueSymbolTable(), VE, Stream);
1335 /// EmitDarwinBCHeader - If generating a bc file on darwin, we have to emit a
1336 /// header and trailer to make it compatible with the system archiver. To do
1337 /// this we emit the following header, and then emit a trailer that pads the
1338 /// file out to be a multiple of 16 bytes.
1340 /// struct bc_header {
1341 /// uint32_t Magic; // 0x0B17C0DE
1342 /// uint32_t Version; // Version, currently always 0.
1343 /// uint32_t BitcodeOffset; // Offset to traditional bitcode file.
1344 /// uint32_t BitcodeSize; // Size of traditional bitcode file.
1345 /// uint32_t CPUType; // CPU specifier.
1346 /// ... potentially more later ...
1349 DarwinBCSizeFieldOffset = 3*4, // Offset to bitcode_size.
1350 DarwinBCHeaderSize = 5*4
1353 static void EmitDarwinBCHeader(BitstreamWriter &Stream,
1354 const std::string &TT) {
1355 unsigned CPUType = ~0U;
1357 // Match x86_64-*, i[3-9]86-*, powerpc-*, powerpc64-*. The CPUType is a
1358 // magic number from /usr/include/mach/machine.h. It is ok to reproduce the
1359 // specific constants here because they are implicitly part of the Darwin ABI.
1361 DARWIN_CPU_ARCH_ABI64 = 0x01000000,
1362 DARWIN_CPU_TYPE_X86 = 7,
1363 DARWIN_CPU_TYPE_POWERPC = 18
1366 if (TT.find("x86_64-") == 0)
1367 CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64;
1368 else if (TT.size() >= 5 && TT[0] == 'i' && TT[2] == '8' && TT[3] == '6' &&
1369 TT[4] == '-' && TT[1] - '3' < 6)
1370 CPUType = DARWIN_CPU_TYPE_X86;
1371 else if (TT.find("powerpc-") == 0)
1372 CPUType = DARWIN_CPU_TYPE_POWERPC;
1373 else if (TT.find("powerpc64-") == 0)
1374 CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64;
1376 // Traditional Bitcode starts after header.
1377 unsigned BCOffset = DarwinBCHeaderSize;
1379 Stream.Emit(0x0B17C0DE, 32);
1380 Stream.Emit(0 , 32); // Version.
1381 Stream.Emit(BCOffset , 32);
1382 Stream.Emit(0 , 32); // Filled in later.
1383 Stream.Emit(CPUType , 32);
1386 /// EmitDarwinBCTrailer - Emit the darwin epilog after the bitcode file and
1387 /// finalize the header.
1388 static void EmitDarwinBCTrailer(BitstreamWriter &Stream, unsigned BufferSize) {
1389 // Update the size field in the header.
1390 Stream.BackpatchWord(DarwinBCSizeFieldOffset, BufferSize-DarwinBCHeaderSize);
1392 // If the file is not a multiple of 16 bytes, insert dummy padding.
1393 while (BufferSize & 15) {
1400 /// WriteBitcodeToFile - Write the specified module to the specified output
1402 void llvm::WriteBitcodeToFile(const Module *M, std::ostream &Out) {
1403 raw_os_ostream RawOut(Out);
1404 // If writing to stdout, set binary mode.
1405 if (llvm::cout == Out)
1406 sys::Program::ChangeStdoutToBinary();
1407 WriteBitcodeToFile(M, RawOut);
1410 /// WriteBitcodeToFile - Write the specified module to the specified output
1412 void llvm::WriteBitcodeToFile(const Module *M, raw_ostream &Out) {
1413 std::vector<unsigned char> Buffer;
1414 BitstreamWriter Stream(Buffer);
1416 Buffer.reserve(256*1024);
1418 WriteBitcodeToStream( M, Stream );
1420 // If writing to stdout, set binary mode.
1421 if (&llvm::outs() == &Out)
1422 sys::Program::ChangeStdoutToBinary();
1424 // Write the generated bitstream to "Out".
1425 Out.write((char*)&Buffer.front(), Buffer.size());
1427 // Make sure it hits disk now.
1431 /// WriteBitcodeToStream - Write the specified module to the specified output
1433 void llvm::WriteBitcodeToStream(const Module *M, BitstreamWriter &Stream) {
1434 // If this is darwin, emit a file header and trailer if needed.
1435 bool isDarwin = M->getTargetTriple().find("-darwin") != std::string::npos;
1437 EmitDarwinBCHeader(Stream, M->getTargetTriple());
1439 // Emit the file header.
1440 Stream.Emit((unsigned)'B', 8);
1441 Stream.Emit((unsigned)'C', 8);
1442 Stream.Emit(0x0, 4);
1443 Stream.Emit(0xC, 4);
1444 Stream.Emit(0xE, 4);
1445 Stream.Emit(0xD, 4);
1448 WriteModule(M, Stream);
1451 EmitDarwinBCTrailer(Stream, Stream.getBuffer().size());