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/ErrorHandling.h"
27 #include "llvm/Support/MathExtras.h"
28 #include "llvm/Support/Streams.h"
29 #include "llvm/Support/raw_ostream.h"
30 #include "llvm/System/Program.h"
33 /// These are manifest constants used by the bitcode writer. They do not need to
34 /// be kept in sync with the reader, but need to be consistent within this file.
38 // VALUE_SYMTAB_BLOCK abbrev id's.
39 VST_ENTRY_8_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
44 // CONSTANTS_BLOCK abbrev id's.
45 CONSTANTS_SETTYPE_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
46 CONSTANTS_INTEGER_ABBREV,
47 CONSTANTS_CE_CAST_Abbrev,
48 CONSTANTS_NULL_Abbrev,
50 // FUNCTION_BLOCK abbrev id's.
51 FUNCTION_INST_LOAD_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
52 FUNCTION_INST_BINOP_ABBREV,
53 FUNCTION_INST_CAST_ABBREV,
54 FUNCTION_INST_RET_VOID_ABBREV,
55 FUNCTION_INST_RET_VAL_ABBREV,
56 FUNCTION_INST_UNREACHABLE_ABBREV
60 static unsigned GetEncodedCastOpcode(unsigned Opcode) {
62 default: llvm_unreachable("Unknown cast instruction!");
63 case Instruction::Trunc : return bitc::CAST_TRUNC;
64 case Instruction::ZExt : return bitc::CAST_ZEXT;
65 case Instruction::SExt : return bitc::CAST_SEXT;
66 case Instruction::FPToUI : return bitc::CAST_FPTOUI;
67 case Instruction::FPToSI : return bitc::CAST_FPTOSI;
68 case Instruction::UIToFP : return bitc::CAST_UITOFP;
69 case Instruction::SIToFP : return bitc::CAST_SITOFP;
70 case Instruction::FPTrunc : return bitc::CAST_FPTRUNC;
71 case Instruction::FPExt : return bitc::CAST_FPEXT;
72 case Instruction::PtrToInt: return bitc::CAST_PTRTOINT;
73 case Instruction::IntToPtr: return bitc::CAST_INTTOPTR;
74 case Instruction::BitCast : return bitc::CAST_BITCAST;
78 static unsigned GetEncodedBinaryOpcode(unsigned Opcode) {
80 default: llvm_unreachable("Unknown binary instruction!");
81 case Instruction::Add:
82 case Instruction::FAdd: return bitc::BINOP_ADD;
83 case Instruction::Sub:
84 case Instruction::FSub: return bitc::BINOP_SUB;
85 case Instruction::Mul:
86 case Instruction::FMul: return bitc::BINOP_MUL;
87 case Instruction::UDiv: return bitc::BINOP_UDIV;
88 case Instruction::FDiv:
89 case Instruction::SDiv: return bitc::BINOP_SDIV;
90 case Instruction::URem: return bitc::BINOP_UREM;
91 case Instruction::FRem:
92 case Instruction::SRem: return bitc::BINOP_SREM;
93 case Instruction::Shl: return bitc::BINOP_SHL;
94 case Instruction::LShr: return bitc::BINOP_LSHR;
95 case Instruction::AShr: return bitc::BINOP_ASHR;
96 case Instruction::And: return bitc::BINOP_AND;
97 case Instruction::Or: return bitc::BINOP_OR;
98 case Instruction::Xor: return bitc::BINOP_XOR;
104 static void WriteStringRecord(unsigned Code, const std::string &Str,
105 unsigned AbbrevToUse, BitstreamWriter &Stream) {
106 SmallVector<unsigned, 64> Vals;
108 // Code: [strchar x N]
109 for (unsigned i = 0, e = Str.size(); i != e; ++i)
110 Vals.push_back(Str[i]);
112 // Emit the finished record.
113 Stream.EmitRecord(Code, Vals, AbbrevToUse);
116 // Emit information about parameter attributes.
117 static void WriteAttributeTable(const ValueEnumerator &VE,
118 BitstreamWriter &Stream) {
119 const std::vector<AttrListPtr> &Attrs = VE.getAttributes();
120 if (Attrs.empty()) return;
122 Stream.EnterSubblock(bitc::PARAMATTR_BLOCK_ID, 3);
124 SmallVector<uint64_t, 64> Record;
125 for (unsigned i = 0, e = Attrs.size(); i != e; ++i) {
126 const AttrListPtr &A = Attrs[i];
127 for (unsigned i = 0, e = A.getNumSlots(); i != e; ++i) {
128 const AttributeWithIndex &PAWI = A.getSlot(i);
129 Record.push_back(PAWI.Index);
131 // FIXME: remove in LLVM 3.0
132 // Store the alignment in the bitcode as a 16-bit raw value instead of a
133 // 5-bit log2 encoded value. Shift the bits above the alignment up by
135 uint64_t FauxAttr = PAWI.Attrs & 0xffff;
136 if (PAWI.Attrs & Attribute::Alignment)
137 FauxAttr |= (1ull<<16)<<(((PAWI.Attrs & Attribute::Alignment)-1) >> 16);
138 FauxAttr |= (PAWI.Attrs & (0x3FFull << 21)) << 11;
140 Record.push_back(FauxAttr);
143 Stream.EmitRecord(bitc::PARAMATTR_CODE_ENTRY, Record);
150 /// WriteTypeTable - Write out the type table for a module.
151 static void WriteTypeTable(const ValueEnumerator &VE, BitstreamWriter &Stream) {
152 const ValueEnumerator::TypeList &TypeList = VE.getTypes();
154 Stream.EnterSubblock(bitc::TYPE_BLOCK_ID, 4 /*count from # abbrevs */);
155 SmallVector<uint64_t, 64> TypeVals;
157 // Abbrev for TYPE_CODE_POINTER.
158 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
159 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_POINTER));
160 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
161 Log2_32_Ceil(VE.getTypes().size()+1)));
162 Abbv->Add(BitCodeAbbrevOp(0)); // Addrspace = 0
163 unsigned PtrAbbrev = Stream.EmitAbbrev(Abbv);
165 // Abbrev for TYPE_CODE_FUNCTION.
166 Abbv = new BitCodeAbbrev();
167 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_FUNCTION));
168 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // isvararg
169 Abbv->Add(BitCodeAbbrevOp(0)); // FIXME: DEAD value, remove in LLVM 3.0
170 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
171 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
172 Log2_32_Ceil(VE.getTypes().size()+1)));
173 unsigned FunctionAbbrev = Stream.EmitAbbrev(Abbv);
175 // Abbrev for TYPE_CODE_STRUCT.
176 Abbv = new BitCodeAbbrev();
177 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT));
178 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
179 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
180 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
181 Log2_32_Ceil(VE.getTypes().size()+1)));
182 unsigned StructAbbrev = Stream.EmitAbbrev(Abbv);
184 // Abbrev for TYPE_CODE_ARRAY.
185 Abbv = new BitCodeAbbrev();
186 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_ARRAY));
187 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // size
188 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
189 Log2_32_Ceil(VE.getTypes().size()+1)));
190 unsigned ArrayAbbrev = Stream.EmitAbbrev(Abbv);
192 // Emit an entry count so the reader can reserve space.
193 TypeVals.push_back(TypeList.size());
194 Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals);
197 // Loop over all of the types, emitting each in turn.
198 for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
199 const Type *T = TypeList[i].first;
203 switch (T->getTypeID()) {
204 default: llvm_unreachable("Unknown type!");
205 case Type::VoidTyID: Code = bitc::TYPE_CODE_VOID; break;
206 case Type::FloatTyID: Code = bitc::TYPE_CODE_FLOAT; break;
207 case Type::DoubleTyID: Code = bitc::TYPE_CODE_DOUBLE; break;
208 case Type::X86_FP80TyID: Code = bitc::TYPE_CODE_X86_FP80; break;
209 case Type::FP128TyID: Code = bitc::TYPE_CODE_FP128; break;
210 case Type::PPC_FP128TyID: Code = bitc::TYPE_CODE_PPC_FP128; break;
211 case Type::LabelTyID: Code = bitc::TYPE_CODE_LABEL; break;
212 case Type::OpaqueTyID: Code = bitc::TYPE_CODE_OPAQUE; break;
213 case Type::MetadataTyID: Code = bitc::TYPE_CODE_METADATA; break;
214 case Type::IntegerTyID:
216 Code = bitc::TYPE_CODE_INTEGER;
217 TypeVals.push_back(cast<IntegerType>(T)->getBitWidth());
219 case Type::PointerTyID: {
220 const PointerType *PTy = cast<PointerType>(T);
221 // POINTER: [pointee type, address space]
222 Code = bitc::TYPE_CODE_POINTER;
223 TypeVals.push_back(VE.getTypeID(PTy->getElementType()));
224 unsigned AddressSpace = PTy->getAddressSpace();
225 TypeVals.push_back(AddressSpace);
226 if (AddressSpace == 0) AbbrevToUse = PtrAbbrev;
229 case Type::FunctionTyID: {
230 const FunctionType *FT = cast<FunctionType>(T);
231 // FUNCTION: [isvararg, attrid, retty, paramty x N]
232 Code = bitc::TYPE_CODE_FUNCTION;
233 TypeVals.push_back(FT->isVarArg());
234 TypeVals.push_back(0); // FIXME: DEAD: remove in llvm 3.0
235 TypeVals.push_back(VE.getTypeID(FT->getReturnType()));
236 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
237 TypeVals.push_back(VE.getTypeID(FT->getParamType(i)));
238 AbbrevToUse = FunctionAbbrev;
241 case Type::StructTyID: {
242 const StructType *ST = cast<StructType>(T);
243 // STRUCT: [ispacked, eltty x N]
244 Code = bitc::TYPE_CODE_STRUCT;
245 TypeVals.push_back(ST->isPacked());
246 // Output all of the element types.
247 for (StructType::element_iterator I = ST->element_begin(),
248 E = ST->element_end(); I != E; ++I)
249 TypeVals.push_back(VE.getTypeID(*I));
250 AbbrevToUse = StructAbbrev;
253 case Type::ArrayTyID: {
254 const ArrayType *AT = cast<ArrayType>(T);
255 // ARRAY: [numelts, eltty]
256 Code = bitc::TYPE_CODE_ARRAY;
257 TypeVals.push_back(AT->getNumElements());
258 TypeVals.push_back(VE.getTypeID(AT->getElementType()));
259 AbbrevToUse = ArrayAbbrev;
262 case Type::VectorTyID: {
263 const VectorType *VT = cast<VectorType>(T);
264 // VECTOR [numelts, eltty]
265 Code = bitc::TYPE_CODE_VECTOR;
266 TypeVals.push_back(VT->getNumElements());
267 TypeVals.push_back(VE.getTypeID(VT->getElementType()));
272 // Emit the finished record.
273 Stream.EmitRecord(Code, TypeVals, AbbrevToUse);
280 static unsigned getEncodedLinkage(const GlobalValue *GV) {
281 switch (GV->getLinkage()) {
282 default: llvm_unreachable("Invalid linkage!");
283 case GlobalValue::GhostLinkage: // Map ghost linkage onto external.
284 case GlobalValue::ExternalLinkage: return 0;
285 case GlobalValue::WeakAnyLinkage: return 1;
286 case GlobalValue::AppendingLinkage: return 2;
287 case GlobalValue::InternalLinkage: return 3;
288 case GlobalValue::LinkOnceAnyLinkage: return 4;
289 case GlobalValue::DLLImportLinkage: return 5;
290 case GlobalValue::DLLExportLinkage: return 6;
291 case GlobalValue::ExternalWeakLinkage: return 7;
292 case GlobalValue::CommonLinkage: return 8;
293 case GlobalValue::PrivateLinkage: return 9;
294 case GlobalValue::WeakODRLinkage: return 10;
295 case GlobalValue::LinkOnceODRLinkage: return 11;
296 case GlobalValue::AvailableExternallyLinkage: return 12;
297 case GlobalValue::LinkerPrivateLinkage: return 13;
301 static unsigned getEncodedVisibility(const GlobalValue *GV) {
302 switch (GV->getVisibility()) {
303 default: llvm_unreachable("Invalid visibility!");
304 case GlobalValue::DefaultVisibility: return 0;
305 case GlobalValue::HiddenVisibility: return 1;
306 case GlobalValue::ProtectedVisibility: return 2;
310 // Emit top-level description of module, including target triple, inline asm,
311 // descriptors for global variables, and function prototype info.
312 static void WriteModuleInfo(const Module *M, const ValueEnumerator &VE,
313 BitstreamWriter &Stream) {
314 // Emit the list of dependent libraries for the Module.
315 for (Module::lib_iterator I = M->lib_begin(), E = M->lib_end(); I != E; ++I)
316 WriteStringRecord(bitc::MODULE_CODE_DEPLIB, *I, 0/*TODO*/, Stream);
318 // Emit various pieces of data attached to a module.
319 if (!M->getTargetTriple().empty())
320 WriteStringRecord(bitc::MODULE_CODE_TRIPLE, M->getTargetTriple(),
322 if (!M->getDataLayout().empty())
323 WriteStringRecord(bitc::MODULE_CODE_DATALAYOUT, M->getDataLayout(),
325 if (!M->getModuleInlineAsm().empty())
326 WriteStringRecord(bitc::MODULE_CODE_ASM, M->getModuleInlineAsm(),
329 // Emit information about sections and GC, computing how many there are. Also
330 // compute the maximum alignment value.
331 std::map<std::string, unsigned> SectionMap;
332 std::map<std::string, unsigned> GCMap;
333 unsigned MaxAlignment = 0;
334 unsigned MaxGlobalType = 0;
335 for (Module::const_global_iterator GV = M->global_begin(),E = M->global_end();
337 MaxAlignment = std::max(MaxAlignment, GV->getAlignment());
338 MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV->getType()));
340 if (!GV->hasSection()) continue;
341 // Give section names unique ID's.
342 unsigned &Entry = SectionMap[GV->getSection()];
343 if (Entry != 0) continue;
344 WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, GV->getSection(),
346 Entry = SectionMap.size();
348 for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) {
349 MaxAlignment = std::max(MaxAlignment, F->getAlignment());
350 if (F->hasSection()) {
351 // Give section names unique ID's.
352 unsigned &Entry = SectionMap[F->getSection()];
354 WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, F->getSection(),
356 Entry = SectionMap.size();
360 // Same for GC names.
361 unsigned &Entry = GCMap[F->getGC()];
363 WriteStringRecord(bitc::MODULE_CODE_GCNAME, F->getGC(),
365 Entry = GCMap.size();
370 // Emit abbrev for globals, now that we know # sections and max alignment.
371 unsigned SimpleGVarAbbrev = 0;
372 if (!M->global_empty()) {
373 // Add an abbrev for common globals with no visibility or thread localness.
374 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
375 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GLOBALVAR));
376 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
377 Log2_32_Ceil(MaxGlobalType+1)));
378 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Constant.
379 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Initializer.
380 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // Linkage.
381 if (MaxAlignment == 0) // Alignment.
382 Abbv->Add(BitCodeAbbrevOp(0));
384 unsigned MaxEncAlignment = Log2_32(MaxAlignment)+1;
385 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
386 Log2_32_Ceil(MaxEncAlignment+1)));
388 if (SectionMap.empty()) // Section.
389 Abbv->Add(BitCodeAbbrevOp(0));
391 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
392 Log2_32_Ceil(SectionMap.size()+1)));
393 // Don't bother emitting vis + thread local.
394 SimpleGVarAbbrev = Stream.EmitAbbrev(Abbv);
397 // Emit the global variable information.
398 SmallVector<unsigned, 64> Vals;
399 for (Module::const_global_iterator GV = M->global_begin(),E = M->global_end();
401 unsigned AbbrevToUse = 0;
403 // GLOBALVAR: [type, isconst, initid,
404 // linkage, alignment, section, visibility, threadlocal]
405 Vals.push_back(VE.getTypeID(GV->getType()));
406 Vals.push_back(GV->isConstant());
407 Vals.push_back(GV->isDeclaration() ? 0 :
408 (VE.getValueID(GV->getInitializer()) + 1));
409 Vals.push_back(getEncodedLinkage(GV));
410 Vals.push_back(Log2_32(GV->getAlignment())+1);
411 Vals.push_back(GV->hasSection() ? SectionMap[GV->getSection()] : 0);
412 if (GV->isThreadLocal() ||
413 GV->getVisibility() != GlobalValue::DefaultVisibility) {
414 Vals.push_back(getEncodedVisibility(GV));
415 Vals.push_back(GV->isThreadLocal());
417 AbbrevToUse = SimpleGVarAbbrev;
420 Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse);
424 // Emit the function proto information.
425 for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) {
426 // FUNCTION: [type, callingconv, isproto, paramattr,
427 // linkage, alignment, section, visibility, gc]
428 Vals.push_back(VE.getTypeID(F->getType()));
429 Vals.push_back(F->getCallingConv());
430 Vals.push_back(F->isDeclaration());
431 Vals.push_back(getEncodedLinkage(F));
432 Vals.push_back(VE.getAttributeID(F->getAttributes()));
433 Vals.push_back(Log2_32(F->getAlignment())+1);
434 Vals.push_back(F->hasSection() ? SectionMap[F->getSection()] : 0);
435 Vals.push_back(getEncodedVisibility(F));
436 Vals.push_back(F->hasGC() ? GCMap[F->getGC()] : 0);
438 unsigned AbbrevToUse = 0;
439 Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse);
444 // Emit the alias information.
445 for (Module::const_alias_iterator AI = M->alias_begin(), E = M->alias_end();
447 Vals.push_back(VE.getTypeID(AI->getType()));
448 Vals.push_back(VE.getValueID(AI->getAliasee()));
449 Vals.push_back(getEncodedLinkage(AI));
450 Vals.push_back(getEncodedVisibility(AI));
451 unsigned AbbrevToUse = 0;
452 Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse);
458 static void WriteConstants(unsigned FirstVal, unsigned LastVal,
459 const ValueEnumerator &VE,
460 BitstreamWriter &Stream, bool isGlobal) {
461 if (FirstVal == LastVal) return;
463 Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 4);
465 unsigned AggregateAbbrev = 0;
466 unsigned String8Abbrev = 0;
467 unsigned CString7Abbrev = 0;
468 unsigned CString6Abbrev = 0;
469 unsigned MDString8Abbrev = 0;
470 unsigned MDString6Abbrev = 0;
471 // If this is a constant pool for the module, emit module-specific abbrevs.
473 // Abbrev for CST_CODE_AGGREGATE.
474 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
475 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_AGGREGATE));
476 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
477 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal+1)));
478 AggregateAbbrev = Stream.EmitAbbrev(Abbv);
480 // Abbrev for CST_CODE_STRING.
481 Abbv = new BitCodeAbbrev();
482 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_STRING));
483 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
484 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
485 String8Abbrev = Stream.EmitAbbrev(Abbv);
486 // Abbrev for CST_CODE_CSTRING.
487 Abbv = new BitCodeAbbrev();
488 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
489 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
490 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
491 CString7Abbrev = Stream.EmitAbbrev(Abbv);
492 // Abbrev for CST_CODE_CSTRING.
493 Abbv = new BitCodeAbbrev();
494 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
495 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
496 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
497 CString6Abbrev = Stream.EmitAbbrev(Abbv);
499 // Abbrev for CST_CODE_MDSTRING.
500 Abbv = new BitCodeAbbrev();
501 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_MDSTRING));
502 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
503 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
504 MDString8Abbrev = Stream.EmitAbbrev(Abbv);
505 // Abbrev for CST_CODE_MDSTRING.
506 Abbv = new BitCodeAbbrev();
507 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_MDSTRING));
508 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
509 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
510 MDString6Abbrev = Stream.EmitAbbrev(Abbv);
513 SmallVector<uint64_t, 64> Record;
515 const ValueEnumerator::ValueList &Vals = VE.getValues();
516 const Type *LastTy = 0;
517 for (unsigned i = FirstVal; i != LastVal; ++i) {
518 const Value *V = Vals[i].first;
519 // If we need to switch types, do so now.
520 if (V->getType() != LastTy) {
521 LastTy = V->getType();
522 Record.push_back(VE.getTypeID(LastTy));
523 Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record,
524 CONSTANTS_SETTYPE_ABBREV);
528 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
529 Record.push_back(unsigned(IA->hasSideEffects()));
531 // Add the asm string.
532 const std::string &AsmStr = IA->getAsmString();
533 Record.push_back(AsmStr.size());
534 for (unsigned i = 0, e = AsmStr.size(); i != e; ++i)
535 Record.push_back(AsmStr[i]);
537 // Add the constraint string.
538 const std::string &ConstraintStr = IA->getConstraintString();
539 Record.push_back(ConstraintStr.size());
540 for (unsigned i = 0, e = ConstraintStr.size(); i != e; ++i)
541 Record.push_back(ConstraintStr[i]);
542 Stream.EmitRecord(bitc::CST_CODE_INLINEASM, Record);
546 const Constant *C = cast<Constant>(V);
548 unsigned AbbrevToUse = 0;
549 if (C->isNullValue()) {
550 Code = bitc::CST_CODE_NULL;
551 } else if (isa<UndefValue>(C)) {
552 Code = bitc::CST_CODE_UNDEF;
553 } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {
554 if (IV->getBitWidth() <= 64) {
555 int64_t V = IV->getSExtValue();
557 Record.push_back(V << 1);
559 Record.push_back((-V << 1) | 1);
560 Code = bitc::CST_CODE_INTEGER;
561 AbbrevToUse = CONSTANTS_INTEGER_ABBREV;
562 } else { // Wide integers, > 64 bits in size.
563 // We have an arbitrary precision integer value to write whose
564 // bit width is > 64. However, in canonical unsigned integer
565 // format it is likely that the high bits are going to be zero.
566 // So, we only write the number of active words.
567 unsigned NWords = IV->getValue().getActiveWords();
568 const uint64_t *RawWords = IV->getValue().getRawData();
569 for (unsigned i = 0; i != NWords; ++i) {
570 int64_t V = RawWords[i];
572 Record.push_back(V << 1);
574 Record.push_back((-V << 1) | 1);
576 Code = bitc::CST_CODE_WIDE_INTEGER;
578 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
579 Code = bitc::CST_CODE_FLOAT;
580 const Type *Ty = CFP->getType();
581 if (Ty == Type::FloatTy || Ty == Type::DoubleTy) {
582 Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
583 } else if (Ty == Type::X86_FP80Ty) {
584 // api needed to prevent premature destruction
585 // bits are not in the same order as a normal i80 APInt, compensate.
586 APInt api = CFP->getValueAPF().bitcastToAPInt();
587 const uint64_t *p = api.getRawData();
588 Record.push_back((p[1] << 48) | (p[0] >> 16));
589 Record.push_back(p[0] & 0xffffLL);
590 } else if (Ty == Type::FP128Ty || Ty == Type::PPC_FP128Ty) {
591 APInt api = CFP->getValueAPF().bitcastToAPInt();
592 const uint64_t *p = api.getRawData();
593 Record.push_back(p[0]);
594 Record.push_back(p[1]);
596 assert (0 && "Unknown FP type!");
598 } else if (isa<ConstantArray>(C) && cast<ConstantArray>(C)->isString()) {
599 // Emit constant strings specially.
600 unsigned NumOps = C->getNumOperands();
601 // If this is a null-terminated string, use the denser CSTRING encoding.
602 if (C->getOperand(NumOps-1)->isNullValue()) {
603 Code = bitc::CST_CODE_CSTRING;
604 --NumOps; // Don't encode the null, which isn't allowed by char6.
606 Code = bitc::CST_CODE_STRING;
607 AbbrevToUse = String8Abbrev;
609 bool isCStr7 = Code == bitc::CST_CODE_CSTRING;
610 bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING;
611 for (unsigned i = 0; i != NumOps; ++i) {
612 unsigned char V = cast<ConstantInt>(C->getOperand(i))->getZExtValue();
614 isCStr7 &= (V & 128) == 0;
616 isCStrChar6 = BitCodeAbbrevOp::isChar6(V);
620 AbbrevToUse = CString6Abbrev;
622 AbbrevToUse = CString7Abbrev;
623 } else if (isa<ConstantArray>(C) || isa<ConstantStruct>(V) ||
624 isa<ConstantVector>(V)) {
625 Code = bitc::CST_CODE_AGGREGATE;
626 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i)
627 Record.push_back(VE.getValueID(C->getOperand(i)));
628 AbbrevToUse = AggregateAbbrev;
629 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
630 switch (CE->getOpcode()) {
632 if (Instruction::isCast(CE->getOpcode())) {
633 Code = bitc::CST_CODE_CE_CAST;
634 Record.push_back(GetEncodedCastOpcode(CE->getOpcode()));
635 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
636 Record.push_back(VE.getValueID(C->getOperand(0)));
637 AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;
639 assert(CE->getNumOperands() == 2 && "Unknown constant expr!");
640 Code = bitc::CST_CODE_CE_BINOP;
641 Record.push_back(GetEncodedBinaryOpcode(CE->getOpcode()));
642 Record.push_back(VE.getValueID(C->getOperand(0)));
643 Record.push_back(VE.getValueID(C->getOperand(1)));
646 case Instruction::GetElementPtr:
647 Code = bitc::CST_CODE_CE_GEP;
648 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
649 Record.push_back(VE.getTypeID(C->getOperand(i)->getType()));
650 Record.push_back(VE.getValueID(C->getOperand(i)));
653 case Instruction::Select:
654 Code = bitc::CST_CODE_CE_SELECT;
655 Record.push_back(VE.getValueID(C->getOperand(0)));
656 Record.push_back(VE.getValueID(C->getOperand(1)));
657 Record.push_back(VE.getValueID(C->getOperand(2)));
659 case Instruction::ExtractElement:
660 Code = bitc::CST_CODE_CE_EXTRACTELT;
661 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
662 Record.push_back(VE.getValueID(C->getOperand(0)));
663 Record.push_back(VE.getValueID(C->getOperand(1)));
665 case Instruction::InsertElement:
666 Code = bitc::CST_CODE_CE_INSERTELT;
667 Record.push_back(VE.getValueID(C->getOperand(0)));
668 Record.push_back(VE.getValueID(C->getOperand(1)));
669 Record.push_back(VE.getValueID(C->getOperand(2)));
671 case Instruction::ShuffleVector:
672 // If the return type and argument types are the same, this is a
673 // standard shufflevector instruction. If the types are different,
674 // then the shuffle is widening or truncating the input vectors, and
675 // the argument type must also be encoded.
676 if (C->getType() == C->getOperand(0)->getType()) {
677 Code = bitc::CST_CODE_CE_SHUFFLEVEC;
679 Code = bitc::CST_CODE_CE_SHUFVEC_EX;
680 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
682 Record.push_back(VE.getValueID(C->getOperand(0)));
683 Record.push_back(VE.getValueID(C->getOperand(1)));
684 Record.push_back(VE.getValueID(C->getOperand(2)));
686 case Instruction::ICmp:
687 case Instruction::FCmp:
688 Code = bitc::CST_CODE_CE_CMP;
689 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
690 Record.push_back(VE.getValueID(C->getOperand(0)));
691 Record.push_back(VE.getValueID(C->getOperand(1)));
692 Record.push_back(CE->getPredicate());
695 } else if (const MDString *S = dyn_cast<MDString>(C)) {
696 Code = bitc::CST_CODE_MDSTRING;
697 AbbrevToUse = MDString6Abbrev;
698 for (unsigned i = 0, e = S->size(); i != e; ++i) {
699 char V = S->begin()[i];
702 if (!BitCodeAbbrevOp::isChar6(V))
703 AbbrevToUse = MDString8Abbrev;
705 } else if (const MDNode *N = dyn_cast<MDNode>(C)) {
706 Code = bitc::CST_CODE_MDNODE;
707 for (unsigned i = 0, e = N->getNumElements(); i != e; ++i) {
708 if (N->getElement(i)) {
709 Record.push_back(VE.getTypeID(N->getElement(i)->getType()));
710 Record.push_back(VE.getValueID(N->getElement(i)));
712 Record.push_back(VE.getTypeID(Type::VoidTy));
717 llvm_unreachable("Unknown constant!");
719 Stream.EmitRecord(Code, Record, AbbrevToUse);
726 static void WriteModuleConstants(const ValueEnumerator &VE,
727 BitstreamWriter &Stream) {
728 const ValueEnumerator::ValueList &Vals = VE.getValues();
730 // Find the first constant to emit, which is the first non-globalvalue value.
731 // We know globalvalues have been emitted by WriteModuleInfo.
732 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
733 if (!isa<GlobalValue>(Vals[i].first)) {
734 WriteConstants(i, Vals.size(), VE, Stream, true);
740 /// PushValueAndType - The file has to encode both the value and type id for
741 /// many values, because we need to know what type to create for forward
742 /// references. However, most operands are not forward references, so this type
743 /// field is not needed.
745 /// This function adds V's value ID to Vals. If the value ID is higher than the
746 /// instruction ID, then it is a forward reference, and it also includes the
748 static bool PushValueAndType(const Value *V, unsigned InstID,
749 SmallVector<unsigned, 64> &Vals,
750 ValueEnumerator &VE) {
751 unsigned ValID = VE.getValueID(V);
752 Vals.push_back(ValID);
753 if (ValID >= InstID) {
754 Vals.push_back(VE.getTypeID(V->getType()));
760 /// WriteInstruction - Emit an instruction to the specified stream.
761 static void WriteInstruction(const Instruction &I, unsigned InstID,
762 ValueEnumerator &VE, BitstreamWriter &Stream,
763 SmallVector<unsigned, 64> &Vals) {
765 unsigned AbbrevToUse = 0;
766 switch (I.getOpcode()) {
768 if (Instruction::isCast(I.getOpcode())) {
769 Code = bitc::FUNC_CODE_INST_CAST;
770 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
771 AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
772 Vals.push_back(VE.getTypeID(I.getType()));
773 Vals.push_back(GetEncodedCastOpcode(I.getOpcode()));
775 assert(isa<BinaryOperator>(I) && "Unknown instruction!");
776 Code = bitc::FUNC_CODE_INST_BINOP;
777 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
778 AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
779 Vals.push_back(VE.getValueID(I.getOperand(1)));
780 Vals.push_back(GetEncodedBinaryOpcode(I.getOpcode()));
784 case Instruction::GetElementPtr:
785 Code = bitc::FUNC_CODE_INST_GEP;
786 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
787 PushValueAndType(I.getOperand(i), InstID, Vals, VE);
789 case Instruction::ExtractValue: {
790 Code = bitc::FUNC_CODE_INST_EXTRACTVAL;
791 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
792 const ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
793 for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
797 case Instruction::InsertValue: {
798 Code = bitc::FUNC_CODE_INST_INSERTVAL;
799 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
800 PushValueAndType(I.getOperand(1), InstID, Vals, VE);
801 const InsertValueInst *IVI = cast<InsertValueInst>(&I);
802 for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
806 case Instruction::Select:
807 Code = bitc::FUNC_CODE_INST_VSELECT;
808 PushValueAndType(I.getOperand(1), InstID, Vals, VE);
809 Vals.push_back(VE.getValueID(I.getOperand(2)));
810 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
812 case Instruction::ExtractElement:
813 Code = bitc::FUNC_CODE_INST_EXTRACTELT;
814 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
815 Vals.push_back(VE.getValueID(I.getOperand(1)));
817 case Instruction::InsertElement:
818 Code = bitc::FUNC_CODE_INST_INSERTELT;
819 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
820 Vals.push_back(VE.getValueID(I.getOperand(1)));
821 Vals.push_back(VE.getValueID(I.getOperand(2)));
823 case Instruction::ShuffleVector:
824 Code = bitc::FUNC_CODE_INST_SHUFFLEVEC;
825 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
826 Vals.push_back(VE.getValueID(I.getOperand(1)));
827 Vals.push_back(VE.getValueID(I.getOperand(2)));
829 case Instruction::ICmp:
830 case Instruction::FCmp:
831 // compare returning Int1Ty or vector of Int1Ty
832 Code = bitc::FUNC_CODE_INST_CMP2;
833 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
834 Vals.push_back(VE.getValueID(I.getOperand(1)));
835 Vals.push_back(cast<CmpInst>(I).getPredicate());
838 case Instruction::Ret:
840 Code = bitc::FUNC_CODE_INST_RET;
841 unsigned NumOperands = I.getNumOperands();
842 if (NumOperands == 0)
843 AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
844 else if (NumOperands == 1) {
845 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
846 AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
848 for (unsigned i = 0, e = NumOperands; i != e; ++i)
849 PushValueAndType(I.getOperand(i), InstID, Vals, VE);
853 case Instruction::Br:
855 Code = bitc::FUNC_CODE_INST_BR;
856 BranchInst &II(cast<BranchInst>(I));
857 Vals.push_back(VE.getValueID(II.getSuccessor(0)));
858 if (II.isConditional()) {
859 Vals.push_back(VE.getValueID(II.getSuccessor(1)));
860 Vals.push_back(VE.getValueID(II.getCondition()));
864 case Instruction::Switch:
865 Code = bitc::FUNC_CODE_INST_SWITCH;
866 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
867 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
868 Vals.push_back(VE.getValueID(I.getOperand(i)));
870 case Instruction::Invoke: {
871 const InvokeInst *II = cast<InvokeInst>(&I);
872 const Value *Callee(II->getCalledValue());
873 const PointerType *PTy = cast<PointerType>(Callee->getType());
874 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
875 Code = bitc::FUNC_CODE_INST_INVOKE;
877 Vals.push_back(VE.getAttributeID(II->getAttributes()));
878 Vals.push_back(II->getCallingConv());
879 Vals.push_back(VE.getValueID(II->getNormalDest()));
880 Vals.push_back(VE.getValueID(II->getUnwindDest()));
881 PushValueAndType(Callee, InstID, Vals, VE);
883 // Emit value #'s for the fixed parameters.
884 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
885 Vals.push_back(VE.getValueID(I.getOperand(i+3))); // fixed param.
887 // Emit type/value pairs for varargs params.
888 if (FTy->isVarArg()) {
889 for (unsigned i = 3+FTy->getNumParams(), e = I.getNumOperands();
891 PushValueAndType(I.getOperand(i), InstID, Vals, VE); // vararg
895 case Instruction::Unwind:
896 Code = bitc::FUNC_CODE_INST_UNWIND;
898 case Instruction::Unreachable:
899 Code = bitc::FUNC_CODE_INST_UNREACHABLE;
900 AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
903 case Instruction::PHI:
904 Code = bitc::FUNC_CODE_INST_PHI;
905 Vals.push_back(VE.getTypeID(I.getType()));
906 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
907 Vals.push_back(VE.getValueID(I.getOperand(i)));
910 case Instruction::Malloc:
911 Code = bitc::FUNC_CODE_INST_MALLOC;
912 Vals.push_back(VE.getTypeID(I.getType()));
913 Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
914 Vals.push_back(Log2_32(cast<MallocInst>(I).getAlignment())+1);
917 case Instruction::Free:
918 Code = bitc::FUNC_CODE_INST_FREE;
919 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
922 case Instruction::Alloca:
923 Code = bitc::FUNC_CODE_INST_ALLOCA;
924 Vals.push_back(VE.getTypeID(I.getType()));
925 Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
926 Vals.push_back(Log2_32(cast<AllocaInst>(I).getAlignment())+1);
929 case Instruction::Load:
930 Code = bitc::FUNC_CODE_INST_LOAD;
931 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE)) // ptr
932 AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
934 Vals.push_back(Log2_32(cast<LoadInst>(I).getAlignment())+1);
935 Vals.push_back(cast<LoadInst>(I).isVolatile());
937 case Instruction::Store:
938 Code = bitc::FUNC_CODE_INST_STORE2;
939 PushValueAndType(I.getOperand(1), InstID, Vals, VE); // ptrty + ptr
940 Vals.push_back(VE.getValueID(I.getOperand(0))); // val.
941 Vals.push_back(Log2_32(cast<StoreInst>(I).getAlignment())+1);
942 Vals.push_back(cast<StoreInst>(I).isVolatile());
944 case Instruction::Call: {
945 const PointerType *PTy = cast<PointerType>(I.getOperand(0)->getType());
946 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
948 Code = bitc::FUNC_CODE_INST_CALL;
950 const CallInst *CI = cast<CallInst>(&I);
951 Vals.push_back(VE.getAttributeID(CI->getAttributes()));
952 Vals.push_back((CI->getCallingConv() << 1) | unsigned(CI->isTailCall()));
953 PushValueAndType(CI->getOperand(0), InstID, Vals, VE); // Callee
955 // Emit value #'s for the fixed parameters.
956 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
957 Vals.push_back(VE.getValueID(I.getOperand(i+1))); // fixed param.
959 // Emit type/value pairs for varargs params.
960 if (FTy->isVarArg()) {
961 unsigned NumVarargs = I.getNumOperands()-1-FTy->getNumParams();
962 for (unsigned i = I.getNumOperands()-NumVarargs, e = I.getNumOperands();
964 PushValueAndType(I.getOperand(i), InstID, Vals, VE); // varargs
968 case Instruction::VAArg:
969 Code = bitc::FUNC_CODE_INST_VAARG;
970 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); // valistty
971 Vals.push_back(VE.getValueID(I.getOperand(0))); // valist.
972 Vals.push_back(VE.getTypeID(I.getType())); // restype.
976 Stream.EmitRecord(Code, Vals, AbbrevToUse);
980 // Emit names for globals/functions etc.
981 static void WriteValueSymbolTable(const ValueSymbolTable &VST,
982 const ValueEnumerator &VE,
983 BitstreamWriter &Stream) {
984 if (VST.empty()) return;
985 Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
987 // FIXME: Set up the abbrev, we know how many values there are!
988 // FIXME: We know if the type names can use 7-bit ascii.
989 SmallVector<unsigned, 64> NameVals;
991 for (ValueSymbolTable::const_iterator SI = VST.begin(), SE = VST.end();
994 const ValueName &Name = *SI;
996 // Figure out the encoding to use for the name.
999 for (const char *C = Name.getKeyData(), *E = C+Name.getKeyLength();
1002 isChar6 = BitCodeAbbrevOp::isChar6(*C);
1003 if ((unsigned char)*C & 128) {
1005 break; // don't bother scanning the rest.
1009 unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
1011 // VST_ENTRY: [valueid, namechar x N]
1012 // VST_BBENTRY: [bbid, namechar x N]
1014 if (isa<BasicBlock>(SI->getValue())) {
1015 Code = bitc::VST_CODE_BBENTRY;
1017 AbbrevToUse = VST_BBENTRY_6_ABBREV;
1019 Code = bitc::VST_CODE_ENTRY;
1021 AbbrevToUse = VST_ENTRY_6_ABBREV;
1023 AbbrevToUse = VST_ENTRY_7_ABBREV;
1026 NameVals.push_back(VE.getValueID(SI->getValue()));
1027 for (const char *P = Name.getKeyData(),
1028 *E = Name.getKeyData()+Name.getKeyLength(); P != E; ++P)
1029 NameVals.push_back((unsigned char)*P);
1031 // Emit the finished record.
1032 Stream.EmitRecord(Code, NameVals, AbbrevToUse);
1038 /// WriteFunction - Emit a function body to the module stream.
1039 static void WriteFunction(const Function &F, ValueEnumerator &VE,
1040 BitstreamWriter &Stream) {
1041 Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 4);
1042 VE.incorporateFunction(F);
1044 SmallVector<unsigned, 64> Vals;
1046 // Emit the number of basic blocks, so the reader can create them ahead of
1048 Vals.push_back(VE.getBasicBlocks().size());
1049 Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals);
1052 // If there are function-local constants, emit them now.
1053 unsigned CstStart, CstEnd;
1054 VE.getFunctionConstantRange(CstStart, CstEnd);
1055 WriteConstants(CstStart, CstEnd, VE, Stream, false);
1057 // Keep a running idea of what the instruction ID is.
1058 unsigned InstID = CstEnd;
1060 // Finally, emit all the instructions, in order.
1061 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1062 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
1064 WriteInstruction(*I, InstID, VE, Stream, Vals);
1065 if (I->getType() != Type::VoidTy)
1069 // Emit names for all the instructions etc.
1070 WriteValueSymbolTable(F.getValueSymbolTable(), VE, Stream);
1076 /// WriteTypeSymbolTable - Emit a block for the specified type symtab.
1077 static void WriteTypeSymbolTable(const TypeSymbolTable &TST,
1078 const ValueEnumerator &VE,
1079 BitstreamWriter &Stream) {
1080 if (TST.empty()) return;
1082 Stream.EnterSubblock(bitc::TYPE_SYMTAB_BLOCK_ID, 3);
1084 // 7-bit fixed width VST_CODE_ENTRY strings.
1085 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1086 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
1087 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
1088 Log2_32_Ceil(VE.getTypes().size()+1)));
1089 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1090 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
1091 unsigned V7Abbrev = Stream.EmitAbbrev(Abbv);
1093 SmallVector<unsigned, 64> NameVals;
1095 for (TypeSymbolTable::const_iterator TI = TST.begin(), TE = TST.end();
1097 // TST_ENTRY: [typeid, namechar x N]
1098 NameVals.push_back(VE.getTypeID(TI->second));
1100 const std::string &Str = TI->first;
1102 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
1103 NameVals.push_back((unsigned char)Str[i]);
1108 // Emit the finished record.
1109 Stream.EmitRecord(bitc::VST_CODE_ENTRY, NameVals, is7Bit ? V7Abbrev : 0);
1116 // Emit blockinfo, which defines the standard abbreviations etc.
1117 static void WriteBlockInfo(const ValueEnumerator &VE, BitstreamWriter &Stream) {
1118 // We only want to emit block info records for blocks that have multiple
1119 // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK. Other
1120 // blocks can defined their abbrevs inline.
1121 Stream.EnterBlockInfoBlock(2);
1123 { // 8-bit fixed-width VST_ENTRY/VST_BBENTRY strings.
1124 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1125 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3));
1126 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1127 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1128 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
1129 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1130 Abbv) != VST_ENTRY_8_ABBREV)
1131 llvm_unreachable("Unexpected abbrev ordering!");
1134 { // 7-bit fixed width VST_ENTRY strings.
1135 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1136 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
1137 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1138 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1139 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
1140 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1141 Abbv) != VST_ENTRY_7_ABBREV)
1142 llvm_unreachable("Unexpected abbrev ordering!");
1144 { // 6-bit char6 VST_ENTRY strings.
1145 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1146 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
1147 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1148 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1149 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
1150 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1151 Abbv) != VST_ENTRY_6_ABBREV)
1152 llvm_unreachable("Unexpected abbrev ordering!");
1154 { // 6-bit char6 VST_BBENTRY strings.
1155 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1156 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY));
1157 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1158 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1159 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
1160 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1161 Abbv) != VST_BBENTRY_6_ABBREV)
1162 llvm_unreachable("Unexpected abbrev ordering!");
1167 { // SETTYPE abbrev for CONSTANTS_BLOCK.
1168 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1169 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_SETTYPE));
1170 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
1171 Log2_32_Ceil(VE.getTypes().size()+1)));
1172 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1173 Abbv) != CONSTANTS_SETTYPE_ABBREV)
1174 llvm_unreachable("Unexpected abbrev ordering!");
1177 { // INTEGER abbrev for CONSTANTS_BLOCK.
1178 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1179 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_INTEGER));
1180 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1181 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1182 Abbv) != CONSTANTS_INTEGER_ABBREV)
1183 llvm_unreachable("Unexpected abbrev ordering!");
1186 { // CE_CAST abbrev for CONSTANTS_BLOCK.
1187 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1188 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CE_CAST));
1189 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // cast opc
1190 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // typeid
1191 Log2_32_Ceil(VE.getTypes().size()+1)));
1192 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
1194 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1195 Abbv) != CONSTANTS_CE_CAST_Abbrev)
1196 llvm_unreachable("Unexpected abbrev ordering!");
1198 { // NULL abbrev for CONSTANTS_BLOCK.
1199 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1200 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_NULL));
1201 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1202 Abbv) != CONSTANTS_NULL_Abbrev)
1203 llvm_unreachable("Unexpected abbrev ordering!");
1206 // FIXME: This should only use space for first class types!
1208 { // INST_LOAD abbrev for FUNCTION_BLOCK.
1209 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1210 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_LOAD));
1211 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Ptr
1212 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align
1213 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile
1214 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1215 Abbv) != FUNCTION_INST_LOAD_ABBREV)
1216 llvm_unreachable("Unexpected abbrev ordering!");
1218 { // INST_BINOP abbrev for FUNCTION_BLOCK.
1219 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1220 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
1221 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
1222 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
1223 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
1224 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1225 Abbv) != FUNCTION_INST_BINOP_ABBREV)
1226 llvm_unreachable("Unexpected abbrev ordering!");
1228 { // INST_CAST abbrev for FUNCTION_BLOCK.
1229 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1230 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST));
1231 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // OpVal
1232 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
1233 Log2_32_Ceil(VE.getTypes().size()+1)));
1234 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
1235 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1236 Abbv) != FUNCTION_INST_CAST_ABBREV)
1237 llvm_unreachable("Unexpected abbrev ordering!");
1240 { // INST_RET abbrev for FUNCTION_BLOCK.
1241 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1242 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
1243 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1244 Abbv) != FUNCTION_INST_RET_VOID_ABBREV)
1245 llvm_unreachable("Unexpected abbrev ordering!");
1247 { // INST_RET abbrev for FUNCTION_BLOCK.
1248 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1249 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
1250 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ValID
1251 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1252 Abbv) != FUNCTION_INST_RET_VAL_ABBREV)
1253 llvm_unreachable("Unexpected abbrev ordering!");
1255 { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK.
1256 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1257 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNREACHABLE));
1258 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1259 Abbv) != FUNCTION_INST_UNREACHABLE_ABBREV)
1260 llvm_unreachable("Unexpected abbrev ordering!");
1267 /// WriteModule - Emit the specified module to the bitstream.
1268 static void WriteModule(const Module *M, BitstreamWriter &Stream) {
1269 Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
1271 // Emit the version number if it is non-zero.
1273 SmallVector<unsigned, 1> Vals;
1274 Vals.push_back(CurVersion);
1275 Stream.EmitRecord(bitc::MODULE_CODE_VERSION, Vals);
1278 // Analyze the module, enumerating globals, functions, etc.
1279 ValueEnumerator VE(M);
1281 // Emit blockinfo, which defines the standard abbreviations etc.
1282 WriteBlockInfo(VE, Stream);
1284 // Emit information about parameter attributes.
1285 WriteAttributeTable(VE, Stream);
1287 // Emit information describing all of the types in the module.
1288 WriteTypeTable(VE, Stream);
1290 // Emit top-level description of module, including target triple, inline asm,
1291 // descriptors for global variables, and function prototype info.
1292 WriteModuleInfo(M, VE, Stream);
1295 WriteModuleConstants(VE, Stream);
1297 // Emit function bodies.
1298 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
1299 if (!I->isDeclaration())
1300 WriteFunction(*I, VE, Stream);
1302 // Emit the type symbol table information.
1303 WriteTypeSymbolTable(M->getTypeSymbolTable(), VE, Stream);
1305 // Emit names for globals/functions etc.
1306 WriteValueSymbolTable(M->getValueSymbolTable(), VE, Stream);
1311 /// EmitDarwinBCHeader - If generating a bc file on darwin, we have to emit a
1312 /// header and trailer to make it compatible with the system archiver. To do
1313 /// this we emit the following header, and then emit a trailer that pads the
1314 /// file out to be a multiple of 16 bytes.
1316 /// struct bc_header {
1317 /// uint32_t Magic; // 0x0B17C0DE
1318 /// uint32_t Version; // Version, currently always 0.
1319 /// uint32_t BitcodeOffset; // Offset to traditional bitcode file.
1320 /// uint32_t BitcodeSize; // Size of traditional bitcode file.
1321 /// uint32_t CPUType; // CPU specifier.
1322 /// ... potentially more later ...
1325 DarwinBCSizeFieldOffset = 3*4, // Offset to bitcode_size.
1326 DarwinBCHeaderSize = 5*4
1329 static void EmitDarwinBCHeader(BitstreamWriter &Stream,
1330 const std::string &TT) {
1331 unsigned CPUType = ~0U;
1333 // Match x86_64-*, i[3-9]86-*, powerpc-*, powerpc64-*. The CPUType is a
1334 // magic number from /usr/include/mach/machine.h. It is ok to reproduce the
1335 // specific constants here because they are implicitly part of the Darwin ABI.
1337 DARWIN_CPU_ARCH_ABI64 = 0x01000000,
1338 DARWIN_CPU_TYPE_X86 = 7,
1339 DARWIN_CPU_TYPE_POWERPC = 18
1342 if (TT.find("x86_64-") == 0)
1343 CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64;
1344 else if (TT.size() >= 5 && TT[0] == 'i' && TT[2] == '8' && TT[3] == '6' &&
1345 TT[4] == '-' && TT[1] - '3' < 6)
1346 CPUType = DARWIN_CPU_TYPE_X86;
1347 else if (TT.find("powerpc-") == 0)
1348 CPUType = DARWIN_CPU_TYPE_POWERPC;
1349 else if (TT.find("powerpc64-") == 0)
1350 CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64;
1352 // Traditional Bitcode starts after header.
1353 unsigned BCOffset = DarwinBCHeaderSize;
1355 Stream.Emit(0x0B17C0DE, 32);
1356 Stream.Emit(0 , 32); // Version.
1357 Stream.Emit(BCOffset , 32);
1358 Stream.Emit(0 , 32); // Filled in later.
1359 Stream.Emit(CPUType , 32);
1362 /// EmitDarwinBCTrailer - Emit the darwin epilog after the bitcode file and
1363 /// finalize the header.
1364 static void EmitDarwinBCTrailer(BitstreamWriter &Stream, unsigned BufferSize) {
1365 // Update the size field in the header.
1366 Stream.BackpatchWord(DarwinBCSizeFieldOffset, BufferSize-DarwinBCHeaderSize);
1368 // If the file is not a multiple of 16 bytes, insert dummy padding.
1369 while (BufferSize & 15) {
1376 /// WriteBitcodeToFile - Write the specified module to the specified output
1378 void llvm::WriteBitcodeToFile(const Module *M, std::ostream &Out) {
1379 raw_os_ostream RawOut(Out);
1380 // If writing to stdout, set binary mode.
1381 if (llvm::cout == Out)
1382 sys::Program::ChangeStdoutToBinary();
1383 WriteBitcodeToFile(M, RawOut);
1386 /// WriteBitcodeToFile - Write the specified module to the specified output
1388 void llvm::WriteBitcodeToFile(const Module *M, raw_ostream &Out) {
1389 std::vector<unsigned char> Buffer;
1390 BitstreamWriter Stream(Buffer);
1392 Buffer.reserve(256*1024);
1394 WriteBitcodeToStream( M, Stream );
1396 // If writing to stdout, set binary mode.
1397 if (&llvm::outs() == &Out)
1398 sys::Program::ChangeStdoutToBinary();
1400 // Write the generated bitstream to "Out".
1401 Out.write((char*)&Buffer.front(), Buffer.size());
1403 // Make sure it hits disk now.
1407 /// WriteBitcodeToStream - Write the specified module to the specified output
1409 void llvm::WriteBitcodeToStream(const Module *M, BitstreamWriter &Stream) {
1410 // If this is darwin, emit a file header and trailer if needed.
1411 bool isDarwin = M->getTargetTriple().find("-darwin") != std::string::npos;
1413 EmitDarwinBCHeader(Stream, M->getTargetTriple());
1415 // Emit the file header.
1416 Stream.Emit((unsigned)'B', 8);
1417 Stream.Emit((unsigned)'C', 8);
1418 Stream.Emit(0x0, 4);
1419 Stream.Emit(0xC, 4);
1420 Stream.Emit(0xE, 4);
1421 Stream.Emit(0xD, 4);
1424 WriteModule(M, Stream);
1427 EmitDarwinBCTrailer(Stream, Stream.getBuffer().size());