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 "ValueEnumerator.h"
16 #include "llvm/ADT/Triple.h"
17 #include "llvm/Bitcode/BitstreamWriter.h"
18 #include "llvm/Bitcode/LLVMBitCodes.h"
19 #include "llvm/IR/Constants.h"
20 #include "llvm/IR/DerivedTypes.h"
21 #include "llvm/IR/InlineAsm.h"
22 #include "llvm/IR/Instructions.h"
23 #include "llvm/IR/Module.h"
24 #include "llvm/IR/Operator.h"
25 #include "llvm/IR/ValueSymbolTable.h"
26 #include "llvm/Support/CommandLine.h"
27 #include "llvm/Support/ErrorHandling.h"
28 #include "llvm/Support/MathExtras.h"
29 #include "llvm/Support/Program.h"
30 #include "llvm/Support/raw_ostream.h"
36 EnablePreserveUseListOrdering("enable-bc-uselist-preserve",
37 cl::desc("Turn on experimental support for "
38 "use-list order preservation."),
39 cl::init(false), cl::Hidden);
41 /// These are manifest constants used by the bitcode writer. They do not need to
42 /// be kept in sync with the reader, but need to be consistent within this file.
44 // VALUE_SYMTAB_BLOCK abbrev id's.
45 VST_ENTRY_8_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
50 // CONSTANTS_BLOCK abbrev id's.
51 CONSTANTS_SETTYPE_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
52 CONSTANTS_INTEGER_ABBREV,
53 CONSTANTS_CE_CAST_Abbrev,
54 CONSTANTS_NULL_Abbrev,
56 // FUNCTION_BLOCK abbrev id's.
57 FUNCTION_INST_LOAD_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
58 FUNCTION_INST_BINOP_ABBREV,
59 FUNCTION_INST_BINOP_FLAGS_ABBREV,
60 FUNCTION_INST_CAST_ABBREV,
61 FUNCTION_INST_RET_VOID_ABBREV,
62 FUNCTION_INST_RET_VAL_ABBREV,
63 FUNCTION_INST_UNREACHABLE_ABBREV,
66 SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
69 static unsigned GetEncodedCastOpcode(unsigned Opcode) {
71 default: llvm_unreachable("Unknown cast instruction!");
72 case Instruction::Trunc : return bitc::CAST_TRUNC;
73 case Instruction::ZExt : return bitc::CAST_ZEXT;
74 case Instruction::SExt : return bitc::CAST_SEXT;
75 case Instruction::FPToUI : return bitc::CAST_FPTOUI;
76 case Instruction::FPToSI : return bitc::CAST_FPTOSI;
77 case Instruction::UIToFP : return bitc::CAST_UITOFP;
78 case Instruction::SIToFP : return bitc::CAST_SITOFP;
79 case Instruction::FPTrunc : return bitc::CAST_FPTRUNC;
80 case Instruction::FPExt : return bitc::CAST_FPEXT;
81 case Instruction::PtrToInt: return bitc::CAST_PTRTOINT;
82 case Instruction::IntToPtr: return bitc::CAST_INTTOPTR;
83 case Instruction::BitCast : return bitc::CAST_BITCAST;
87 static unsigned GetEncodedBinaryOpcode(unsigned Opcode) {
89 default: llvm_unreachable("Unknown binary instruction!");
90 case Instruction::Add:
91 case Instruction::FAdd: return bitc::BINOP_ADD;
92 case Instruction::Sub:
93 case Instruction::FSub: return bitc::BINOP_SUB;
94 case Instruction::Mul:
95 case Instruction::FMul: return bitc::BINOP_MUL;
96 case Instruction::UDiv: return bitc::BINOP_UDIV;
97 case Instruction::FDiv:
98 case Instruction::SDiv: return bitc::BINOP_SDIV;
99 case Instruction::URem: return bitc::BINOP_UREM;
100 case Instruction::FRem:
101 case Instruction::SRem: return bitc::BINOP_SREM;
102 case Instruction::Shl: return bitc::BINOP_SHL;
103 case Instruction::LShr: return bitc::BINOP_LSHR;
104 case Instruction::AShr: return bitc::BINOP_ASHR;
105 case Instruction::And: return bitc::BINOP_AND;
106 case Instruction::Or: return bitc::BINOP_OR;
107 case Instruction::Xor: return bitc::BINOP_XOR;
111 static unsigned GetEncodedRMWOperation(AtomicRMWInst::BinOp Op) {
113 default: llvm_unreachable("Unknown RMW operation!");
114 case AtomicRMWInst::Xchg: return bitc::RMW_XCHG;
115 case AtomicRMWInst::Add: return bitc::RMW_ADD;
116 case AtomicRMWInst::Sub: return bitc::RMW_SUB;
117 case AtomicRMWInst::And: return bitc::RMW_AND;
118 case AtomicRMWInst::Nand: return bitc::RMW_NAND;
119 case AtomicRMWInst::Or: return bitc::RMW_OR;
120 case AtomicRMWInst::Xor: return bitc::RMW_XOR;
121 case AtomicRMWInst::Max: return bitc::RMW_MAX;
122 case AtomicRMWInst::Min: return bitc::RMW_MIN;
123 case AtomicRMWInst::UMax: return bitc::RMW_UMAX;
124 case AtomicRMWInst::UMin: return bitc::RMW_UMIN;
128 static unsigned GetEncodedOrdering(AtomicOrdering Ordering) {
130 case NotAtomic: return bitc::ORDERING_NOTATOMIC;
131 case Unordered: return bitc::ORDERING_UNORDERED;
132 case Monotonic: return bitc::ORDERING_MONOTONIC;
133 case Acquire: return bitc::ORDERING_ACQUIRE;
134 case Release: return bitc::ORDERING_RELEASE;
135 case AcquireRelease: return bitc::ORDERING_ACQREL;
136 case SequentiallyConsistent: return bitc::ORDERING_SEQCST;
138 llvm_unreachable("Invalid ordering");
141 static unsigned GetEncodedSynchScope(SynchronizationScope SynchScope) {
142 switch (SynchScope) {
143 case SingleThread: return bitc::SYNCHSCOPE_SINGLETHREAD;
144 case CrossThread: return bitc::SYNCHSCOPE_CROSSTHREAD;
146 llvm_unreachable("Invalid synch scope");
149 static void WriteStringRecord(unsigned Code, StringRef Str,
150 unsigned AbbrevToUse, BitstreamWriter &Stream) {
151 SmallVector<unsigned, 64> Vals;
153 // Code: [strchar x N]
154 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
155 if (AbbrevToUse && !BitCodeAbbrevOp::isChar6(Str[i]))
157 Vals.push_back(Str[i]);
160 // Emit the finished record.
161 Stream.EmitRecord(Code, Vals, AbbrevToUse);
164 static uint64_t getAttrKindEncoding(Attribute::AttrKind Kind) {
166 case Attribute::Alignment:
167 return bitc::ATTR_KIND_ALIGNMENT;
168 case Attribute::AlwaysInline:
169 return bitc::ATTR_KIND_ALWAYS_INLINE;
170 case Attribute::Builtin:
171 return bitc::ATTR_KIND_BUILTIN;
172 case Attribute::ByVal:
173 return bitc::ATTR_KIND_BY_VAL;
174 case Attribute::Cold:
175 return bitc::ATTR_KIND_COLD;
176 case Attribute::InlineHint:
177 return bitc::ATTR_KIND_INLINE_HINT;
178 case Attribute::InReg:
179 return bitc::ATTR_KIND_IN_REG;
180 case Attribute::MinSize:
181 return bitc::ATTR_KIND_MIN_SIZE;
182 case Attribute::Naked:
183 return bitc::ATTR_KIND_NAKED;
184 case Attribute::Nest:
185 return bitc::ATTR_KIND_NEST;
186 case Attribute::NoAlias:
187 return bitc::ATTR_KIND_NO_ALIAS;
188 case Attribute::NoBuiltin:
189 return bitc::ATTR_KIND_NO_BUILTIN;
190 case Attribute::NoCapture:
191 return bitc::ATTR_KIND_NO_CAPTURE;
192 case Attribute::NoDuplicate:
193 return bitc::ATTR_KIND_NO_DUPLICATE;
194 case Attribute::NoImplicitFloat:
195 return bitc::ATTR_KIND_NO_IMPLICIT_FLOAT;
196 case Attribute::NoInline:
197 return bitc::ATTR_KIND_NO_INLINE;
198 case Attribute::NonLazyBind:
199 return bitc::ATTR_KIND_NON_LAZY_BIND;
200 case Attribute::NoRedZone:
201 return bitc::ATTR_KIND_NO_RED_ZONE;
202 case Attribute::NoReturn:
203 return bitc::ATTR_KIND_NO_RETURN;
204 case Attribute::NoUnwind:
205 return bitc::ATTR_KIND_NO_UNWIND;
206 case Attribute::OptimizeForSize:
207 return bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE;
208 case Attribute::OptimizeNone:
209 return bitc::ATTR_KIND_OPTIMIZE_NONE;
210 case Attribute::ReadNone:
211 return bitc::ATTR_KIND_READ_NONE;
212 case Attribute::ReadOnly:
213 return bitc::ATTR_KIND_READ_ONLY;
214 case Attribute::Returned:
215 return bitc::ATTR_KIND_RETURNED;
216 case Attribute::ReturnsTwice:
217 return bitc::ATTR_KIND_RETURNS_TWICE;
218 case Attribute::SExt:
219 return bitc::ATTR_KIND_S_EXT;
220 case Attribute::StackAlignment:
221 return bitc::ATTR_KIND_STACK_ALIGNMENT;
222 case Attribute::StackProtect:
223 return bitc::ATTR_KIND_STACK_PROTECT;
224 case Attribute::StackProtectReq:
225 return bitc::ATTR_KIND_STACK_PROTECT_REQ;
226 case Attribute::StackProtectStrong:
227 return bitc::ATTR_KIND_STACK_PROTECT_STRONG;
228 case Attribute::StructRet:
229 return bitc::ATTR_KIND_STRUCT_RET;
230 case Attribute::SanitizeAddress:
231 return bitc::ATTR_KIND_SANITIZE_ADDRESS;
232 case Attribute::SanitizeThread:
233 return bitc::ATTR_KIND_SANITIZE_THREAD;
234 case Attribute::SanitizeMemory:
235 return bitc::ATTR_KIND_SANITIZE_MEMORY;
236 case Attribute::UWTable:
237 return bitc::ATTR_KIND_UW_TABLE;
238 case Attribute::ZExt:
239 return bitc::ATTR_KIND_Z_EXT;
240 case Attribute::EndAttrKinds:
241 llvm_unreachable("Can not encode end-attribute kinds marker.");
242 case Attribute::None:
243 llvm_unreachable("Can not encode none-attribute.");
246 llvm_unreachable("Trying to encode unknown attribute");
249 static void WriteAttributeGroupTable(const ValueEnumerator &VE,
250 BitstreamWriter &Stream) {
251 const std::vector<AttributeSet> &AttrGrps = VE.getAttributeGroups();
252 if (AttrGrps.empty()) return;
254 Stream.EnterSubblock(bitc::PARAMATTR_GROUP_BLOCK_ID, 3);
256 SmallVector<uint64_t, 64> Record;
257 for (unsigned i = 0, e = AttrGrps.size(); i != e; ++i) {
258 AttributeSet AS = AttrGrps[i];
259 for (unsigned i = 0, e = AS.getNumSlots(); i != e; ++i) {
260 AttributeSet A = AS.getSlotAttributes(i);
262 Record.push_back(VE.getAttributeGroupID(A));
263 Record.push_back(AS.getSlotIndex(i));
265 for (AttributeSet::iterator I = AS.begin(0), E = AS.end(0);
268 if (Attr.isEnumAttribute()) {
270 Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
271 } else if (Attr.isAlignAttribute()) {
273 Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
274 Record.push_back(Attr.getValueAsInt());
276 StringRef Kind = Attr.getKindAsString();
277 StringRef Val = Attr.getValueAsString();
279 Record.push_back(Val.empty() ? 3 : 4);
280 Record.append(Kind.begin(), Kind.end());
283 Record.append(Val.begin(), Val.end());
289 Stream.EmitRecord(bitc::PARAMATTR_GRP_CODE_ENTRY, Record);
297 static void WriteAttributeTable(const ValueEnumerator &VE,
298 BitstreamWriter &Stream) {
299 const std::vector<AttributeSet> &Attrs = VE.getAttributes();
300 if (Attrs.empty()) return;
302 Stream.EnterSubblock(bitc::PARAMATTR_BLOCK_ID, 3);
304 SmallVector<uint64_t, 64> Record;
305 for (unsigned i = 0, e = Attrs.size(); i != e; ++i) {
306 const AttributeSet &A = Attrs[i];
307 for (unsigned i = 0, e = A.getNumSlots(); i != e; ++i)
308 Record.push_back(VE.getAttributeGroupID(A.getSlotAttributes(i)));
310 Stream.EmitRecord(bitc::PARAMATTR_CODE_ENTRY, Record);
317 /// WriteTypeTable - Write out the type table for a module.
318 static void WriteTypeTable(const ValueEnumerator &VE, BitstreamWriter &Stream) {
319 const ValueEnumerator::TypeList &TypeList = VE.getTypes();
321 Stream.EnterSubblock(bitc::TYPE_BLOCK_ID_NEW, 4 /*count from # abbrevs */);
322 SmallVector<uint64_t, 64> TypeVals;
324 uint64_t NumBits = Log2_32_Ceil(VE.getTypes().size()+1);
326 // Abbrev for TYPE_CODE_POINTER.
327 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
328 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_POINTER));
329 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
330 Abbv->Add(BitCodeAbbrevOp(0)); // Addrspace = 0
331 unsigned PtrAbbrev = Stream.EmitAbbrev(Abbv);
333 // Abbrev for TYPE_CODE_FUNCTION.
334 Abbv = new BitCodeAbbrev();
335 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_FUNCTION));
336 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // isvararg
337 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
338 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
340 unsigned FunctionAbbrev = Stream.EmitAbbrev(Abbv);
342 // Abbrev for TYPE_CODE_STRUCT_ANON.
343 Abbv = new BitCodeAbbrev();
344 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_ANON));
345 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
346 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
347 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
349 unsigned StructAnonAbbrev = Stream.EmitAbbrev(Abbv);
351 // Abbrev for TYPE_CODE_STRUCT_NAME.
352 Abbv = new BitCodeAbbrev();
353 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAME));
354 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
355 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
356 unsigned StructNameAbbrev = Stream.EmitAbbrev(Abbv);
358 // Abbrev for TYPE_CODE_STRUCT_NAMED.
359 Abbv = new BitCodeAbbrev();
360 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAMED));
361 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
362 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
363 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
365 unsigned StructNamedAbbrev = Stream.EmitAbbrev(Abbv);
367 // Abbrev for TYPE_CODE_ARRAY.
368 Abbv = new BitCodeAbbrev();
369 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_ARRAY));
370 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // size
371 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
373 unsigned ArrayAbbrev = Stream.EmitAbbrev(Abbv);
375 // Emit an entry count so the reader can reserve space.
376 TypeVals.push_back(TypeList.size());
377 Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals);
380 // Loop over all of the types, emitting each in turn.
381 for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
382 Type *T = TypeList[i];
386 switch (T->getTypeID()) {
387 default: llvm_unreachable("Unknown type!");
388 case Type::VoidTyID: Code = bitc::TYPE_CODE_VOID; break;
389 case Type::HalfTyID: Code = bitc::TYPE_CODE_HALF; break;
390 case Type::FloatTyID: Code = bitc::TYPE_CODE_FLOAT; break;
391 case Type::DoubleTyID: Code = bitc::TYPE_CODE_DOUBLE; break;
392 case Type::X86_FP80TyID: Code = bitc::TYPE_CODE_X86_FP80; break;
393 case Type::FP128TyID: Code = bitc::TYPE_CODE_FP128; break;
394 case Type::PPC_FP128TyID: Code = bitc::TYPE_CODE_PPC_FP128; break;
395 case Type::LabelTyID: Code = bitc::TYPE_CODE_LABEL; break;
396 case Type::MetadataTyID: Code = bitc::TYPE_CODE_METADATA; break;
397 case Type::X86_MMXTyID: Code = bitc::TYPE_CODE_X86_MMX; break;
398 case Type::IntegerTyID:
400 Code = bitc::TYPE_CODE_INTEGER;
401 TypeVals.push_back(cast<IntegerType>(T)->getBitWidth());
403 case Type::PointerTyID: {
404 PointerType *PTy = cast<PointerType>(T);
405 // POINTER: [pointee type, address space]
406 Code = bitc::TYPE_CODE_POINTER;
407 TypeVals.push_back(VE.getTypeID(PTy->getElementType()));
408 unsigned AddressSpace = PTy->getAddressSpace();
409 TypeVals.push_back(AddressSpace);
410 if (AddressSpace == 0) AbbrevToUse = PtrAbbrev;
413 case Type::FunctionTyID: {
414 FunctionType *FT = cast<FunctionType>(T);
415 // FUNCTION: [isvararg, retty, paramty x N]
416 Code = bitc::TYPE_CODE_FUNCTION;
417 TypeVals.push_back(FT->isVarArg());
418 TypeVals.push_back(VE.getTypeID(FT->getReturnType()));
419 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
420 TypeVals.push_back(VE.getTypeID(FT->getParamType(i)));
421 AbbrevToUse = FunctionAbbrev;
424 case Type::StructTyID: {
425 StructType *ST = cast<StructType>(T);
426 // STRUCT: [ispacked, eltty x N]
427 TypeVals.push_back(ST->isPacked());
428 // Output all of the element types.
429 for (StructType::element_iterator I = ST->element_begin(),
430 E = ST->element_end(); I != E; ++I)
431 TypeVals.push_back(VE.getTypeID(*I));
433 if (ST->isLiteral()) {
434 Code = bitc::TYPE_CODE_STRUCT_ANON;
435 AbbrevToUse = StructAnonAbbrev;
437 if (ST->isOpaque()) {
438 Code = bitc::TYPE_CODE_OPAQUE;
440 Code = bitc::TYPE_CODE_STRUCT_NAMED;
441 AbbrevToUse = StructNamedAbbrev;
444 // Emit the name if it is present.
445 if (!ST->getName().empty())
446 WriteStringRecord(bitc::TYPE_CODE_STRUCT_NAME, ST->getName(),
447 StructNameAbbrev, Stream);
451 case Type::ArrayTyID: {
452 ArrayType *AT = cast<ArrayType>(T);
453 // ARRAY: [numelts, eltty]
454 Code = bitc::TYPE_CODE_ARRAY;
455 TypeVals.push_back(AT->getNumElements());
456 TypeVals.push_back(VE.getTypeID(AT->getElementType()));
457 AbbrevToUse = ArrayAbbrev;
460 case Type::VectorTyID: {
461 VectorType *VT = cast<VectorType>(T);
462 // VECTOR [numelts, eltty]
463 Code = bitc::TYPE_CODE_VECTOR;
464 TypeVals.push_back(VT->getNumElements());
465 TypeVals.push_back(VE.getTypeID(VT->getElementType()));
470 // Emit the finished record.
471 Stream.EmitRecord(Code, TypeVals, AbbrevToUse);
478 static unsigned getEncodedLinkage(const GlobalValue *GV) {
479 switch (GV->getLinkage()) {
480 case GlobalValue::ExternalLinkage: return 0;
481 case GlobalValue::WeakAnyLinkage: return 1;
482 case GlobalValue::AppendingLinkage: return 2;
483 case GlobalValue::InternalLinkage: return 3;
484 case GlobalValue::LinkOnceAnyLinkage: return 4;
485 case GlobalValue::DLLImportLinkage: return 5;
486 case GlobalValue::DLLExportLinkage: return 6;
487 case GlobalValue::ExternalWeakLinkage: return 7;
488 case GlobalValue::CommonLinkage: return 8;
489 case GlobalValue::PrivateLinkage: return 9;
490 case GlobalValue::WeakODRLinkage: return 10;
491 case GlobalValue::LinkOnceODRLinkage: return 11;
492 case GlobalValue::AvailableExternallyLinkage: return 12;
493 case GlobalValue::LinkerPrivateLinkage: return 13;
494 case GlobalValue::LinkerPrivateWeakLinkage: return 14;
495 case GlobalValue::LinkOnceODRAutoHideLinkage: return 15;
497 llvm_unreachable("Invalid linkage");
500 static unsigned getEncodedVisibility(const GlobalValue *GV) {
501 switch (GV->getVisibility()) {
502 case GlobalValue::DefaultVisibility: return 0;
503 case GlobalValue::HiddenVisibility: return 1;
504 case GlobalValue::ProtectedVisibility: return 2;
506 llvm_unreachable("Invalid visibility");
509 static unsigned getEncodedThreadLocalMode(const GlobalVariable *GV) {
510 switch (GV->getThreadLocalMode()) {
511 case GlobalVariable::NotThreadLocal: return 0;
512 case GlobalVariable::GeneralDynamicTLSModel: return 1;
513 case GlobalVariable::LocalDynamicTLSModel: return 2;
514 case GlobalVariable::InitialExecTLSModel: return 3;
515 case GlobalVariable::LocalExecTLSModel: return 4;
517 llvm_unreachable("Invalid TLS model");
520 // Emit top-level description of module, including target triple, inline asm,
521 // descriptors for global variables, and function prototype info.
522 static void WriteModuleInfo(const Module *M, const ValueEnumerator &VE,
523 BitstreamWriter &Stream) {
524 // Emit various pieces of data attached to a module.
525 if (!M->getTargetTriple().empty())
526 WriteStringRecord(bitc::MODULE_CODE_TRIPLE, M->getTargetTriple(),
528 if (!M->getDataLayout().empty())
529 WriteStringRecord(bitc::MODULE_CODE_DATALAYOUT, M->getDataLayout(),
531 if (!M->getModuleInlineAsm().empty())
532 WriteStringRecord(bitc::MODULE_CODE_ASM, M->getModuleInlineAsm(),
535 // Emit information about sections and GC, computing how many there are. Also
536 // compute the maximum alignment value.
537 std::map<std::string, unsigned> SectionMap;
538 std::map<std::string, unsigned> GCMap;
539 unsigned MaxAlignment = 0;
540 unsigned MaxGlobalType = 0;
541 for (Module::const_global_iterator GV = M->global_begin(),E = M->global_end();
543 MaxAlignment = std::max(MaxAlignment, GV->getAlignment());
544 MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV->getType()));
545 if (GV->hasSection()) {
546 // Give section names unique ID's.
547 unsigned &Entry = SectionMap[GV->getSection()];
549 WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, GV->getSection(),
551 Entry = SectionMap.size();
555 for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) {
556 MaxAlignment = std::max(MaxAlignment, F->getAlignment());
557 if (F->hasSection()) {
558 // Give section names unique ID's.
559 unsigned &Entry = SectionMap[F->getSection()];
561 WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, F->getSection(),
563 Entry = SectionMap.size();
567 // Same for GC names.
568 unsigned &Entry = GCMap[F->getGC()];
570 WriteStringRecord(bitc::MODULE_CODE_GCNAME, F->getGC(),
572 Entry = GCMap.size();
577 // Emit abbrev for globals, now that we know # sections and max alignment.
578 unsigned SimpleGVarAbbrev = 0;
579 if (!M->global_empty()) {
580 // Add an abbrev for common globals with no visibility or thread localness.
581 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
582 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GLOBALVAR));
583 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
584 Log2_32_Ceil(MaxGlobalType+1)));
585 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Constant.
586 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Initializer.
587 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // Linkage.
588 if (MaxAlignment == 0) // Alignment.
589 Abbv->Add(BitCodeAbbrevOp(0));
591 unsigned MaxEncAlignment = Log2_32(MaxAlignment)+1;
592 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
593 Log2_32_Ceil(MaxEncAlignment+1)));
595 if (SectionMap.empty()) // Section.
596 Abbv->Add(BitCodeAbbrevOp(0));
598 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
599 Log2_32_Ceil(SectionMap.size()+1)));
600 // Don't bother emitting vis + thread local.
601 SimpleGVarAbbrev = Stream.EmitAbbrev(Abbv);
604 // Emit the global variable information.
605 SmallVector<unsigned, 64> Vals;
606 for (Module::const_global_iterator GV = M->global_begin(),E = M->global_end();
608 unsigned AbbrevToUse = 0;
610 // GLOBALVAR: [type, isconst, initid,
611 // linkage, alignment, section, visibility, threadlocal,
613 Vals.push_back(VE.getTypeID(GV->getType()));
614 Vals.push_back(GV->isConstant());
615 Vals.push_back(GV->isDeclaration() ? 0 :
616 (VE.getValueID(GV->getInitializer()) + 1));
617 Vals.push_back(getEncodedLinkage(GV));
618 Vals.push_back(Log2_32(GV->getAlignment())+1);
619 Vals.push_back(GV->hasSection() ? SectionMap[GV->getSection()] : 0);
620 if (GV->isThreadLocal() ||
621 GV->getVisibility() != GlobalValue::DefaultVisibility ||
622 GV->hasUnnamedAddr() || GV->isExternallyInitialized()) {
623 Vals.push_back(getEncodedVisibility(GV));
624 Vals.push_back(getEncodedThreadLocalMode(GV));
625 Vals.push_back(GV->hasUnnamedAddr());
626 Vals.push_back(GV->isExternallyInitialized());
628 AbbrevToUse = SimpleGVarAbbrev;
631 Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse);
635 // Emit the function proto information.
636 for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) {
637 // FUNCTION: [type, callingconv, isproto, linkage, paramattrs, alignment,
638 // section, visibility, gc, unnamed_addr]
639 Vals.push_back(VE.getTypeID(F->getType()));
640 Vals.push_back(F->getCallingConv());
641 Vals.push_back(F->isDeclaration());
642 Vals.push_back(getEncodedLinkage(F));
643 Vals.push_back(VE.getAttributeID(F->getAttributes()));
644 Vals.push_back(Log2_32(F->getAlignment())+1);
645 Vals.push_back(F->hasSection() ? SectionMap[F->getSection()] : 0);
646 Vals.push_back(getEncodedVisibility(F));
647 Vals.push_back(F->hasGC() ? GCMap[F->getGC()] : 0);
648 Vals.push_back(F->hasUnnamedAddr());
650 unsigned AbbrevToUse = 0;
651 Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse);
655 // Emit the alias information.
656 for (Module::const_alias_iterator AI = M->alias_begin(), E = M->alias_end();
658 // ALIAS: [alias type, aliasee val#, linkage, visibility]
659 Vals.push_back(VE.getTypeID(AI->getType()));
660 Vals.push_back(VE.getValueID(AI->getAliasee()));
661 Vals.push_back(getEncodedLinkage(AI));
662 Vals.push_back(getEncodedVisibility(AI));
663 unsigned AbbrevToUse = 0;
664 Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse);
669 static uint64_t GetOptimizationFlags(const Value *V) {
672 if (const OverflowingBinaryOperator *OBO =
673 dyn_cast<OverflowingBinaryOperator>(V)) {
674 if (OBO->hasNoSignedWrap())
675 Flags |= 1 << bitc::OBO_NO_SIGNED_WRAP;
676 if (OBO->hasNoUnsignedWrap())
677 Flags |= 1 << bitc::OBO_NO_UNSIGNED_WRAP;
678 } else if (const PossiblyExactOperator *PEO =
679 dyn_cast<PossiblyExactOperator>(V)) {
681 Flags |= 1 << bitc::PEO_EXACT;
682 } else if (const FPMathOperator *FPMO =
683 dyn_cast<const FPMathOperator>(V)) {
684 if (FPMO->hasUnsafeAlgebra())
685 Flags |= FastMathFlags::UnsafeAlgebra;
686 if (FPMO->hasNoNaNs())
687 Flags |= FastMathFlags::NoNaNs;
688 if (FPMO->hasNoInfs())
689 Flags |= FastMathFlags::NoInfs;
690 if (FPMO->hasNoSignedZeros())
691 Flags |= FastMathFlags::NoSignedZeros;
692 if (FPMO->hasAllowReciprocal())
693 Flags |= FastMathFlags::AllowReciprocal;
699 static void WriteMDNode(const MDNode *N,
700 const ValueEnumerator &VE,
701 BitstreamWriter &Stream,
702 SmallVectorImpl<uint64_t> &Record) {
703 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
704 if (N->getOperand(i)) {
705 Record.push_back(VE.getTypeID(N->getOperand(i)->getType()));
706 Record.push_back(VE.getValueID(N->getOperand(i)));
708 Record.push_back(VE.getTypeID(Type::getVoidTy(N->getContext())));
712 unsigned MDCode = N->isFunctionLocal() ? bitc::METADATA_FN_NODE :
714 Stream.EmitRecord(MDCode, Record, 0);
718 static void WriteModuleMetadata(const Module *M,
719 const ValueEnumerator &VE,
720 BitstreamWriter &Stream) {
721 const ValueEnumerator::ValueList &Vals = VE.getMDValues();
722 bool StartedMetadataBlock = false;
723 unsigned MDSAbbrev = 0;
724 SmallVector<uint64_t, 64> Record;
725 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
727 if (const MDNode *N = dyn_cast<MDNode>(Vals[i].first)) {
728 if (!N->isFunctionLocal() || !N->getFunction()) {
729 if (!StartedMetadataBlock) {
730 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
731 StartedMetadataBlock = true;
733 WriteMDNode(N, VE, Stream, Record);
735 } else if (const MDString *MDS = dyn_cast<MDString>(Vals[i].first)) {
736 if (!StartedMetadataBlock) {
737 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
739 // Abbrev for METADATA_STRING.
740 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
741 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_STRING));
742 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
743 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
744 MDSAbbrev = Stream.EmitAbbrev(Abbv);
745 StartedMetadataBlock = true;
748 // Code: [strchar x N]
749 Record.append(MDS->begin(), MDS->end());
751 // Emit the finished record.
752 Stream.EmitRecord(bitc::METADATA_STRING, Record, MDSAbbrev);
757 // Write named metadata.
758 for (Module::const_named_metadata_iterator I = M->named_metadata_begin(),
759 E = M->named_metadata_end(); I != E; ++I) {
760 const NamedMDNode *NMD = I;
761 if (!StartedMetadataBlock) {
762 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
763 StartedMetadataBlock = true;
767 StringRef Str = NMD->getName();
768 for (unsigned i = 0, e = Str.size(); i != e; ++i)
769 Record.push_back(Str[i]);
770 Stream.EmitRecord(bitc::METADATA_NAME, Record, 0/*TODO*/);
773 // Write named metadata operands.
774 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i)
775 Record.push_back(VE.getValueID(NMD->getOperand(i)));
776 Stream.EmitRecord(bitc::METADATA_NAMED_NODE, Record, 0);
780 if (StartedMetadataBlock)
784 static void WriteFunctionLocalMetadata(const Function &F,
785 const ValueEnumerator &VE,
786 BitstreamWriter &Stream) {
787 bool StartedMetadataBlock = false;
788 SmallVector<uint64_t, 64> Record;
789 const SmallVectorImpl<const MDNode *> &Vals = VE.getFunctionLocalMDValues();
790 for (unsigned i = 0, e = Vals.size(); i != e; ++i)
791 if (const MDNode *N = Vals[i])
792 if (N->isFunctionLocal() && N->getFunction() == &F) {
793 if (!StartedMetadataBlock) {
794 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
795 StartedMetadataBlock = true;
797 WriteMDNode(N, VE, Stream, Record);
800 if (StartedMetadataBlock)
804 static void WriteMetadataAttachment(const Function &F,
805 const ValueEnumerator &VE,
806 BitstreamWriter &Stream) {
807 Stream.EnterSubblock(bitc::METADATA_ATTACHMENT_ID, 3);
809 SmallVector<uint64_t, 64> Record;
811 // Write metadata attachments
812 // METADATA_ATTACHMENT - [m x [value, [n x [id, mdnode]]]
813 SmallVector<std::pair<unsigned, MDNode*>, 4> MDs;
815 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
816 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
819 I->getAllMetadataOtherThanDebugLoc(MDs);
821 // If no metadata, ignore instruction.
822 if (MDs.empty()) continue;
824 Record.push_back(VE.getInstructionID(I));
826 for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
827 Record.push_back(MDs[i].first);
828 Record.push_back(VE.getValueID(MDs[i].second));
830 Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
837 static void WriteModuleMetadataStore(const Module *M, BitstreamWriter &Stream) {
838 SmallVector<uint64_t, 64> Record;
840 // Write metadata kinds
841 // METADATA_KIND - [n x [id, name]]
842 SmallVector<StringRef, 8> Names;
843 M->getMDKindNames(Names);
845 if (Names.empty()) return;
847 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
849 for (unsigned MDKindID = 0, e = Names.size(); MDKindID != e; ++MDKindID) {
850 Record.push_back(MDKindID);
851 StringRef KName = Names[MDKindID];
852 Record.append(KName.begin(), KName.end());
854 Stream.EmitRecord(bitc::METADATA_KIND, Record, 0);
861 static void emitSignedInt64(SmallVectorImpl<uint64_t> &Vals, uint64_t V) {
863 Vals.push_back(V << 1);
865 Vals.push_back((-V << 1) | 1);
868 static void EmitAPInt(SmallVectorImpl<uint64_t> &Vals,
869 unsigned &Code, unsigned &AbbrevToUse, const APInt &Val,
870 bool EmitSizeForWideNumbers = false
872 if (Val.getBitWidth() <= 64) {
873 uint64_t V = Val.getSExtValue();
874 emitSignedInt64(Vals, V);
875 Code = bitc::CST_CODE_INTEGER;
876 AbbrevToUse = CONSTANTS_INTEGER_ABBREV;
878 // Wide integers, > 64 bits in size.
879 // We have an arbitrary precision integer value to write whose
880 // bit width is > 64. However, in canonical unsigned integer
881 // format it is likely that the high bits are going to be zero.
882 // So, we only write the number of active words.
883 unsigned NWords = Val.getActiveWords();
885 if (EmitSizeForWideNumbers)
886 Vals.push_back(NWords);
888 const uint64_t *RawWords = Val.getRawData();
889 for (unsigned i = 0; i != NWords; ++i) {
890 emitSignedInt64(Vals, RawWords[i]);
892 Code = bitc::CST_CODE_WIDE_INTEGER;
896 static void WriteConstants(unsigned FirstVal, unsigned LastVal,
897 const ValueEnumerator &VE,
898 BitstreamWriter &Stream, bool isGlobal) {
899 if (FirstVal == LastVal) return;
901 Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 4);
903 unsigned AggregateAbbrev = 0;
904 unsigned String8Abbrev = 0;
905 unsigned CString7Abbrev = 0;
906 unsigned CString6Abbrev = 0;
907 // If this is a constant pool for the module, emit module-specific abbrevs.
909 // Abbrev for CST_CODE_AGGREGATE.
910 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
911 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_AGGREGATE));
912 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
913 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal+1)));
914 AggregateAbbrev = Stream.EmitAbbrev(Abbv);
916 // Abbrev for CST_CODE_STRING.
917 Abbv = new BitCodeAbbrev();
918 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_STRING));
919 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
920 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
921 String8Abbrev = Stream.EmitAbbrev(Abbv);
922 // Abbrev for CST_CODE_CSTRING.
923 Abbv = new BitCodeAbbrev();
924 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
925 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
926 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
927 CString7Abbrev = Stream.EmitAbbrev(Abbv);
928 // Abbrev for CST_CODE_CSTRING.
929 Abbv = new BitCodeAbbrev();
930 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
931 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
932 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
933 CString6Abbrev = Stream.EmitAbbrev(Abbv);
936 SmallVector<uint64_t, 64> Record;
938 const ValueEnumerator::ValueList &Vals = VE.getValues();
940 for (unsigned i = FirstVal; i != LastVal; ++i) {
941 const Value *V = Vals[i].first;
942 // If we need to switch types, do so now.
943 if (V->getType() != LastTy) {
944 LastTy = V->getType();
945 Record.push_back(VE.getTypeID(LastTy));
946 Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record,
947 CONSTANTS_SETTYPE_ABBREV);
951 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
952 Record.push_back(unsigned(IA->hasSideEffects()) |
953 unsigned(IA->isAlignStack()) << 1 |
954 unsigned(IA->getDialect()&1) << 2);
956 // Add the asm string.
957 const std::string &AsmStr = IA->getAsmString();
958 Record.push_back(AsmStr.size());
959 for (unsigned i = 0, e = AsmStr.size(); i != e; ++i)
960 Record.push_back(AsmStr[i]);
962 // Add the constraint string.
963 const std::string &ConstraintStr = IA->getConstraintString();
964 Record.push_back(ConstraintStr.size());
965 for (unsigned i = 0, e = ConstraintStr.size(); i != e; ++i)
966 Record.push_back(ConstraintStr[i]);
967 Stream.EmitRecord(bitc::CST_CODE_INLINEASM, Record);
971 const Constant *C = cast<Constant>(V);
973 unsigned AbbrevToUse = 0;
974 if (C->isNullValue()) {
975 Code = bitc::CST_CODE_NULL;
976 } else if (isa<UndefValue>(C)) {
977 Code = bitc::CST_CODE_UNDEF;
978 } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {
979 EmitAPInt(Record, Code, AbbrevToUse, IV->getValue());
980 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
981 Code = bitc::CST_CODE_FLOAT;
982 Type *Ty = CFP->getType();
983 if (Ty->isHalfTy() || Ty->isFloatTy() || Ty->isDoubleTy()) {
984 Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
985 } else if (Ty->isX86_FP80Ty()) {
986 // api needed to prevent premature destruction
987 // bits are not in the same order as a normal i80 APInt, compensate.
988 APInt api = CFP->getValueAPF().bitcastToAPInt();
989 const uint64_t *p = api.getRawData();
990 Record.push_back((p[1] << 48) | (p[0] >> 16));
991 Record.push_back(p[0] & 0xffffLL);
992 } else if (Ty->isFP128Ty() || Ty->isPPC_FP128Ty()) {
993 APInt api = CFP->getValueAPF().bitcastToAPInt();
994 const uint64_t *p = api.getRawData();
995 Record.push_back(p[0]);
996 Record.push_back(p[1]);
998 assert (0 && "Unknown FP type!");
1000 } else if (isa<ConstantDataSequential>(C) &&
1001 cast<ConstantDataSequential>(C)->isString()) {
1002 const ConstantDataSequential *Str = cast<ConstantDataSequential>(C);
1003 // Emit constant strings specially.
1004 unsigned NumElts = Str->getNumElements();
1005 // If this is a null-terminated string, use the denser CSTRING encoding.
1006 if (Str->isCString()) {
1007 Code = bitc::CST_CODE_CSTRING;
1008 --NumElts; // Don't encode the null, which isn't allowed by char6.
1010 Code = bitc::CST_CODE_STRING;
1011 AbbrevToUse = String8Abbrev;
1013 bool isCStr7 = Code == bitc::CST_CODE_CSTRING;
1014 bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING;
1015 for (unsigned i = 0; i != NumElts; ++i) {
1016 unsigned char V = Str->getElementAsInteger(i);
1017 Record.push_back(V);
1018 isCStr7 &= (V & 128) == 0;
1020 isCStrChar6 = BitCodeAbbrevOp::isChar6(V);
1024 AbbrevToUse = CString6Abbrev;
1026 AbbrevToUse = CString7Abbrev;
1027 } else if (const ConstantDataSequential *CDS =
1028 dyn_cast<ConstantDataSequential>(C)) {
1029 Code = bitc::CST_CODE_DATA;
1030 Type *EltTy = CDS->getType()->getElementType();
1031 if (isa<IntegerType>(EltTy)) {
1032 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
1033 Record.push_back(CDS->getElementAsInteger(i));
1034 } else if (EltTy->isFloatTy()) {
1035 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1036 union { float F; uint32_t I; };
1037 F = CDS->getElementAsFloat(i);
1038 Record.push_back(I);
1041 assert(EltTy->isDoubleTy() && "Unknown ConstantData element type");
1042 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1043 union { double F; uint64_t I; };
1044 F = CDS->getElementAsDouble(i);
1045 Record.push_back(I);
1048 } else if (isa<ConstantArray>(C) || isa<ConstantStruct>(C) ||
1049 isa<ConstantVector>(C)) {
1050 Code = bitc::CST_CODE_AGGREGATE;
1051 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i)
1052 Record.push_back(VE.getValueID(C->getOperand(i)));
1053 AbbrevToUse = AggregateAbbrev;
1054 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1055 switch (CE->getOpcode()) {
1057 if (Instruction::isCast(CE->getOpcode())) {
1058 Code = bitc::CST_CODE_CE_CAST;
1059 Record.push_back(GetEncodedCastOpcode(CE->getOpcode()));
1060 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
1061 Record.push_back(VE.getValueID(C->getOperand(0)));
1062 AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;
1064 assert(CE->getNumOperands() == 2 && "Unknown constant expr!");
1065 Code = bitc::CST_CODE_CE_BINOP;
1066 Record.push_back(GetEncodedBinaryOpcode(CE->getOpcode()));
1067 Record.push_back(VE.getValueID(C->getOperand(0)));
1068 Record.push_back(VE.getValueID(C->getOperand(1)));
1069 uint64_t Flags = GetOptimizationFlags(CE);
1071 Record.push_back(Flags);
1074 case Instruction::GetElementPtr:
1075 Code = bitc::CST_CODE_CE_GEP;
1076 if (cast<GEPOperator>(C)->isInBounds())
1077 Code = bitc::CST_CODE_CE_INBOUNDS_GEP;
1078 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
1079 Record.push_back(VE.getTypeID(C->getOperand(i)->getType()));
1080 Record.push_back(VE.getValueID(C->getOperand(i)));
1083 case Instruction::Select:
1084 Code = bitc::CST_CODE_CE_SELECT;
1085 Record.push_back(VE.getValueID(C->getOperand(0)));
1086 Record.push_back(VE.getValueID(C->getOperand(1)));
1087 Record.push_back(VE.getValueID(C->getOperand(2)));
1089 case Instruction::ExtractElement:
1090 Code = bitc::CST_CODE_CE_EXTRACTELT;
1091 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
1092 Record.push_back(VE.getValueID(C->getOperand(0)));
1093 Record.push_back(VE.getValueID(C->getOperand(1)));
1095 case Instruction::InsertElement:
1096 Code = bitc::CST_CODE_CE_INSERTELT;
1097 Record.push_back(VE.getValueID(C->getOperand(0)));
1098 Record.push_back(VE.getValueID(C->getOperand(1)));
1099 Record.push_back(VE.getValueID(C->getOperand(2)));
1101 case Instruction::ShuffleVector:
1102 // If the return type and argument types are the same, this is a
1103 // standard shufflevector instruction. If the types are different,
1104 // then the shuffle is widening or truncating the input vectors, and
1105 // the argument type must also be encoded.
1106 if (C->getType() == C->getOperand(0)->getType()) {
1107 Code = bitc::CST_CODE_CE_SHUFFLEVEC;
1109 Code = bitc::CST_CODE_CE_SHUFVEC_EX;
1110 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
1112 Record.push_back(VE.getValueID(C->getOperand(0)));
1113 Record.push_back(VE.getValueID(C->getOperand(1)));
1114 Record.push_back(VE.getValueID(C->getOperand(2)));
1116 case Instruction::ICmp:
1117 case Instruction::FCmp:
1118 Code = bitc::CST_CODE_CE_CMP;
1119 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
1120 Record.push_back(VE.getValueID(C->getOperand(0)));
1121 Record.push_back(VE.getValueID(C->getOperand(1)));
1122 Record.push_back(CE->getPredicate());
1125 } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) {
1126 Code = bitc::CST_CODE_BLOCKADDRESS;
1127 Record.push_back(VE.getTypeID(BA->getFunction()->getType()));
1128 Record.push_back(VE.getValueID(BA->getFunction()));
1129 Record.push_back(VE.getGlobalBasicBlockID(BA->getBasicBlock()));
1134 llvm_unreachable("Unknown constant!");
1136 Stream.EmitRecord(Code, Record, AbbrevToUse);
1143 static void WriteModuleConstants(const ValueEnumerator &VE,
1144 BitstreamWriter &Stream) {
1145 const ValueEnumerator::ValueList &Vals = VE.getValues();
1147 // Find the first constant to emit, which is the first non-globalvalue value.
1148 // We know globalvalues have been emitted by WriteModuleInfo.
1149 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
1150 if (!isa<GlobalValue>(Vals[i].first)) {
1151 WriteConstants(i, Vals.size(), VE, Stream, true);
1157 /// PushValueAndType - The file has to encode both the value and type id for
1158 /// many values, because we need to know what type to create for forward
1159 /// references. However, most operands are not forward references, so this type
1160 /// field is not needed.
1162 /// This function adds V's value ID to Vals. If the value ID is higher than the
1163 /// instruction ID, then it is a forward reference, and it also includes the
1164 /// type ID. The value ID that is written is encoded relative to the InstID.
1165 static bool PushValueAndType(const Value *V, unsigned InstID,
1166 SmallVectorImpl<unsigned> &Vals,
1167 ValueEnumerator &VE) {
1168 unsigned ValID = VE.getValueID(V);
1169 // Make encoding relative to the InstID.
1170 Vals.push_back(InstID - ValID);
1171 if (ValID >= InstID) {
1172 Vals.push_back(VE.getTypeID(V->getType()));
1178 /// pushValue - Like PushValueAndType, but where the type of the value is
1179 /// omitted (perhaps it was already encoded in an earlier operand).
1180 static void pushValue(const Value *V, unsigned InstID,
1181 SmallVectorImpl<unsigned> &Vals,
1182 ValueEnumerator &VE) {
1183 unsigned ValID = VE.getValueID(V);
1184 Vals.push_back(InstID - ValID);
1187 static void pushValue64(const Value *V, unsigned InstID,
1188 SmallVectorImpl<uint64_t> &Vals,
1189 ValueEnumerator &VE) {
1190 uint64_t ValID = VE.getValueID(V);
1191 Vals.push_back(InstID - ValID);
1194 static void pushValueSigned(const Value *V, unsigned InstID,
1195 SmallVectorImpl<uint64_t> &Vals,
1196 ValueEnumerator &VE) {
1197 unsigned ValID = VE.getValueID(V);
1198 int64_t diff = ((int32_t)InstID - (int32_t)ValID);
1199 emitSignedInt64(Vals, diff);
1202 /// WriteInstruction - Emit an instruction to the specified stream.
1203 static void WriteInstruction(const Instruction &I, unsigned InstID,
1204 ValueEnumerator &VE, BitstreamWriter &Stream,
1205 SmallVectorImpl<unsigned> &Vals) {
1207 unsigned AbbrevToUse = 0;
1208 VE.setInstructionID(&I);
1209 switch (I.getOpcode()) {
1211 if (Instruction::isCast(I.getOpcode())) {
1212 Code = bitc::FUNC_CODE_INST_CAST;
1213 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
1214 AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
1215 Vals.push_back(VE.getTypeID(I.getType()));
1216 Vals.push_back(GetEncodedCastOpcode(I.getOpcode()));
1218 assert(isa<BinaryOperator>(I) && "Unknown instruction!");
1219 Code = bitc::FUNC_CODE_INST_BINOP;
1220 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
1221 AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
1222 pushValue(I.getOperand(1), InstID, Vals, VE);
1223 Vals.push_back(GetEncodedBinaryOpcode(I.getOpcode()));
1224 uint64_t Flags = GetOptimizationFlags(&I);
1226 if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV)
1227 AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV;
1228 Vals.push_back(Flags);
1233 case Instruction::GetElementPtr:
1234 Code = bitc::FUNC_CODE_INST_GEP;
1235 if (cast<GEPOperator>(&I)->isInBounds())
1236 Code = bitc::FUNC_CODE_INST_INBOUNDS_GEP;
1237 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
1238 PushValueAndType(I.getOperand(i), InstID, Vals, VE);
1240 case Instruction::ExtractValue: {
1241 Code = bitc::FUNC_CODE_INST_EXTRACTVAL;
1242 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1243 const ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
1244 for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
1248 case Instruction::InsertValue: {
1249 Code = bitc::FUNC_CODE_INST_INSERTVAL;
1250 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1251 PushValueAndType(I.getOperand(1), InstID, Vals, VE);
1252 const InsertValueInst *IVI = cast<InsertValueInst>(&I);
1253 for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
1257 case Instruction::Select:
1258 Code = bitc::FUNC_CODE_INST_VSELECT;
1259 PushValueAndType(I.getOperand(1), InstID, Vals, VE);
1260 pushValue(I.getOperand(2), InstID, Vals, VE);
1261 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1263 case Instruction::ExtractElement:
1264 Code = bitc::FUNC_CODE_INST_EXTRACTELT;
1265 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1266 pushValue(I.getOperand(1), InstID, Vals, VE);
1268 case Instruction::InsertElement:
1269 Code = bitc::FUNC_CODE_INST_INSERTELT;
1270 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1271 pushValue(I.getOperand(1), InstID, Vals, VE);
1272 pushValue(I.getOperand(2), InstID, Vals, VE);
1274 case Instruction::ShuffleVector:
1275 Code = bitc::FUNC_CODE_INST_SHUFFLEVEC;
1276 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1277 pushValue(I.getOperand(1), InstID, Vals, VE);
1278 pushValue(I.getOperand(2), InstID, Vals, VE);
1280 case Instruction::ICmp:
1281 case Instruction::FCmp:
1282 // compare returning Int1Ty or vector of Int1Ty
1283 Code = bitc::FUNC_CODE_INST_CMP2;
1284 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1285 pushValue(I.getOperand(1), InstID, Vals, VE);
1286 Vals.push_back(cast<CmpInst>(I).getPredicate());
1289 case Instruction::Ret:
1291 Code = bitc::FUNC_CODE_INST_RET;
1292 unsigned NumOperands = I.getNumOperands();
1293 if (NumOperands == 0)
1294 AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
1295 else if (NumOperands == 1) {
1296 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
1297 AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
1299 for (unsigned i = 0, e = NumOperands; i != e; ++i)
1300 PushValueAndType(I.getOperand(i), InstID, Vals, VE);
1304 case Instruction::Br:
1306 Code = bitc::FUNC_CODE_INST_BR;
1307 const BranchInst &II = cast<BranchInst>(I);
1308 Vals.push_back(VE.getValueID(II.getSuccessor(0)));
1309 if (II.isConditional()) {
1310 Vals.push_back(VE.getValueID(II.getSuccessor(1)));
1311 pushValue(II.getCondition(), InstID, Vals, VE);
1315 case Instruction::Switch:
1317 // Redefine Vals, since here we need to use 64 bit values
1318 // explicitly to store large APInt numbers.
1319 SmallVector<uint64_t, 128> Vals64;
1321 Code = bitc::FUNC_CODE_INST_SWITCH;
1322 const SwitchInst &SI = cast<SwitchInst>(I);
1324 uint32_t SwitchRecordHeader = SI.hash() | (SWITCH_INST_MAGIC << 16);
1325 Vals64.push_back(SwitchRecordHeader);
1327 Vals64.push_back(VE.getTypeID(SI.getCondition()->getType()));
1328 pushValue64(SI.getCondition(), InstID, Vals64, VE);
1329 Vals64.push_back(VE.getValueID(SI.getDefaultDest()));
1330 Vals64.push_back(SI.getNumCases());
1331 for (SwitchInst::ConstCaseIt i = SI.case_begin(), e = SI.case_end();
1333 const IntegersSubset& CaseRanges = i.getCaseValueEx();
1334 unsigned Code, Abbrev; // will unused.
1336 if (CaseRanges.isSingleNumber()) {
1337 Vals64.push_back(1/*NumItems = 1*/);
1338 Vals64.push_back(true/*IsSingleNumber = true*/);
1339 EmitAPInt(Vals64, Code, Abbrev, CaseRanges.getSingleNumber(0), true);
1342 Vals64.push_back(CaseRanges.getNumItems());
1344 if (CaseRanges.isSingleNumbersOnly()) {
1345 for (unsigned ri = 0, rn = CaseRanges.getNumItems();
1348 Vals64.push_back(true/*IsSingleNumber = true*/);
1350 EmitAPInt(Vals64, Code, Abbrev,
1351 CaseRanges.getSingleNumber(ri), true);
1354 for (unsigned ri = 0, rn = CaseRanges.getNumItems();
1356 IntegersSubset::Range r = CaseRanges.getItem(ri);
1357 bool IsSingleNumber = CaseRanges.isSingleNumber(ri);
1359 Vals64.push_back(IsSingleNumber);
1361 EmitAPInt(Vals64, Code, Abbrev, r.getLow(), true);
1362 if (!IsSingleNumber)
1363 EmitAPInt(Vals64, Code, Abbrev, r.getHigh(), true);
1366 Vals64.push_back(VE.getValueID(i.getCaseSuccessor()));
1369 Stream.EmitRecord(Code, Vals64, AbbrevToUse);
1371 // Also do expected action - clear external Vals collection:
1376 case Instruction::IndirectBr:
1377 Code = bitc::FUNC_CODE_INST_INDIRECTBR;
1378 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
1379 // Encode the address operand as relative, but not the basic blocks.
1380 pushValue(I.getOperand(0), InstID, Vals, VE);
1381 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i)
1382 Vals.push_back(VE.getValueID(I.getOperand(i)));
1385 case Instruction::Invoke: {
1386 const InvokeInst *II = cast<InvokeInst>(&I);
1387 const Value *Callee(II->getCalledValue());
1388 PointerType *PTy = cast<PointerType>(Callee->getType());
1389 FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1390 Code = bitc::FUNC_CODE_INST_INVOKE;
1392 Vals.push_back(VE.getAttributeID(II->getAttributes()));
1393 Vals.push_back(II->getCallingConv());
1394 Vals.push_back(VE.getValueID(II->getNormalDest()));
1395 Vals.push_back(VE.getValueID(II->getUnwindDest()));
1396 PushValueAndType(Callee, InstID, Vals, VE);
1398 // Emit value #'s for the fixed parameters.
1399 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
1400 pushValue(I.getOperand(i), InstID, Vals, VE); // fixed param.
1402 // Emit type/value pairs for varargs params.
1403 if (FTy->isVarArg()) {
1404 for (unsigned i = FTy->getNumParams(), e = I.getNumOperands()-3;
1406 PushValueAndType(I.getOperand(i), InstID, Vals, VE); // vararg
1410 case Instruction::Resume:
1411 Code = bitc::FUNC_CODE_INST_RESUME;
1412 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1414 case Instruction::Unreachable:
1415 Code = bitc::FUNC_CODE_INST_UNREACHABLE;
1416 AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
1419 case Instruction::PHI: {
1420 const PHINode &PN = cast<PHINode>(I);
1421 Code = bitc::FUNC_CODE_INST_PHI;
1422 // With the newer instruction encoding, forward references could give
1423 // negative valued IDs. This is most common for PHIs, so we use
1425 SmallVector<uint64_t, 128> Vals64;
1426 Vals64.push_back(VE.getTypeID(PN.getType()));
1427 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
1428 pushValueSigned(PN.getIncomingValue(i), InstID, Vals64, VE);
1429 Vals64.push_back(VE.getValueID(PN.getIncomingBlock(i)));
1431 // Emit a Vals64 vector and exit.
1432 Stream.EmitRecord(Code, Vals64, AbbrevToUse);
1437 case Instruction::LandingPad: {
1438 const LandingPadInst &LP = cast<LandingPadInst>(I);
1439 Code = bitc::FUNC_CODE_INST_LANDINGPAD;
1440 Vals.push_back(VE.getTypeID(LP.getType()));
1441 PushValueAndType(LP.getPersonalityFn(), InstID, Vals, VE);
1442 Vals.push_back(LP.isCleanup());
1443 Vals.push_back(LP.getNumClauses());
1444 for (unsigned I = 0, E = LP.getNumClauses(); I != E; ++I) {
1446 Vals.push_back(LandingPadInst::Catch);
1448 Vals.push_back(LandingPadInst::Filter);
1449 PushValueAndType(LP.getClause(I), InstID, Vals, VE);
1454 case Instruction::Alloca:
1455 Code = bitc::FUNC_CODE_INST_ALLOCA;
1456 Vals.push_back(VE.getTypeID(I.getType()));
1457 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
1458 Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
1459 Vals.push_back(Log2_32(cast<AllocaInst>(I).getAlignment())+1);
1462 case Instruction::Load:
1463 if (cast<LoadInst>(I).isAtomic()) {
1464 Code = bitc::FUNC_CODE_INST_LOADATOMIC;
1465 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1467 Code = bitc::FUNC_CODE_INST_LOAD;
1468 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE)) // ptr
1469 AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
1471 Vals.push_back(Log2_32(cast<LoadInst>(I).getAlignment())+1);
1472 Vals.push_back(cast<LoadInst>(I).isVolatile());
1473 if (cast<LoadInst>(I).isAtomic()) {
1474 Vals.push_back(GetEncodedOrdering(cast<LoadInst>(I).getOrdering()));
1475 Vals.push_back(GetEncodedSynchScope(cast<LoadInst>(I).getSynchScope()));
1478 case Instruction::Store:
1479 if (cast<StoreInst>(I).isAtomic())
1480 Code = bitc::FUNC_CODE_INST_STOREATOMIC;
1482 Code = bitc::FUNC_CODE_INST_STORE;
1483 PushValueAndType(I.getOperand(1), InstID, Vals, VE); // ptrty + ptr
1484 pushValue(I.getOperand(0), InstID, Vals, VE); // val.
1485 Vals.push_back(Log2_32(cast<StoreInst>(I).getAlignment())+1);
1486 Vals.push_back(cast<StoreInst>(I).isVolatile());
1487 if (cast<StoreInst>(I).isAtomic()) {
1488 Vals.push_back(GetEncodedOrdering(cast<StoreInst>(I).getOrdering()));
1489 Vals.push_back(GetEncodedSynchScope(cast<StoreInst>(I).getSynchScope()));
1492 case Instruction::AtomicCmpXchg:
1493 Code = bitc::FUNC_CODE_INST_CMPXCHG;
1494 PushValueAndType(I.getOperand(0), InstID, Vals, VE); // ptrty + ptr
1495 pushValue(I.getOperand(1), InstID, Vals, VE); // cmp.
1496 pushValue(I.getOperand(2), InstID, Vals, VE); // newval.
1497 Vals.push_back(cast<AtomicCmpXchgInst>(I).isVolatile());
1498 Vals.push_back(GetEncodedOrdering(
1499 cast<AtomicCmpXchgInst>(I).getOrdering()));
1500 Vals.push_back(GetEncodedSynchScope(
1501 cast<AtomicCmpXchgInst>(I).getSynchScope()));
1503 case Instruction::AtomicRMW:
1504 Code = bitc::FUNC_CODE_INST_ATOMICRMW;
1505 PushValueAndType(I.getOperand(0), InstID, Vals, VE); // ptrty + ptr
1506 pushValue(I.getOperand(1), InstID, Vals, VE); // val.
1507 Vals.push_back(GetEncodedRMWOperation(
1508 cast<AtomicRMWInst>(I).getOperation()));
1509 Vals.push_back(cast<AtomicRMWInst>(I).isVolatile());
1510 Vals.push_back(GetEncodedOrdering(cast<AtomicRMWInst>(I).getOrdering()));
1511 Vals.push_back(GetEncodedSynchScope(
1512 cast<AtomicRMWInst>(I).getSynchScope()));
1514 case Instruction::Fence:
1515 Code = bitc::FUNC_CODE_INST_FENCE;
1516 Vals.push_back(GetEncodedOrdering(cast<FenceInst>(I).getOrdering()));
1517 Vals.push_back(GetEncodedSynchScope(cast<FenceInst>(I).getSynchScope()));
1519 case Instruction::Call: {
1520 const CallInst &CI = cast<CallInst>(I);
1521 PointerType *PTy = cast<PointerType>(CI.getCalledValue()->getType());
1522 FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1524 Code = bitc::FUNC_CODE_INST_CALL;
1526 Vals.push_back(VE.getAttributeID(CI.getAttributes()));
1527 Vals.push_back((CI.getCallingConv() << 1) | unsigned(CI.isTailCall()));
1528 PushValueAndType(CI.getCalledValue(), InstID, Vals, VE); // Callee
1530 // Emit value #'s for the fixed parameters.
1531 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
1532 // Check for labels (can happen with asm labels).
1533 if (FTy->getParamType(i)->isLabelTy())
1534 Vals.push_back(VE.getValueID(CI.getArgOperand(i)));
1536 pushValue(CI.getArgOperand(i), InstID, Vals, VE); // fixed param.
1539 // Emit type/value pairs for varargs params.
1540 if (FTy->isVarArg()) {
1541 for (unsigned i = FTy->getNumParams(), e = CI.getNumArgOperands();
1543 PushValueAndType(CI.getArgOperand(i), InstID, Vals, VE); // varargs
1547 case Instruction::VAArg:
1548 Code = bitc::FUNC_CODE_INST_VAARG;
1549 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); // valistty
1550 pushValue(I.getOperand(0), InstID, Vals, VE); // valist.
1551 Vals.push_back(VE.getTypeID(I.getType())); // restype.
1555 Stream.EmitRecord(Code, Vals, AbbrevToUse);
1559 // Emit names for globals/functions etc.
1560 static void WriteValueSymbolTable(const ValueSymbolTable &VST,
1561 const ValueEnumerator &VE,
1562 BitstreamWriter &Stream) {
1563 if (VST.empty()) return;
1564 Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
1566 // FIXME: Set up the abbrev, we know how many values there are!
1567 // FIXME: We know if the type names can use 7-bit ascii.
1568 SmallVector<unsigned, 64> NameVals;
1570 for (ValueSymbolTable::const_iterator SI = VST.begin(), SE = VST.end();
1573 const ValueName &Name = *SI;
1575 // Figure out the encoding to use for the name.
1577 bool isChar6 = true;
1578 for (const char *C = Name.getKeyData(), *E = C+Name.getKeyLength();
1581 isChar6 = BitCodeAbbrevOp::isChar6(*C);
1582 if ((unsigned char)*C & 128) {
1584 break; // don't bother scanning the rest.
1588 unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
1590 // VST_ENTRY: [valueid, namechar x N]
1591 // VST_BBENTRY: [bbid, namechar x N]
1593 if (isa<BasicBlock>(SI->getValue())) {
1594 Code = bitc::VST_CODE_BBENTRY;
1596 AbbrevToUse = VST_BBENTRY_6_ABBREV;
1598 Code = bitc::VST_CODE_ENTRY;
1600 AbbrevToUse = VST_ENTRY_6_ABBREV;
1602 AbbrevToUse = VST_ENTRY_7_ABBREV;
1605 NameVals.push_back(VE.getValueID(SI->getValue()));
1606 for (const char *P = Name.getKeyData(),
1607 *E = Name.getKeyData()+Name.getKeyLength(); P != E; ++P)
1608 NameVals.push_back((unsigned char)*P);
1610 // Emit the finished record.
1611 Stream.EmitRecord(Code, NameVals, AbbrevToUse);
1617 /// WriteFunction - Emit a function body to the module stream.
1618 static void WriteFunction(const Function &F, ValueEnumerator &VE,
1619 BitstreamWriter &Stream) {
1620 Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 4);
1621 VE.incorporateFunction(F);
1623 SmallVector<unsigned, 64> Vals;
1625 // Emit the number of basic blocks, so the reader can create them ahead of
1627 Vals.push_back(VE.getBasicBlocks().size());
1628 Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals);
1631 // If there are function-local constants, emit them now.
1632 unsigned CstStart, CstEnd;
1633 VE.getFunctionConstantRange(CstStart, CstEnd);
1634 WriteConstants(CstStart, CstEnd, VE, Stream, false);
1636 // If there is function-local metadata, emit it now.
1637 WriteFunctionLocalMetadata(F, VE, Stream);
1639 // Keep a running idea of what the instruction ID is.
1640 unsigned InstID = CstEnd;
1642 bool NeedsMetadataAttachment = false;
1646 // Finally, emit all the instructions, in order.
1647 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1648 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
1650 WriteInstruction(*I, InstID, VE, Stream, Vals);
1652 if (!I->getType()->isVoidTy())
1655 // If the instruction has metadata, write a metadata attachment later.
1656 NeedsMetadataAttachment |= I->hasMetadataOtherThanDebugLoc();
1658 // If the instruction has a debug location, emit it.
1659 DebugLoc DL = I->getDebugLoc();
1660 if (DL.isUnknown()) {
1662 } else if (DL == LastDL) {
1663 // Just repeat the same debug loc as last time.
1664 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC_AGAIN, Vals);
1667 DL.getScopeAndInlinedAt(Scope, IA, I->getContext());
1669 Vals.push_back(DL.getLine());
1670 Vals.push_back(DL.getCol());
1671 Vals.push_back(Scope ? VE.getValueID(Scope)+1 : 0);
1672 Vals.push_back(IA ? VE.getValueID(IA)+1 : 0);
1673 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC, Vals);
1680 // Emit names for all the instructions etc.
1681 WriteValueSymbolTable(F.getValueSymbolTable(), VE, Stream);
1683 if (NeedsMetadataAttachment)
1684 WriteMetadataAttachment(F, VE, Stream);
1689 // Emit blockinfo, which defines the standard abbreviations etc.
1690 static void WriteBlockInfo(const ValueEnumerator &VE, BitstreamWriter &Stream) {
1691 // We only want to emit block info records for blocks that have multiple
1692 // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK.
1693 // Other blocks can define their abbrevs inline.
1694 Stream.EnterBlockInfoBlock(2);
1696 { // 8-bit fixed-width VST_ENTRY/VST_BBENTRY strings.
1697 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1698 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3));
1699 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1700 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1701 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
1702 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1703 Abbv) != VST_ENTRY_8_ABBREV)
1704 llvm_unreachable("Unexpected abbrev ordering!");
1707 { // 7-bit fixed width VST_ENTRY strings.
1708 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1709 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
1710 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1711 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1712 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
1713 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1714 Abbv) != VST_ENTRY_7_ABBREV)
1715 llvm_unreachable("Unexpected abbrev ordering!");
1717 { // 6-bit char6 VST_ENTRY strings.
1718 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1719 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
1720 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1721 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1722 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
1723 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1724 Abbv) != VST_ENTRY_6_ABBREV)
1725 llvm_unreachable("Unexpected abbrev ordering!");
1727 { // 6-bit char6 VST_BBENTRY strings.
1728 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1729 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY));
1730 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1731 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1732 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
1733 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1734 Abbv) != VST_BBENTRY_6_ABBREV)
1735 llvm_unreachable("Unexpected abbrev ordering!");
1740 { // SETTYPE abbrev for CONSTANTS_BLOCK.
1741 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1742 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_SETTYPE));
1743 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
1744 Log2_32_Ceil(VE.getTypes().size()+1)));
1745 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1746 Abbv) != CONSTANTS_SETTYPE_ABBREV)
1747 llvm_unreachable("Unexpected abbrev ordering!");
1750 { // INTEGER abbrev for CONSTANTS_BLOCK.
1751 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1752 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_INTEGER));
1753 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1754 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1755 Abbv) != CONSTANTS_INTEGER_ABBREV)
1756 llvm_unreachable("Unexpected abbrev ordering!");
1759 { // CE_CAST abbrev for CONSTANTS_BLOCK.
1760 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1761 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CE_CAST));
1762 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // cast opc
1763 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // typeid
1764 Log2_32_Ceil(VE.getTypes().size()+1)));
1765 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
1767 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1768 Abbv) != CONSTANTS_CE_CAST_Abbrev)
1769 llvm_unreachable("Unexpected abbrev ordering!");
1771 { // NULL abbrev for CONSTANTS_BLOCK.
1772 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1773 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_NULL));
1774 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1775 Abbv) != CONSTANTS_NULL_Abbrev)
1776 llvm_unreachable("Unexpected abbrev ordering!");
1779 // FIXME: This should only use space for first class types!
1781 { // INST_LOAD abbrev for FUNCTION_BLOCK.
1782 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1783 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_LOAD));
1784 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Ptr
1785 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align
1786 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile
1787 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1788 Abbv) != FUNCTION_INST_LOAD_ABBREV)
1789 llvm_unreachable("Unexpected abbrev ordering!");
1791 { // INST_BINOP abbrev for FUNCTION_BLOCK.
1792 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1793 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
1794 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
1795 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
1796 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
1797 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1798 Abbv) != FUNCTION_INST_BINOP_ABBREV)
1799 llvm_unreachable("Unexpected abbrev ordering!");
1801 { // INST_BINOP_FLAGS abbrev for FUNCTION_BLOCK.
1802 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1803 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
1804 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
1805 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
1806 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
1807 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7)); // flags
1808 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1809 Abbv) != FUNCTION_INST_BINOP_FLAGS_ABBREV)
1810 llvm_unreachable("Unexpected abbrev ordering!");
1812 { // INST_CAST abbrev for FUNCTION_BLOCK.
1813 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1814 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST));
1815 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // OpVal
1816 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
1817 Log2_32_Ceil(VE.getTypes().size()+1)));
1818 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
1819 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1820 Abbv) != FUNCTION_INST_CAST_ABBREV)
1821 llvm_unreachable("Unexpected abbrev ordering!");
1824 { // INST_RET abbrev for FUNCTION_BLOCK.
1825 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1826 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
1827 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1828 Abbv) != FUNCTION_INST_RET_VOID_ABBREV)
1829 llvm_unreachable("Unexpected abbrev ordering!");
1831 { // INST_RET abbrev for FUNCTION_BLOCK.
1832 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1833 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
1834 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ValID
1835 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1836 Abbv) != FUNCTION_INST_RET_VAL_ABBREV)
1837 llvm_unreachable("Unexpected abbrev ordering!");
1839 { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK.
1840 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1841 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNREACHABLE));
1842 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1843 Abbv) != FUNCTION_INST_UNREACHABLE_ABBREV)
1844 llvm_unreachable("Unexpected abbrev ordering!");
1850 // Sort the Users based on the order in which the reader parses the bitcode
1852 static bool bitcodereader_order(const User *lhs, const User *rhs) {
1857 static void WriteUseList(const Value *V, const ValueEnumerator &VE,
1858 BitstreamWriter &Stream) {
1860 // One or zero uses can't get out of order.
1861 if (V->use_empty() || V->hasNUses(1))
1864 // Make a copy of the in-memory use-list for sorting.
1865 unsigned UseListSize = std::distance(V->use_begin(), V->use_end());
1866 SmallVector<const User*, 8> UseList;
1867 UseList.reserve(UseListSize);
1868 for (Value::const_use_iterator I = V->use_begin(), E = V->use_end();
1871 UseList.push_back(U);
1874 // Sort the copy based on the order read by the BitcodeReader.
1875 std::sort(UseList.begin(), UseList.end(), bitcodereader_order);
1877 // TODO: Generate a diff between the BitcodeWriter in-memory use-list and the
1878 // sorted list (i.e., the expected BitcodeReader in-memory use-list).
1880 // TODO: Emit the USELIST_CODE_ENTRYs.
1883 static void WriteFunctionUseList(const Function *F, ValueEnumerator &VE,
1884 BitstreamWriter &Stream) {
1885 VE.incorporateFunction(*F);
1887 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1889 WriteUseList(AI, VE, Stream);
1890 for (Function::const_iterator BB = F->begin(), FE = F->end(); BB != FE;
1892 WriteUseList(BB, VE, Stream);
1893 for (BasicBlock::const_iterator II = BB->begin(), IE = BB->end(); II != IE;
1895 WriteUseList(II, VE, Stream);
1896 for (User::const_op_iterator OI = II->op_begin(), E = II->op_end();
1898 if ((isa<Constant>(*OI) && !isa<GlobalValue>(*OI)) ||
1899 isa<InlineAsm>(*OI))
1900 WriteUseList(*OI, VE, Stream);
1908 static void WriteModuleUseLists(const Module *M, ValueEnumerator &VE,
1909 BitstreamWriter &Stream) {
1910 Stream.EnterSubblock(bitc::USELIST_BLOCK_ID, 3);
1912 // XXX: this modifies the module, but in a way that should never change the
1913 // behavior of any pass or codegen in LLVM. The problem is that GVs may
1914 // contain entries in the use_list that do not exist in the Module and are
1915 // not stored in the .bc file.
1916 for (Module::const_global_iterator I = M->global_begin(), E = M->global_end();
1918 I->removeDeadConstantUsers();
1920 // Write the global variables.
1921 for (Module::const_global_iterator GI = M->global_begin(),
1922 GE = M->global_end(); GI != GE; ++GI) {
1923 WriteUseList(GI, VE, Stream);
1925 // Write the global variable initializers.
1926 if (GI->hasInitializer())
1927 WriteUseList(GI->getInitializer(), VE, Stream);
1930 // Write the functions.
1931 for (Module::const_iterator FI = M->begin(), FE = M->end(); FI != FE; ++FI) {
1932 WriteUseList(FI, VE, Stream);
1933 if (!FI->isDeclaration())
1934 WriteFunctionUseList(FI, VE, Stream);
1937 // Write the aliases.
1938 for (Module::const_alias_iterator AI = M->alias_begin(), AE = M->alias_end();
1940 WriteUseList(AI, VE, Stream);
1941 WriteUseList(AI->getAliasee(), VE, Stream);
1947 /// WriteModule - Emit the specified module to the bitstream.
1948 static void WriteModule(const Module *M, BitstreamWriter &Stream) {
1949 Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
1951 SmallVector<unsigned, 1> Vals;
1952 unsigned CurVersion = 1;
1953 Vals.push_back(CurVersion);
1954 Stream.EmitRecord(bitc::MODULE_CODE_VERSION, Vals);
1956 // Analyze the module, enumerating globals, functions, etc.
1957 ValueEnumerator VE(M);
1959 // Emit blockinfo, which defines the standard abbreviations etc.
1960 WriteBlockInfo(VE, Stream);
1962 // Emit information about attribute groups.
1963 WriteAttributeGroupTable(VE, Stream);
1965 // Emit information about parameter attributes.
1966 WriteAttributeTable(VE, Stream);
1968 // Emit information describing all of the types in the module.
1969 WriteTypeTable(VE, Stream);
1971 // Emit top-level description of module, including target triple, inline asm,
1972 // descriptors for global variables, and function prototype info.
1973 WriteModuleInfo(M, VE, Stream);
1976 WriteModuleConstants(VE, Stream);
1979 WriteModuleMetadata(M, VE, Stream);
1982 WriteModuleMetadataStore(M, Stream);
1984 // Emit names for globals/functions etc.
1985 WriteValueSymbolTable(M->getValueSymbolTable(), VE, Stream);
1988 if (EnablePreserveUseListOrdering)
1989 WriteModuleUseLists(M, VE, Stream);
1991 // Emit function bodies.
1992 for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F)
1993 if (!F->isDeclaration())
1994 WriteFunction(*F, VE, Stream);
1999 /// EmitDarwinBCHeader - If generating a bc file on darwin, we have to emit a
2000 /// header and trailer to make it compatible with the system archiver. To do
2001 /// this we emit the following header, and then emit a trailer that pads the
2002 /// file out to be a multiple of 16 bytes.
2004 /// struct bc_header {
2005 /// uint32_t Magic; // 0x0B17C0DE
2006 /// uint32_t Version; // Version, currently always 0.
2007 /// uint32_t BitcodeOffset; // Offset to traditional bitcode file.
2008 /// uint32_t BitcodeSize; // Size of traditional bitcode file.
2009 /// uint32_t CPUType; // CPU specifier.
2010 /// ... potentially more later ...
2013 DarwinBCSizeFieldOffset = 3*4, // Offset to bitcode_size.
2014 DarwinBCHeaderSize = 5*4
2017 static void WriteInt32ToBuffer(uint32_t Value, SmallVectorImpl<char> &Buffer,
2018 uint32_t &Position) {
2019 Buffer[Position + 0] = (unsigned char) (Value >> 0);
2020 Buffer[Position + 1] = (unsigned char) (Value >> 8);
2021 Buffer[Position + 2] = (unsigned char) (Value >> 16);
2022 Buffer[Position + 3] = (unsigned char) (Value >> 24);
2026 static void EmitDarwinBCHeaderAndTrailer(SmallVectorImpl<char> &Buffer,
2028 unsigned CPUType = ~0U;
2030 // Match x86_64-*, i[3-9]86-*, powerpc-*, powerpc64-*, arm-*, thumb-*,
2031 // armv[0-9]-*, thumbv[0-9]-*, armv5te-*, or armv6t2-*. The CPUType is a magic
2032 // number from /usr/include/mach/machine.h. It is ok to reproduce the
2033 // specific constants here because they are implicitly part of the Darwin ABI.
2035 DARWIN_CPU_ARCH_ABI64 = 0x01000000,
2036 DARWIN_CPU_TYPE_X86 = 7,
2037 DARWIN_CPU_TYPE_ARM = 12,
2038 DARWIN_CPU_TYPE_POWERPC = 18
2041 Triple::ArchType Arch = TT.getArch();
2042 if (Arch == Triple::x86_64)
2043 CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64;
2044 else if (Arch == Triple::x86)
2045 CPUType = DARWIN_CPU_TYPE_X86;
2046 else if (Arch == Triple::ppc)
2047 CPUType = DARWIN_CPU_TYPE_POWERPC;
2048 else if (Arch == Triple::ppc64)
2049 CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64;
2050 else if (Arch == Triple::arm || Arch == Triple::thumb)
2051 CPUType = DARWIN_CPU_TYPE_ARM;
2053 // Traditional Bitcode starts after header.
2054 assert(Buffer.size() >= DarwinBCHeaderSize &&
2055 "Expected header size to be reserved");
2056 unsigned BCOffset = DarwinBCHeaderSize;
2057 unsigned BCSize = Buffer.size()-DarwinBCHeaderSize;
2059 // Write the magic and version.
2060 unsigned Position = 0;
2061 WriteInt32ToBuffer(0x0B17C0DE , Buffer, Position);
2062 WriteInt32ToBuffer(0 , Buffer, Position); // Version.
2063 WriteInt32ToBuffer(BCOffset , Buffer, Position);
2064 WriteInt32ToBuffer(BCSize , Buffer, Position);
2065 WriteInt32ToBuffer(CPUType , Buffer, Position);
2067 // If the file is not a multiple of 16 bytes, insert dummy padding.
2068 while (Buffer.size() & 15)
2069 Buffer.push_back(0);
2072 /// WriteBitcodeToFile - Write the specified module to the specified output
2074 void llvm::WriteBitcodeToFile(const Module *M, raw_ostream &Out) {
2075 SmallVector<char, 0> Buffer;
2076 Buffer.reserve(256*1024);
2078 // If this is darwin or another generic macho target, reserve space for the
2080 Triple TT(M->getTargetTriple());
2081 if (TT.isOSDarwin())
2082 Buffer.insert(Buffer.begin(), DarwinBCHeaderSize, 0);
2084 // Emit the module into the buffer.
2086 BitstreamWriter Stream(Buffer);
2088 // Emit the file header.
2089 Stream.Emit((unsigned)'B', 8);
2090 Stream.Emit((unsigned)'C', 8);
2091 Stream.Emit(0x0, 4);
2092 Stream.Emit(0xC, 4);
2093 Stream.Emit(0xE, 4);
2094 Stream.Emit(0xD, 4);
2097 WriteModule(M, Stream);
2100 if (TT.isOSDarwin())
2101 EmitDarwinBCHeaderAndTrailer(Buffer, TT);
2103 // Write the generated bitstream to "Out".
2104 Out.write((char*)&Buffer.front(), Buffer.size());