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/DebugInfoMetadata.h"
21 #include "llvm/IR/DerivedTypes.h"
22 #include "llvm/IR/InlineAsm.h"
23 #include "llvm/IR/Instructions.h"
24 #include "llvm/IR/Module.h"
25 #include "llvm/IR/Operator.h"
26 #include "llvm/IR/UseListOrder.h"
27 #include "llvm/IR/ValueSymbolTable.h"
28 #include "llvm/Support/CommandLine.h"
29 #include "llvm/Support/ErrorHandling.h"
30 #include "llvm/Support/MathExtras.h"
31 #include "llvm/Support/Program.h"
32 #include "llvm/Support/raw_ostream.h"
37 /// These are manifest constants used by the bitcode writer. They do not need to
38 /// be kept in sync with the reader, but need to be consistent within this file.
40 // VALUE_SYMTAB_BLOCK abbrev id's.
41 VST_ENTRY_8_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
46 // CONSTANTS_BLOCK abbrev id's.
47 CONSTANTS_SETTYPE_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
48 CONSTANTS_INTEGER_ABBREV,
49 CONSTANTS_CE_CAST_Abbrev,
50 CONSTANTS_NULL_Abbrev,
52 // FUNCTION_BLOCK abbrev id's.
53 FUNCTION_INST_LOAD_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
54 FUNCTION_INST_BINOP_ABBREV,
55 FUNCTION_INST_BINOP_FLAGS_ABBREV,
56 FUNCTION_INST_CAST_ABBREV,
57 FUNCTION_INST_RET_VOID_ABBREV,
58 FUNCTION_INST_RET_VAL_ABBREV,
59 FUNCTION_INST_UNREACHABLE_ABBREV,
60 FUNCTION_INST_GEP_ABBREV,
63 static unsigned GetEncodedCastOpcode(unsigned Opcode) {
65 default: llvm_unreachable("Unknown cast instruction!");
66 case Instruction::Trunc : return bitc::CAST_TRUNC;
67 case Instruction::ZExt : return bitc::CAST_ZEXT;
68 case Instruction::SExt : return bitc::CAST_SEXT;
69 case Instruction::FPToUI : return bitc::CAST_FPTOUI;
70 case Instruction::FPToSI : return bitc::CAST_FPTOSI;
71 case Instruction::UIToFP : return bitc::CAST_UITOFP;
72 case Instruction::SIToFP : return bitc::CAST_SITOFP;
73 case Instruction::FPTrunc : return bitc::CAST_FPTRUNC;
74 case Instruction::FPExt : return bitc::CAST_FPEXT;
75 case Instruction::PtrToInt: return bitc::CAST_PTRTOINT;
76 case Instruction::IntToPtr: return bitc::CAST_INTTOPTR;
77 case Instruction::BitCast : return bitc::CAST_BITCAST;
78 case Instruction::AddrSpaceCast: return bitc::CAST_ADDRSPACECAST;
82 static unsigned GetEncodedBinaryOpcode(unsigned Opcode) {
84 default: llvm_unreachable("Unknown binary instruction!");
85 case Instruction::Add:
86 case Instruction::FAdd: return bitc::BINOP_ADD;
87 case Instruction::Sub:
88 case Instruction::FSub: return bitc::BINOP_SUB;
89 case Instruction::Mul:
90 case Instruction::FMul: return bitc::BINOP_MUL;
91 case Instruction::UDiv: return bitc::BINOP_UDIV;
92 case Instruction::FDiv:
93 case Instruction::SDiv: return bitc::BINOP_SDIV;
94 case Instruction::URem: return bitc::BINOP_UREM;
95 case Instruction::FRem:
96 case Instruction::SRem: return bitc::BINOP_SREM;
97 case Instruction::Shl: return bitc::BINOP_SHL;
98 case Instruction::LShr: return bitc::BINOP_LSHR;
99 case Instruction::AShr: return bitc::BINOP_ASHR;
100 case Instruction::And: return bitc::BINOP_AND;
101 case Instruction::Or: return bitc::BINOP_OR;
102 case Instruction::Xor: return bitc::BINOP_XOR;
106 static unsigned GetEncodedRMWOperation(AtomicRMWInst::BinOp Op) {
108 default: llvm_unreachable("Unknown RMW operation!");
109 case AtomicRMWInst::Xchg: return bitc::RMW_XCHG;
110 case AtomicRMWInst::Add: return bitc::RMW_ADD;
111 case AtomicRMWInst::Sub: return bitc::RMW_SUB;
112 case AtomicRMWInst::And: return bitc::RMW_AND;
113 case AtomicRMWInst::Nand: return bitc::RMW_NAND;
114 case AtomicRMWInst::Or: return bitc::RMW_OR;
115 case AtomicRMWInst::Xor: return bitc::RMW_XOR;
116 case AtomicRMWInst::Max: return bitc::RMW_MAX;
117 case AtomicRMWInst::Min: return bitc::RMW_MIN;
118 case AtomicRMWInst::UMax: return bitc::RMW_UMAX;
119 case AtomicRMWInst::UMin: return bitc::RMW_UMIN;
123 static unsigned GetEncodedOrdering(AtomicOrdering Ordering) {
125 case NotAtomic: return bitc::ORDERING_NOTATOMIC;
126 case Unordered: return bitc::ORDERING_UNORDERED;
127 case Monotonic: return bitc::ORDERING_MONOTONIC;
128 case Acquire: return bitc::ORDERING_ACQUIRE;
129 case Release: return bitc::ORDERING_RELEASE;
130 case AcquireRelease: return bitc::ORDERING_ACQREL;
131 case SequentiallyConsistent: return bitc::ORDERING_SEQCST;
133 llvm_unreachable("Invalid ordering");
136 static unsigned GetEncodedSynchScope(SynchronizationScope SynchScope) {
137 switch (SynchScope) {
138 case SingleThread: return bitc::SYNCHSCOPE_SINGLETHREAD;
139 case CrossThread: return bitc::SYNCHSCOPE_CROSSTHREAD;
141 llvm_unreachable("Invalid synch scope");
144 static void WriteStringRecord(unsigned Code, StringRef Str,
145 unsigned AbbrevToUse, BitstreamWriter &Stream) {
146 SmallVector<unsigned, 64> Vals;
148 // Code: [strchar x N]
149 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
150 if (AbbrevToUse && !BitCodeAbbrevOp::isChar6(Str[i]))
152 Vals.push_back(Str[i]);
155 // Emit the finished record.
156 Stream.EmitRecord(Code, Vals, AbbrevToUse);
159 static uint64_t getAttrKindEncoding(Attribute::AttrKind Kind) {
161 case Attribute::Alignment:
162 return bitc::ATTR_KIND_ALIGNMENT;
163 case Attribute::AlwaysInline:
164 return bitc::ATTR_KIND_ALWAYS_INLINE;
165 case Attribute::Builtin:
166 return bitc::ATTR_KIND_BUILTIN;
167 case Attribute::ByVal:
168 return bitc::ATTR_KIND_BY_VAL;
169 case Attribute::InAlloca:
170 return bitc::ATTR_KIND_IN_ALLOCA;
171 case Attribute::Cold:
172 return bitc::ATTR_KIND_COLD;
173 case Attribute::InlineHint:
174 return bitc::ATTR_KIND_INLINE_HINT;
175 case Attribute::InReg:
176 return bitc::ATTR_KIND_IN_REG;
177 case Attribute::JumpTable:
178 return bitc::ATTR_KIND_JUMP_TABLE;
179 case Attribute::MinSize:
180 return bitc::ATTR_KIND_MIN_SIZE;
181 case Attribute::Naked:
182 return bitc::ATTR_KIND_NAKED;
183 case Attribute::Nest:
184 return bitc::ATTR_KIND_NEST;
185 case Attribute::NoAlias:
186 return bitc::ATTR_KIND_NO_ALIAS;
187 case Attribute::NoBuiltin:
188 return bitc::ATTR_KIND_NO_BUILTIN;
189 case Attribute::NoCapture:
190 return bitc::ATTR_KIND_NO_CAPTURE;
191 case Attribute::NoDuplicate:
192 return bitc::ATTR_KIND_NO_DUPLICATE;
193 case Attribute::NoImplicitFloat:
194 return bitc::ATTR_KIND_NO_IMPLICIT_FLOAT;
195 case Attribute::NoInline:
196 return bitc::ATTR_KIND_NO_INLINE;
197 case Attribute::NonLazyBind:
198 return bitc::ATTR_KIND_NON_LAZY_BIND;
199 case Attribute::NonNull:
200 return bitc::ATTR_KIND_NON_NULL;
201 case Attribute::Dereferenceable:
202 return bitc::ATTR_KIND_DEREFERENCEABLE;
203 case Attribute::NoRedZone:
204 return bitc::ATTR_KIND_NO_RED_ZONE;
205 case Attribute::NoReturn:
206 return bitc::ATTR_KIND_NO_RETURN;
207 case Attribute::NoUnwind:
208 return bitc::ATTR_KIND_NO_UNWIND;
209 case Attribute::OptimizeForSize:
210 return bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE;
211 case Attribute::OptimizeNone:
212 return bitc::ATTR_KIND_OPTIMIZE_NONE;
213 case Attribute::ReadNone:
214 return bitc::ATTR_KIND_READ_NONE;
215 case Attribute::ReadOnly:
216 return bitc::ATTR_KIND_READ_ONLY;
217 case Attribute::Returned:
218 return bitc::ATTR_KIND_RETURNED;
219 case Attribute::ReturnsTwice:
220 return bitc::ATTR_KIND_RETURNS_TWICE;
221 case Attribute::SExt:
222 return bitc::ATTR_KIND_S_EXT;
223 case Attribute::StackAlignment:
224 return bitc::ATTR_KIND_STACK_ALIGNMENT;
225 case Attribute::StackProtect:
226 return bitc::ATTR_KIND_STACK_PROTECT;
227 case Attribute::StackProtectReq:
228 return bitc::ATTR_KIND_STACK_PROTECT_REQ;
229 case Attribute::StackProtectStrong:
230 return bitc::ATTR_KIND_STACK_PROTECT_STRONG;
231 case Attribute::StructRet:
232 return bitc::ATTR_KIND_STRUCT_RET;
233 case Attribute::SanitizeAddress:
234 return bitc::ATTR_KIND_SANITIZE_ADDRESS;
235 case Attribute::SanitizeThread:
236 return bitc::ATTR_KIND_SANITIZE_THREAD;
237 case Attribute::SanitizeMemory:
238 return bitc::ATTR_KIND_SANITIZE_MEMORY;
239 case Attribute::UWTable:
240 return bitc::ATTR_KIND_UW_TABLE;
241 case Attribute::ZExt:
242 return bitc::ATTR_KIND_Z_EXT;
243 case Attribute::EndAttrKinds:
244 llvm_unreachable("Can not encode end-attribute kinds marker.");
245 case Attribute::None:
246 llvm_unreachable("Can not encode none-attribute.");
249 llvm_unreachable("Trying to encode unknown attribute");
252 static void WriteAttributeGroupTable(const ValueEnumerator &VE,
253 BitstreamWriter &Stream) {
254 const std::vector<AttributeSet> &AttrGrps = VE.getAttributeGroups();
255 if (AttrGrps.empty()) return;
257 Stream.EnterSubblock(bitc::PARAMATTR_GROUP_BLOCK_ID, 3);
259 SmallVector<uint64_t, 64> Record;
260 for (unsigned i = 0, e = AttrGrps.size(); i != e; ++i) {
261 AttributeSet AS = AttrGrps[i];
262 for (unsigned i = 0, e = AS.getNumSlots(); i != e; ++i) {
263 AttributeSet A = AS.getSlotAttributes(i);
265 Record.push_back(VE.getAttributeGroupID(A));
266 Record.push_back(AS.getSlotIndex(i));
268 for (AttributeSet::iterator I = AS.begin(0), E = AS.end(0);
271 if (Attr.isEnumAttribute()) {
273 Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
274 } else if (Attr.isIntAttribute()) {
276 Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
277 Record.push_back(Attr.getValueAsInt());
279 StringRef Kind = Attr.getKindAsString();
280 StringRef Val = Attr.getValueAsString();
282 Record.push_back(Val.empty() ? 3 : 4);
283 Record.append(Kind.begin(), Kind.end());
286 Record.append(Val.begin(), Val.end());
292 Stream.EmitRecord(bitc::PARAMATTR_GRP_CODE_ENTRY, Record);
300 static void WriteAttributeTable(const ValueEnumerator &VE,
301 BitstreamWriter &Stream) {
302 const std::vector<AttributeSet> &Attrs = VE.getAttributes();
303 if (Attrs.empty()) return;
305 Stream.EnterSubblock(bitc::PARAMATTR_BLOCK_ID, 3);
307 SmallVector<uint64_t, 64> Record;
308 for (unsigned i = 0, e = Attrs.size(); i != e; ++i) {
309 const AttributeSet &A = Attrs[i];
310 for (unsigned i = 0, e = A.getNumSlots(); i != e; ++i)
311 Record.push_back(VE.getAttributeGroupID(A.getSlotAttributes(i)));
313 Stream.EmitRecord(bitc::PARAMATTR_CODE_ENTRY, Record);
320 /// WriteTypeTable - Write out the type table for a module.
321 static void WriteTypeTable(const ValueEnumerator &VE, BitstreamWriter &Stream) {
322 const ValueEnumerator::TypeList &TypeList = VE.getTypes();
324 Stream.EnterSubblock(bitc::TYPE_BLOCK_ID_NEW, 4 /*count from # abbrevs */);
325 SmallVector<uint64_t, 64> TypeVals;
327 uint64_t NumBits = VE.computeBitsRequiredForTypeIndicies();
329 // Abbrev for TYPE_CODE_POINTER.
330 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
331 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_POINTER));
332 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
333 Abbv->Add(BitCodeAbbrevOp(0)); // Addrspace = 0
334 unsigned PtrAbbrev = Stream.EmitAbbrev(Abbv);
336 // Abbrev for TYPE_CODE_FUNCTION.
337 Abbv = new BitCodeAbbrev();
338 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_FUNCTION));
339 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // isvararg
340 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
341 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
343 unsigned FunctionAbbrev = Stream.EmitAbbrev(Abbv);
345 // Abbrev for TYPE_CODE_STRUCT_ANON.
346 Abbv = new BitCodeAbbrev();
347 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_ANON));
348 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
349 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
350 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
352 unsigned StructAnonAbbrev = Stream.EmitAbbrev(Abbv);
354 // Abbrev for TYPE_CODE_STRUCT_NAME.
355 Abbv = new BitCodeAbbrev();
356 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAME));
357 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
358 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
359 unsigned StructNameAbbrev = Stream.EmitAbbrev(Abbv);
361 // Abbrev for TYPE_CODE_STRUCT_NAMED.
362 Abbv = new BitCodeAbbrev();
363 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAMED));
364 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
365 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
366 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
368 unsigned StructNamedAbbrev = Stream.EmitAbbrev(Abbv);
370 // Abbrev for TYPE_CODE_ARRAY.
371 Abbv = new BitCodeAbbrev();
372 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_ARRAY));
373 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // size
374 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
376 unsigned ArrayAbbrev = Stream.EmitAbbrev(Abbv);
378 // Emit an entry count so the reader can reserve space.
379 TypeVals.push_back(TypeList.size());
380 Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals);
383 // Loop over all of the types, emitting each in turn.
384 for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
385 Type *T = TypeList[i];
389 switch (T->getTypeID()) {
390 case Type::VoidTyID: Code = bitc::TYPE_CODE_VOID; break;
391 case Type::HalfTyID: Code = bitc::TYPE_CODE_HALF; break;
392 case Type::FloatTyID: Code = bitc::TYPE_CODE_FLOAT; break;
393 case Type::DoubleTyID: Code = bitc::TYPE_CODE_DOUBLE; break;
394 case Type::X86_FP80TyID: Code = bitc::TYPE_CODE_X86_FP80; break;
395 case Type::FP128TyID: Code = bitc::TYPE_CODE_FP128; break;
396 case Type::PPC_FP128TyID: Code = bitc::TYPE_CODE_PPC_FP128; break;
397 case Type::LabelTyID: Code = bitc::TYPE_CODE_LABEL; break;
398 case Type::MetadataTyID: Code = bitc::TYPE_CODE_METADATA; break;
399 case Type::X86_MMXTyID: Code = bitc::TYPE_CODE_X86_MMX; break;
400 case Type::IntegerTyID:
402 Code = bitc::TYPE_CODE_INTEGER;
403 TypeVals.push_back(cast<IntegerType>(T)->getBitWidth());
405 case Type::PointerTyID: {
406 PointerType *PTy = cast<PointerType>(T);
407 // POINTER: [pointee type, address space]
408 Code = bitc::TYPE_CODE_POINTER;
409 TypeVals.push_back(VE.getTypeID(PTy->getElementType()));
410 unsigned AddressSpace = PTy->getAddressSpace();
411 TypeVals.push_back(AddressSpace);
412 if (AddressSpace == 0) AbbrevToUse = PtrAbbrev;
415 case Type::FunctionTyID: {
416 FunctionType *FT = cast<FunctionType>(T);
417 // FUNCTION: [isvararg, retty, paramty x N]
418 Code = bitc::TYPE_CODE_FUNCTION;
419 TypeVals.push_back(FT->isVarArg());
420 TypeVals.push_back(VE.getTypeID(FT->getReturnType()));
421 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
422 TypeVals.push_back(VE.getTypeID(FT->getParamType(i)));
423 AbbrevToUse = FunctionAbbrev;
426 case Type::StructTyID: {
427 StructType *ST = cast<StructType>(T);
428 // STRUCT: [ispacked, eltty x N]
429 TypeVals.push_back(ST->isPacked());
430 // Output all of the element types.
431 for (StructType::element_iterator I = ST->element_begin(),
432 E = ST->element_end(); I != E; ++I)
433 TypeVals.push_back(VE.getTypeID(*I));
435 if (ST->isLiteral()) {
436 Code = bitc::TYPE_CODE_STRUCT_ANON;
437 AbbrevToUse = StructAnonAbbrev;
439 if (ST->isOpaque()) {
440 Code = bitc::TYPE_CODE_OPAQUE;
442 Code = bitc::TYPE_CODE_STRUCT_NAMED;
443 AbbrevToUse = StructNamedAbbrev;
446 // Emit the name if it is present.
447 if (!ST->getName().empty())
448 WriteStringRecord(bitc::TYPE_CODE_STRUCT_NAME, ST->getName(),
449 StructNameAbbrev, Stream);
453 case Type::ArrayTyID: {
454 ArrayType *AT = cast<ArrayType>(T);
455 // ARRAY: [numelts, eltty]
456 Code = bitc::TYPE_CODE_ARRAY;
457 TypeVals.push_back(AT->getNumElements());
458 TypeVals.push_back(VE.getTypeID(AT->getElementType()));
459 AbbrevToUse = ArrayAbbrev;
462 case Type::VectorTyID: {
463 VectorType *VT = cast<VectorType>(T);
464 // VECTOR [numelts, eltty]
465 Code = bitc::TYPE_CODE_VECTOR;
466 TypeVals.push_back(VT->getNumElements());
467 TypeVals.push_back(VE.getTypeID(VT->getElementType()));
472 // Emit the finished record.
473 Stream.EmitRecord(Code, TypeVals, AbbrevToUse);
480 static unsigned getEncodedLinkage(const GlobalValue &GV) {
481 switch (GV.getLinkage()) {
482 case GlobalValue::ExternalLinkage:
484 case GlobalValue::WeakAnyLinkage:
486 case GlobalValue::AppendingLinkage:
488 case GlobalValue::InternalLinkage:
490 case GlobalValue::LinkOnceAnyLinkage:
492 case GlobalValue::ExternalWeakLinkage:
494 case GlobalValue::CommonLinkage:
496 case GlobalValue::PrivateLinkage:
498 case GlobalValue::WeakODRLinkage:
500 case GlobalValue::LinkOnceODRLinkage:
502 case GlobalValue::AvailableExternallyLinkage:
505 llvm_unreachable("Invalid linkage");
508 static unsigned getEncodedVisibility(const GlobalValue &GV) {
509 switch (GV.getVisibility()) {
510 case GlobalValue::DefaultVisibility: return 0;
511 case GlobalValue::HiddenVisibility: return 1;
512 case GlobalValue::ProtectedVisibility: return 2;
514 llvm_unreachable("Invalid visibility");
517 static unsigned getEncodedDLLStorageClass(const GlobalValue &GV) {
518 switch (GV.getDLLStorageClass()) {
519 case GlobalValue::DefaultStorageClass: return 0;
520 case GlobalValue::DLLImportStorageClass: return 1;
521 case GlobalValue::DLLExportStorageClass: return 2;
523 llvm_unreachable("Invalid DLL storage class");
526 static unsigned getEncodedThreadLocalMode(const GlobalValue &GV) {
527 switch (GV.getThreadLocalMode()) {
528 case GlobalVariable::NotThreadLocal: return 0;
529 case GlobalVariable::GeneralDynamicTLSModel: return 1;
530 case GlobalVariable::LocalDynamicTLSModel: return 2;
531 case GlobalVariable::InitialExecTLSModel: return 3;
532 case GlobalVariable::LocalExecTLSModel: return 4;
534 llvm_unreachable("Invalid TLS model");
537 static unsigned getEncodedComdatSelectionKind(const Comdat &C) {
538 switch (C.getSelectionKind()) {
540 return bitc::COMDAT_SELECTION_KIND_ANY;
541 case Comdat::ExactMatch:
542 return bitc::COMDAT_SELECTION_KIND_EXACT_MATCH;
543 case Comdat::Largest:
544 return bitc::COMDAT_SELECTION_KIND_LARGEST;
545 case Comdat::NoDuplicates:
546 return bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES;
547 case Comdat::SameSize:
548 return bitc::COMDAT_SELECTION_KIND_SAME_SIZE;
550 llvm_unreachable("Invalid selection kind");
553 static void writeComdats(const ValueEnumerator &VE, BitstreamWriter &Stream) {
554 SmallVector<uint16_t, 64> Vals;
555 for (const Comdat *C : VE.getComdats()) {
556 // COMDAT: [selection_kind, name]
557 Vals.push_back(getEncodedComdatSelectionKind(*C));
558 size_t Size = C->getName().size();
559 assert(isUInt<16>(Size));
560 Vals.push_back(Size);
561 for (char Chr : C->getName())
562 Vals.push_back((unsigned char)Chr);
563 Stream.EmitRecord(bitc::MODULE_CODE_COMDAT, Vals, /*AbbrevToUse=*/0);
568 // Emit top-level description of module, including target triple, inline asm,
569 // descriptors for global variables, and function prototype info.
570 static void WriteModuleInfo(const Module *M, const ValueEnumerator &VE,
571 BitstreamWriter &Stream) {
572 // Emit various pieces of data attached to a module.
573 if (!M->getTargetTriple().empty())
574 WriteStringRecord(bitc::MODULE_CODE_TRIPLE, M->getTargetTriple(),
576 const std::string &DL = M->getDataLayoutStr();
578 WriteStringRecord(bitc::MODULE_CODE_DATALAYOUT, DL, 0 /*TODO*/, Stream);
579 if (!M->getModuleInlineAsm().empty())
580 WriteStringRecord(bitc::MODULE_CODE_ASM, M->getModuleInlineAsm(),
583 // Emit information about sections and GC, computing how many there are. Also
584 // compute the maximum alignment value.
585 std::map<std::string, unsigned> SectionMap;
586 std::map<std::string, unsigned> GCMap;
587 unsigned MaxAlignment = 0;
588 unsigned MaxGlobalType = 0;
589 for (const GlobalValue &GV : M->globals()) {
590 MaxAlignment = std::max(MaxAlignment, GV.getAlignment());
591 MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV.getType()));
592 if (GV.hasSection()) {
593 // Give section names unique ID's.
594 unsigned &Entry = SectionMap[GV.getSection()];
596 WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, GV.getSection(),
598 Entry = SectionMap.size();
602 for (const Function &F : *M) {
603 MaxAlignment = std::max(MaxAlignment, F.getAlignment());
604 if (F.hasSection()) {
605 // Give section names unique ID's.
606 unsigned &Entry = SectionMap[F.getSection()];
608 WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, F.getSection(),
610 Entry = SectionMap.size();
614 // Same for GC names.
615 unsigned &Entry = GCMap[F.getGC()];
617 WriteStringRecord(bitc::MODULE_CODE_GCNAME, F.getGC(),
619 Entry = GCMap.size();
624 // Emit abbrev for globals, now that we know # sections and max alignment.
625 unsigned SimpleGVarAbbrev = 0;
626 if (!M->global_empty()) {
627 // Add an abbrev for common globals with no visibility or thread localness.
628 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
629 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GLOBALVAR));
630 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
631 Log2_32_Ceil(MaxGlobalType+1)));
632 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Constant.
633 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Initializer.
634 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5)); // Linkage.
635 if (MaxAlignment == 0) // Alignment.
636 Abbv->Add(BitCodeAbbrevOp(0));
638 unsigned MaxEncAlignment = Log2_32(MaxAlignment)+1;
639 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
640 Log2_32_Ceil(MaxEncAlignment+1)));
642 if (SectionMap.empty()) // Section.
643 Abbv->Add(BitCodeAbbrevOp(0));
645 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
646 Log2_32_Ceil(SectionMap.size()+1)));
647 // Don't bother emitting vis + thread local.
648 SimpleGVarAbbrev = Stream.EmitAbbrev(Abbv);
651 // Emit the global variable information.
652 SmallVector<unsigned, 64> Vals;
653 for (const GlobalVariable &GV : M->globals()) {
654 unsigned AbbrevToUse = 0;
656 // GLOBALVAR: [type, isconst, initid,
657 // linkage, alignment, section, visibility, threadlocal,
658 // unnamed_addr, externally_initialized, dllstorageclass,
660 Vals.push_back(VE.getTypeID(GV.getType()));
661 Vals.push_back(GV.isConstant());
662 Vals.push_back(GV.isDeclaration() ? 0 :
663 (VE.getValueID(GV.getInitializer()) + 1));
664 Vals.push_back(getEncodedLinkage(GV));
665 Vals.push_back(Log2_32(GV.getAlignment())+1);
666 Vals.push_back(GV.hasSection() ? SectionMap[GV.getSection()] : 0);
667 if (GV.isThreadLocal() ||
668 GV.getVisibility() != GlobalValue::DefaultVisibility ||
669 GV.hasUnnamedAddr() || GV.isExternallyInitialized() ||
670 GV.getDLLStorageClass() != GlobalValue::DefaultStorageClass ||
672 Vals.push_back(getEncodedVisibility(GV));
673 Vals.push_back(getEncodedThreadLocalMode(GV));
674 Vals.push_back(GV.hasUnnamedAddr());
675 Vals.push_back(GV.isExternallyInitialized());
676 Vals.push_back(getEncodedDLLStorageClass(GV));
677 Vals.push_back(GV.hasComdat() ? VE.getComdatID(GV.getComdat()) : 0);
679 AbbrevToUse = SimpleGVarAbbrev;
682 Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse);
686 // Emit the function proto information.
687 for (const Function &F : *M) {
688 // FUNCTION: [type, callingconv, isproto, linkage, paramattrs, alignment,
689 // section, visibility, gc, unnamed_addr, prologuedata,
690 // dllstorageclass, comdat, prefixdata]
691 Vals.push_back(VE.getTypeID(F.getType()));
692 Vals.push_back(F.getCallingConv());
693 Vals.push_back(F.isDeclaration());
694 Vals.push_back(getEncodedLinkage(F));
695 Vals.push_back(VE.getAttributeID(F.getAttributes()));
696 Vals.push_back(Log2_32(F.getAlignment())+1);
697 Vals.push_back(F.hasSection() ? SectionMap[F.getSection()] : 0);
698 Vals.push_back(getEncodedVisibility(F));
699 Vals.push_back(F.hasGC() ? GCMap[F.getGC()] : 0);
700 Vals.push_back(F.hasUnnamedAddr());
701 Vals.push_back(F.hasPrologueData() ? (VE.getValueID(F.getPrologueData()) + 1)
703 Vals.push_back(getEncodedDLLStorageClass(F));
704 Vals.push_back(F.hasComdat() ? VE.getComdatID(F.getComdat()) : 0);
705 Vals.push_back(F.hasPrefixData() ? (VE.getValueID(F.getPrefixData()) + 1)
708 unsigned AbbrevToUse = 0;
709 Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse);
713 // Emit the alias information.
714 for (const GlobalAlias &A : M->aliases()) {
715 // ALIAS: [alias type, aliasee val#, linkage, visibility]
716 Vals.push_back(VE.getTypeID(A.getType()));
717 Vals.push_back(VE.getValueID(A.getAliasee()));
718 Vals.push_back(getEncodedLinkage(A));
719 Vals.push_back(getEncodedVisibility(A));
720 Vals.push_back(getEncodedDLLStorageClass(A));
721 Vals.push_back(getEncodedThreadLocalMode(A));
722 Vals.push_back(A.hasUnnamedAddr());
723 unsigned AbbrevToUse = 0;
724 Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse);
729 static uint64_t GetOptimizationFlags(const Value *V) {
732 if (const auto *OBO = dyn_cast<OverflowingBinaryOperator>(V)) {
733 if (OBO->hasNoSignedWrap())
734 Flags |= 1 << bitc::OBO_NO_SIGNED_WRAP;
735 if (OBO->hasNoUnsignedWrap())
736 Flags |= 1 << bitc::OBO_NO_UNSIGNED_WRAP;
737 } else if (const auto *PEO = dyn_cast<PossiblyExactOperator>(V)) {
739 Flags |= 1 << bitc::PEO_EXACT;
740 } else if (const auto *FPMO = dyn_cast<FPMathOperator>(V)) {
741 if (FPMO->hasUnsafeAlgebra())
742 Flags |= FastMathFlags::UnsafeAlgebra;
743 if (FPMO->hasNoNaNs())
744 Flags |= FastMathFlags::NoNaNs;
745 if (FPMO->hasNoInfs())
746 Flags |= FastMathFlags::NoInfs;
747 if (FPMO->hasNoSignedZeros())
748 Flags |= FastMathFlags::NoSignedZeros;
749 if (FPMO->hasAllowReciprocal())
750 Flags |= FastMathFlags::AllowReciprocal;
756 static void WriteValueAsMetadata(const ValueAsMetadata *MD,
757 const ValueEnumerator &VE,
758 BitstreamWriter &Stream,
759 SmallVectorImpl<uint64_t> &Record) {
760 // Mimic an MDNode with a value as one operand.
761 Value *V = MD->getValue();
762 Record.push_back(VE.getTypeID(V->getType()));
763 Record.push_back(VE.getValueID(V));
764 Stream.EmitRecord(bitc::METADATA_VALUE, Record, 0);
768 static void WriteMDTuple(const MDTuple *N, const ValueEnumerator &VE,
769 BitstreamWriter &Stream,
770 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev) {
771 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
772 Metadata *MD = N->getOperand(i);
773 assert(!(MD && isa<LocalAsMetadata>(MD)) &&
774 "Unexpected function-local metadata");
775 Record.push_back(VE.getMetadataOrNullID(MD));
777 Stream.EmitRecord(N->isDistinct() ? bitc::METADATA_DISTINCT_NODE
778 : bitc::METADATA_NODE,
783 static void WriteMDLocation(const MDLocation *N, const ValueEnumerator &VE,
784 BitstreamWriter &Stream,
785 SmallVectorImpl<uint64_t> &Record,
787 Record.push_back(N->isDistinct());
788 Record.push_back(N->getLine());
789 Record.push_back(N->getColumn());
790 Record.push_back(VE.getMetadataID(N->getScope()));
791 Record.push_back(VE.getMetadataOrNullID(N->getInlinedAt()));
793 Stream.EmitRecord(bitc::METADATA_LOCATION, Record, Abbrev);
797 static void WriteGenericDebugNode(const GenericDebugNode *N,
798 const ValueEnumerator &VE,
799 BitstreamWriter &Stream,
800 SmallVectorImpl<uint64_t> &Record,
802 Record.push_back(N->isDistinct());
803 Record.push_back(N->getTag());
804 Record.push_back(0); // Per-tag version field; unused for now.
806 for (auto &I : N->operands())
807 Record.push_back(VE.getMetadataOrNullID(I));
809 Stream.EmitRecord(bitc::METADATA_GENERIC_DEBUG, Record, Abbrev);
813 static uint64_t rotateSign(int64_t I) {
815 return I < 0 ? ~(U << 1) : U << 1;
818 static void WriteMDSubrange(const MDSubrange *N, const ValueEnumerator &,
819 BitstreamWriter &Stream,
820 SmallVectorImpl<uint64_t> &Record,
822 Record.push_back(N->isDistinct());
823 Record.push_back(N->getCount());
824 Record.push_back(rotateSign(N->getLo()));
826 Stream.EmitRecord(bitc::METADATA_SUBRANGE, Record, Abbrev);
830 static void WriteMDEnumerator(const MDEnumerator *N, const ValueEnumerator &VE,
831 BitstreamWriter &Stream,
832 SmallVectorImpl<uint64_t> &Record,
834 Record.push_back(N->isDistinct());
835 Record.push_back(rotateSign(N->getValue()));
836 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
838 Stream.EmitRecord(bitc::METADATA_ENUMERATOR, Record, Abbrev);
842 static void WriteMDBasicType(const MDBasicType *N, const ValueEnumerator &VE,
843 BitstreamWriter &Stream,
844 SmallVectorImpl<uint64_t> &Record,
846 Record.push_back(N->isDistinct());
847 Record.push_back(N->getTag());
848 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
849 Record.push_back(N->getSizeInBits());
850 Record.push_back(N->getAlignInBits());
851 Record.push_back(N->getEncoding());
853 Stream.EmitRecord(bitc::METADATA_BASIC_TYPE, Record, Abbrev);
857 static void WriteMDDerivedType(const MDDerivedType *N,
858 const ValueEnumerator &VE,
859 BitstreamWriter &Stream,
860 SmallVectorImpl<uint64_t> &Record,
862 Record.push_back(N->isDistinct());
863 Record.push_back(N->getTag());
864 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
865 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
866 Record.push_back(N->getLine());
867 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
868 Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
869 Record.push_back(N->getSizeInBits());
870 Record.push_back(N->getAlignInBits());
871 Record.push_back(N->getOffsetInBits());
872 Record.push_back(N->getFlags());
873 Record.push_back(VE.getMetadataOrNullID(N->getExtraData()));
875 Stream.EmitRecord(bitc::METADATA_DERIVED_TYPE, Record, Abbrev);
879 static void WriteMDCompositeType(const MDCompositeType *N,
880 const ValueEnumerator &VE,
881 BitstreamWriter &Stream,
882 SmallVectorImpl<uint64_t> &Record,
884 Record.push_back(N->isDistinct());
885 Record.push_back(N->getTag());
886 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
887 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
888 Record.push_back(N->getLine());
889 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
890 Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
891 Record.push_back(N->getSizeInBits());
892 Record.push_back(N->getAlignInBits());
893 Record.push_back(N->getOffsetInBits());
894 Record.push_back(N->getFlags());
895 Record.push_back(VE.getMetadataOrNullID(N->getElements()));
896 Record.push_back(N->getRuntimeLang());
897 Record.push_back(VE.getMetadataOrNullID(N->getVTableHolder()));
898 Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams()));
899 Record.push_back(VE.getMetadataOrNullID(N->getRawIdentifier()));
901 Stream.EmitRecord(bitc::METADATA_COMPOSITE_TYPE, Record, Abbrev);
905 static void WriteMDSubroutineType(const MDSubroutineType *N,
906 const ValueEnumerator &VE,
907 BitstreamWriter &Stream,
908 SmallVectorImpl<uint64_t> &Record,
910 Record.push_back(N->isDistinct());
911 Record.push_back(N->getFlags());
912 Record.push_back(VE.getMetadataOrNullID(N->getTypeArray()));
914 Stream.EmitRecord(bitc::METADATA_SUBROUTINE_TYPE, Record, Abbrev);
918 static void WriteMDFile(const MDFile *N, const ValueEnumerator &VE,
919 BitstreamWriter &Stream,
920 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev) {
921 Record.push_back(N->isDistinct());
922 Record.push_back(VE.getMetadataOrNullID(N->getRawFilename()));
923 Record.push_back(VE.getMetadataOrNullID(N->getRawDirectory()));
925 Stream.EmitRecord(bitc::METADATA_FILE, Record, Abbrev);
929 static void WriteMDCompileUnit(const MDCompileUnit *N,
930 const ValueEnumerator &VE,
931 BitstreamWriter &Stream,
932 SmallVectorImpl<uint64_t> &Record,
934 Record.push_back(N->isDistinct());
935 Record.push_back(N->getSourceLanguage());
936 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
937 Record.push_back(VE.getMetadataOrNullID(N->getRawProducer()));
938 Record.push_back(N->isOptimized());
939 Record.push_back(VE.getMetadataOrNullID(N->getRawFlags()));
940 Record.push_back(N->getRuntimeVersion());
941 Record.push_back(VE.getMetadataOrNullID(N->getRawSplitDebugFilename()));
942 Record.push_back(N->getEmissionKind());
943 Record.push_back(VE.getMetadataOrNullID(N->getEnumTypes()));
944 Record.push_back(VE.getMetadataOrNullID(N->getRetainedTypes()));
945 Record.push_back(VE.getMetadataOrNullID(N->getSubprograms()));
946 Record.push_back(VE.getMetadataOrNullID(N->getGlobalVariables()));
947 Record.push_back(VE.getMetadataOrNullID(N->getImportedEntities()));
949 Stream.EmitRecord(bitc::METADATA_COMPILE_UNIT, Record, Abbrev);
953 static void WriteMDSubprogram(const MDSubprogram *N,
954 const ValueEnumerator &VE,
955 BitstreamWriter &Stream,
956 SmallVectorImpl<uint64_t> &Record,
958 Record.push_back(N->isDistinct());
959 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
960 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
961 Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
962 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
963 Record.push_back(N->getLine());
964 Record.push_back(VE.getMetadataOrNullID(N->getType()));
965 Record.push_back(N->isLocalToUnit());
966 Record.push_back(N->isDefinition());
967 Record.push_back(N->getScopeLine());
968 Record.push_back(VE.getMetadataOrNullID(N->getContainingType()));
969 Record.push_back(N->getVirtuality());
970 Record.push_back(N->getVirtualIndex());
971 Record.push_back(N->getFlags());
972 Record.push_back(N->isOptimized());
973 Record.push_back(VE.getMetadataOrNullID(N->getFunction()));
974 Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams()));
975 Record.push_back(VE.getMetadataOrNullID(N->getDeclaration()));
976 Record.push_back(VE.getMetadataOrNullID(N->getVariables()));
978 Stream.EmitRecord(bitc::METADATA_SUBPROGRAM, Record, Abbrev);
982 static void WriteMDLexicalBlock(const MDLexicalBlock *N,
983 const ValueEnumerator &VE,
984 BitstreamWriter &Stream,
985 SmallVectorImpl<uint64_t> &Record,
987 Record.push_back(N->isDistinct());
988 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
989 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
990 Record.push_back(N->getLine());
991 Record.push_back(N->getColumn());
993 Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK, Record, Abbrev);
997 static void WriteMDLexicalBlockFile(const MDLexicalBlockFile *N,
998 const ValueEnumerator &VE,
999 BitstreamWriter &Stream,
1000 SmallVectorImpl<uint64_t> &Record,
1002 Record.push_back(N->isDistinct());
1003 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1004 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1005 Record.push_back(N->getDiscriminator());
1007 Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK_FILE, Record, Abbrev);
1011 static void WriteMDNamespace(const MDNamespace *N, const ValueEnumerator &VE,
1012 BitstreamWriter &Stream,
1013 SmallVectorImpl<uint64_t> &Record,
1015 Record.push_back(N->isDistinct());
1016 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1017 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1018 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1019 Record.push_back(N->getLine());
1021 Stream.EmitRecord(bitc::METADATA_NAMESPACE, Record, Abbrev);
1025 static void WriteMDTemplateTypeParameter(const MDTemplateTypeParameter *N,
1026 const ValueEnumerator &VE,
1027 BitstreamWriter &Stream,
1028 SmallVectorImpl<uint64_t> &Record,
1030 Record.push_back(N->isDistinct());
1031 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1032 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1034 Stream.EmitRecord(bitc::METADATA_TEMPLATE_TYPE, Record, Abbrev);
1038 static void WriteMDTemplateValueParameter(const MDTemplateValueParameter *N,
1039 const ValueEnumerator &VE,
1040 BitstreamWriter &Stream,
1041 SmallVectorImpl<uint64_t> &Record,
1043 Record.push_back(N->isDistinct());
1044 Record.push_back(N->getTag());
1045 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1046 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1047 Record.push_back(VE.getMetadataOrNullID(N->getValue()));
1049 Stream.EmitRecord(bitc::METADATA_TEMPLATE_VALUE, Record, Abbrev);
1053 static void WriteMDGlobalVariable(const MDGlobalVariable *N,
1054 const ValueEnumerator &VE,
1055 BitstreamWriter &Stream,
1056 SmallVectorImpl<uint64_t> &Record,
1058 Record.push_back(N->isDistinct());
1059 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1060 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1061 Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
1062 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1063 Record.push_back(N->getLine());
1064 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1065 Record.push_back(N->isLocalToUnit());
1066 Record.push_back(N->isDefinition());
1067 Record.push_back(VE.getMetadataOrNullID(N->getVariable()));
1068 Record.push_back(VE.getMetadataOrNullID(N->getStaticDataMemberDeclaration()));
1070 Stream.EmitRecord(bitc::METADATA_GLOBAL_VAR, Record, Abbrev);
1074 static void WriteMDLocalVariable(const MDLocalVariable *N,
1075 const ValueEnumerator &VE,
1076 BitstreamWriter &Stream,
1077 SmallVectorImpl<uint64_t> &Record,
1079 Record.push_back(N->isDistinct());
1080 Record.push_back(N->getTag());
1081 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1082 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1083 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1084 Record.push_back(N->getLine());
1085 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1086 Record.push_back(N->getArg());
1087 Record.push_back(N->getFlags());
1088 Record.push_back(VE.getMetadataOrNullID(N->getInlinedAt()));
1090 Stream.EmitRecord(bitc::METADATA_LOCAL_VAR, Record, Abbrev);
1094 static void WriteMDExpression(const MDExpression *N, const ValueEnumerator &,
1095 BitstreamWriter &Stream,
1096 SmallVectorImpl<uint64_t> &Record,
1098 Record.reserve(N->getElements().size() + 1);
1100 Record.push_back(N->isDistinct());
1101 Record.append(N->elements_begin(), N->elements_end());
1103 Stream.EmitRecord(bitc::METADATA_EXPRESSION, Record, Abbrev);
1107 static void WriteMDObjCProperty(const MDObjCProperty *N,
1108 const ValueEnumerator &VE,
1109 BitstreamWriter &Stream,
1110 SmallVectorImpl<uint64_t> &Record,
1112 Record.push_back(N->isDistinct());
1113 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1114 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1115 Record.push_back(N->getLine());
1116 Record.push_back(VE.getMetadataOrNullID(N->getRawSetterName()));
1117 Record.push_back(VE.getMetadataOrNullID(N->getRawGetterName()));
1118 Record.push_back(N->getAttributes());
1119 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1121 Stream.EmitRecord(bitc::METADATA_OBJC_PROPERTY, Record, Abbrev);
1125 static void WriteMDImportedEntity(const MDImportedEntity *N,
1126 const ValueEnumerator &VE,
1127 BitstreamWriter &Stream,
1128 SmallVectorImpl<uint64_t> &Record,
1130 Record.push_back(N->isDistinct());
1131 Record.push_back(N->getTag());
1132 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1133 Record.push_back(VE.getMetadataOrNullID(N->getEntity()));
1134 Record.push_back(N->getLine());
1135 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1137 Stream.EmitRecord(bitc::METADATA_IMPORTED_ENTITY, Record, Abbrev);
1141 static void WriteModuleMetadata(const Module *M,
1142 const ValueEnumerator &VE,
1143 BitstreamWriter &Stream) {
1144 const auto &MDs = VE.getMDs();
1145 if (MDs.empty() && M->named_metadata_empty())
1148 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
1150 unsigned MDSAbbrev = 0;
1151 if (VE.hasMDString()) {
1152 // Abbrev for METADATA_STRING.
1153 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1154 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_STRING));
1155 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1156 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
1157 MDSAbbrev = Stream.EmitAbbrev(Abbv);
1160 // Initialize MDNode abbreviations.
1161 #define HANDLE_MDNODE_LEAF(CLASS) unsigned CLASS##Abbrev = 0;
1162 #include "llvm/IR/Metadata.def"
1164 if (VE.hasMDLocation()) {
1165 // Abbrev for METADATA_LOCATION.
1167 // Assume the column is usually under 128, and always output the inlined-at
1168 // location (it's never more expensive than building an array size 1).
1169 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1170 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_LOCATION));
1171 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1172 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1173 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1174 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1175 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1176 MDLocationAbbrev = Stream.EmitAbbrev(Abbv);
1179 if (VE.hasGenericDebugNode()) {
1180 // Abbrev for METADATA_GENERIC_DEBUG.
1182 // Assume the column is usually under 128, and always output the inlined-at
1183 // location (it's never more expensive than building an array size 1).
1184 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1185 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_GENERIC_DEBUG));
1186 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1187 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1188 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1189 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1190 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1191 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1192 GenericDebugNodeAbbrev = Stream.EmitAbbrev(Abbv);
1195 unsigned NameAbbrev = 0;
1196 if (!M->named_metadata_empty()) {
1197 // Abbrev for METADATA_NAME.
1198 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1199 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_NAME));
1200 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1201 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
1202 NameAbbrev = Stream.EmitAbbrev(Abbv);
1205 SmallVector<uint64_t, 64> Record;
1206 for (const Metadata *MD : MDs) {
1207 if (const MDNode *N = dyn_cast<MDNode>(MD)) {
1208 switch (N->getMetadataID()) {
1210 llvm_unreachable("Invalid MDNode subclass");
1211 #define HANDLE_MDNODE_LEAF(CLASS) \
1212 case Metadata::CLASS##Kind: \
1213 Write##CLASS(cast<CLASS>(N), VE, Stream, Record, CLASS##Abbrev); \
1215 #include "llvm/IR/Metadata.def"
1218 if (const auto *MDC = dyn_cast<ConstantAsMetadata>(MD)) {
1219 WriteValueAsMetadata(MDC, VE, Stream, Record);
1222 const MDString *MDS = cast<MDString>(MD);
1223 // Code: [strchar x N]
1224 Record.append(MDS->bytes_begin(), MDS->bytes_end());
1226 // Emit the finished record.
1227 Stream.EmitRecord(bitc::METADATA_STRING, Record, MDSAbbrev);
1231 // Write named metadata.
1232 for (const NamedMDNode &NMD : M->named_metadata()) {
1234 StringRef Str = NMD.getName();
1235 Record.append(Str.bytes_begin(), Str.bytes_end());
1236 Stream.EmitRecord(bitc::METADATA_NAME, Record, NameAbbrev);
1239 // Write named metadata operands.
1240 for (const MDNode *N : NMD.operands())
1241 Record.push_back(VE.getMetadataID(N));
1242 Stream.EmitRecord(bitc::METADATA_NAMED_NODE, Record, 0);
1249 static void WriteFunctionLocalMetadata(const Function &F,
1250 const ValueEnumerator &VE,
1251 BitstreamWriter &Stream) {
1252 bool StartedMetadataBlock = false;
1253 SmallVector<uint64_t, 64> Record;
1254 const SmallVectorImpl<const LocalAsMetadata *> &MDs =
1255 VE.getFunctionLocalMDs();
1256 for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
1257 assert(MDs[i] && "Expected valid function-local metadata");
1258 if (!StartedMetadataBlock) {
1259 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
1260 StartedMetadataBlock = true;
1262 WriteValueAsMetadata(MDs[i], VE, Stream, Record);
1265 if (StartedMetadataBlock)
1269 static void WriteMetadataAttachment(const Function &F,
1270 const ValueEnumerator &VE,
1271 BitstreamWriter &Stream) {
1272 Stream.EnterSubblock(bitc::METADATA_ATTACHMENT_ID, 3);
1274 SmallVector<uint64_t, 64> Record;
1276 // Write metadata attachments
1277 // METADATA_ATTACHMENT - [m x [value, [n x [id, mdnode]]]
1278 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
1280 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1281 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
1284 I->getAllMetadataOtherThanDebugLoc(MDs);
1286 // If no metadata, ignore instruction.
1287 if (MDs.empty()) continue;
1289 Record.push_back(VE.getInstructionID(I));
1291 for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
1292 Record.push_back(MDs[i].first);
1293 Record.push_back(VE.getMetadataID(MDs[i].second));
1295 Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
1302 static void WriteModuleMetadataStore(const Module *M, BitstreamWriter &Stream) {
1303 SmallVector<uint64_t, 64> Record;
1305 // Write metadata kinds
1306 // METADATA_KIND - [n x [id, name]]
1307 SmallVector<StringRef, 8> Names;
1308 M->getMDKindNames(Names);
1310 if (Names.empty()) return;
1312 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
1314 for (unsigned MDKindID = 0, e = Names.size(); MDKindID != e; ++MDKindID) {
1315 Record.push_back(MDKindID);
1316 StringRef KName = Names[MDKindID];
1317 Record.append(KName.begin(), KName.end());
1319 Stream.EmitRecord(bitc::METADATA_KIND, Record, 0);
1326 static void emitSignedInt64(SmallVectorImpl<uint64_t> &Vals, uint64_t V) {
1327 if ((int64_t)V >= 0)
1328 Vals.push_back(V << 1);
1330 Vals.push_back((-V << 1) | 1);
1333 static void WriteConstants(unsigned FirstVal, unsigned LastVal,
1334 const ValueEnumerator &VE,
1335 BitstreamWriter &Stream, bool isGlobal) {
1336 if (FirstVal == LastVal) return;
1338 Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 4);
1340 unsigned AggregateAbbrev = 0;
1341 unsigned String8Abbrev = 0;
1342 unsigned CString7Abbrev = 0;
1343 unsigned CString6Abbrev = 0;
1344 // If this is a constant pool for the module, emit module-specific abbrevs.
1346 // Abbrev for CST_CODE_AGGREGATE.
1347 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1348 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_AGGREGATE));
1349 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1350 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal+1)));
1351 AggregateAbbrev = Stream.EmitAbbrev(Abbv);
1353 // Abbrev for CST_CODE_STRING.
1354 Abbv = new BitCodeAbbrev();
1355 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_STRING));
1356 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1357 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
1358 String8Abbrev = Stream.EmitAbbrev(Abbv);
1359 // Abbrev for CST_CODE_CSTRING.
1360 Abbv = new BitCodeAbbrev();
1361 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
1362 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1363 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
1364 CString7Abbrev = Stream.EmitAbbrev(Abbv);
1365 // Abbrev for CST_CODE_CSTRING.
1366 Abbv = new BitCodeAbbrev();
1367 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
1368 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1369 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
1370 CString6Abbrev = Stream.EmitAbbrev(Abbv);
1373 SmallVector<uint64_t, 64> Record;
1375 const ValueEnumerator::ValueList &Vals = VE.getValues();
1376 Type *LastTy = nullptr;
1377 for (unsigned i = FirstVal; i != LastVal; ++i) {
1378 const Value *V = Vals[i].first;
1379 // If we need to switch types, do so now.
1380 if (V->getType() != LastTy) {
1381 LastTy = V->getType();
1382 Record.push_back(VE.getTypeID(LastTy));
1383 Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record,
1384 CONSTANTS_SETTYPE_ABBREV);
1388 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
1389 Record.push_back(unsigned(IA->hasSideEffects()) |
1390 unsigned(IA->isAlignStack()) << 1 |
1391 unsigned(IA->getDialect()&1) << 2);
1393 // Add the asm string.
1394 const std::string &AsmStr = IA->getAsmString();
1395 Record.push_back(AsmStr.size());
1396 Record.append(AsmStr.begin(), AsmStr.end());
1398 // Add the constraint string.
1399 const std::string &ConstraintStr = IA->getConstraintString();
1400 Record.push_back(ConstraintStr.size());
1401 Record.append(ConstraintStr.begin(), ConstraintStr.end());
1402 Stream.EmitRecord(bitc::CST_CODE_INLINEASM, Record);
1406 const Constant *C = cast<Constant>(V);
1407 unsigned Code = -1U;
1408 unsigned AbbrevToUse = 0;
1409 if (C->isNullValue()) {
1410 Code = bitc::CST_CODE_NULL;
1411 } else if (isa<UndefValue>(C)) {
1412 Code = bitc::CST_CODE_UNDEF;
1413 } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {
1414 if (IV->getBitWidth() <= 64) {
1415 uint64_t V = IV->getSExtValue();
1416 emitSignedInt64(Record, V);
1417 Code = bitc::CST_CODE_INTEGER;
1418 AbbrevToUse = CONSTANTS_INTEGER_ABBREV;
1419 } else { // Wide integers, > 64 bits in size.
1420 // We have an arbitrary precision integer value to write whose
1421 // bit width is > 64. However, in canonical unsigned integer
1422 // format it is likely that the high bits are going to be zero.
1423 // So, we only write the number of active words.
1424 unsigned NWords = IV->getValue().getActiveWords();
1425 const uint64_t *RawWords = IV->getValue().getRawData();
1426 for (unsigned i = 0; i != NWords; ++i) {
1427 emitSignedInt64(Record, RawWords[i]);
1429 Code = bitc::CST_CODE_WIDE_INTEGER;
1431 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
1432 Code = bitc::CST_CODE_FLOAT;
1433 Type *Ty = CFP->getType();
1434 if (Ty->isHalfTy() || Ty->isFloatTy() || Ty->isDoubleTy()) {
1435 Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
1436 } else if (Ty->isX86_FP80Ty()) {
1437 // api needed to prevent premature destruction
1438 // bits are not in the same order as a normal i80 APInt, compensate.
1439 APInt api = CFP->getValueAPF().bitcastToAPInt();
1440 const uint64_t *p = api.getRawData();
1441 Record.push_back((p[1] << 48) | (p[0] >> 16));
1442 Record.push_back(p[0] & 0xffffLL);
1443 } else if (Ty->isFP128Ty() || Ty->isPPC_FP128Ty()) {
1444 APInt api = CFP->getValueAPF().bitcastToAPInt();
1445 const uint64_t *p = api.getRawData();
1446 Record.push_back(p[0]);
1447 Record.push_back(p[1]);
1449 assert (0 && "Unknown FP type!");
1451 } else if (isa<ConstantDataSequential>(C) &&
1452 cast<ConstantDataSequential>(C)->isString()) {
1453 const ConstantDataSequential *Str = cast<ConstantDataSequential>(C);
1454 // Emit constant strings specially.
1455 unsigned NumElts = Str->getNumElements();
1456 // If this is a null-terminated string, use the denser CSTRING encoding.
1457 if (Str->isCString()) {
1458 Code = bitc::CST_CODE_CSTRING;
1459 --NumElts; // Don't encode the null, which isn't allowed by char6.
1461 Code = bitc::CST_CODE_STRING;
1462 AbbrevToUse = String8Abbrev;
1464 bool isCStr7 = Code == bitc::CST_CODE_CSTRING;
1465 bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING;
1466 for (unsigned i = 0; i != NumElts; ++i) {
1467 unsigned char V = Str->getElementAsInteger(i);
1468 Record.push_back(V);
1469 isCStr7 &= (V & 128) == 0;
1471 isCStrChar6 = BitCodeAbbrevOp::isChar6(V);
1475 AbbrevToUse = CString6Abbrev;
1477 AbbrevToUse = CString7Abbrev;
1478 } else if (const ConstantDataSequential *CDS =
1479 dyn_cast<ConstantDataSequential>(C)) {
1480 Code = bitc::CST_CODE_DATA;
1481 Type *EltTy = CDS->getType()->getElementType();
1482 if (isa<IntegerType>(EltTy)) {
1483 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
1484 Record.push_back(CDS->getElementAsInteger(i));
1485 } else if (EltTy->isFloatTy()) {
1486 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1487 union { float F; uint32_t I; };
1488 F = CDS->getElementAsFloat(i);
1489 Record.push_back(I);
1492 assert(EltTy->isDoubleTy() && "Unknown ConstantData element type");
1493 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1494 union { double F; uint64_t I; };
1495 F = CDS->getElementAsDouble(i);
1496 Record.push_back(I);
1499 } else if (isa<ConstantArray>(C) || isa<ConstantStruct>(C) ||
1500 isa<ConstantVector>(C)) {
1501 Code = bitc::CST_CODE_AGGREGATE;
1502 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i)
1503 Record.push_back(VE.getValueID(C->getOperand(i)));
1504 AbbrevToUse = AggregateAbbrev;
1505 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1506 switch (CE->getOpcode()) {
1508 if (Instruction::isCast(CE->getOpcode())) {
1509 Code = bitc::CST_CODE_CE_CAST;
1510 Record.push_back(GetEncodedCastOpcode(CE->getOpcode()));
1511 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
1512 Record.push_back(VE.getValueID(C->getOperand(0)));
1513 AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;
1515 assert(CE->getNumOperands() == 2 && "Unknown constant expr!");
1516 Code = bitc::CST_CODE_CE_BINOP;
1517 Record.push_back(GetEncodedBinaryOpcode(CE->getOpcode()));
1518 Record.push_back(VE.getValueID(C->getOperand(0)));
1519 Record.push_back(VE.getValueID(C->getOperand(1)));
1520 uint64_t Flags = GetOptimizationFlags(CE);
1522 Record.push_back(Flags);
1525 case Instruction::GetElementPtr: {
1526 Code = bitc::CST_CODE_CE_GEP;
1527 const auto *GO = cast<GEPOperator>(C);
1528 if (GO->isInBounds())
1529 Code = bitc::CST_CODE_CE_INBOUNDS_GEP;
1530 Record.push_back(VE.getTypeID(GO->getSourceElementType()));
1531 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
1532 Record.push_back(VE.getTypeID(C->getOperand(i)->getType()));
1533 Record.push_back(VE.getValueID(C->getOperand(i)));
1537 case Instruction::Select:
1538 Code = bitc::CST_CODE_CE_SELECT;
1539 Record.push_back(VE.getValueID(C->getOperand(0)));
1540 Record.push_back(VE.getValueID(C->getOperand(1)));
1541 Record.push_back(VE.getValueID(C->getOperand(2)));
1543 case Instruction::ExtractElement:
1544 Code = bitc::CST_CODE_CE_EXTRACTELT;
1545 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
1546 Record.push_back(VE.getValueID(C->getOperand(0)));
1547 Record.push_back(VE.getTypeID(C->getOperand(1)->getType()));
1548 Record.push_back(VE.getValueID(C->getOperand(1)));
1550 case Instruction::InsertElement:
1551 Code = bitc::CST_CODE_CE_INSERTELT;
1552 Record.push_back(VE.getValueID(C->getOperand(0)));
1553 Record.push_back(VE.getValueID(C->getOperand(1)));
1554 Record.push_back(VE.getTypeID(C->getOperand(2)->getType()));
1555 Record.push_back(VE.getValueID(C->getOperand(2)));
1557 case Instruction::ShuffleVector:
1558 // If the return type and argument types are the same, this is a
1559 // standard shufflevector instruction. If the types are different,
1560 // then the shuffle is widening or truncating the input vectors, and
1561 // the argument type must also be encoded.
1562 if (C->getType() == C->getOperand(0)->getType()) {
1563 Code = bitc::CST_CODE_CE_SHUFFLEVEC;
1565 Code = bitc::CST_CODE_CE_SHUFVEC_EX;
1566 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
1568 Record.push_back(VE.getValueID(C->getOperand(0)));
1569 Record.push_back(VE.getValueID(C->getOperand(1)));
1570 Record.push_back(VE.getValueID(C->getOperand(2)));
1572 case Instruction::ICmp:
1573 case Instruction::FCmp:
1574 Code = bitc::CST_CODE_CE_CMP;
1575 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
1576 Record.push_back(VE.getValueID(C->getOperand(0)));
1577 Record.push_back(VE.getValueID(C->getOperand(1)));
1578 Record.push_back(CE->getPredicate());
1581 } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) {
1582 Code = bitc::CST_CODE_BLOCKADDRESS;
1583 Record.push_back(VE.getTypeID(BA->getFunction()->getType()));
1584 Record.push_back(VE.getValueID(BA->getFunction()));
1585 Record.push_back(VE.getGlobalBasicBlockID(BA->getBasicBlock()));
1590 llvm_unreachable("Unknown constant!");
1592 Stream.EmitRecord(Code, Record, AbbrevToUse);
1599 static void WriteModuleConstants(const ValueEnumerator &VE,
1600 BitstreamWriter &Stream) {
1601 const ValueEnumerator::ValueList &Vals = VE.getValues();
1603 // Find the first constant to emit, which is the first non-globalvalue value.
1604 // We know globalvalues have been emitted by WriteModuleInfo.
1605 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
1606 if (!isa<GlobalValue>(Vals[i].first)) {
1607 WriteConstants(i, Vals.size(), VE, Stream, true);
1613 /// PushValueAndType - The file has to encode both the value and type id for
1614 /// many values, because we need to know what type to create for forward
1615 /// references. However, most operands are not forward references, so this type
1616 /// field is not needed.
1618 /// This function adds V's value ID to Vals. If the value ID is higher than the
1619 /// instruction ID, then it is a forward reference, and it also includes the
1620 /// type ID. The value ID that is written is encoded relative to the InstID.
1621 static bool PushValueAndType(const Value *V, unsigned InstID,
1622 SmallVectorImpl<unsigned> &Vals,
1623 ValueEnumerator &VE) {
1624 unsigned ValID = VE.getValueID(V);
1625 // Make encoding relative to the InstID.
1626 Vals.push_back(InstID - ValID);
1627 if (ValID >= InstID) {
1628 Vals.push_back(VE.getTypeID(V->getType()));
1634 /// pushValue - Like PushValueAndType, but where the type of the value is
1635 /// omitted (perhaps it was already encoded in an earlier operand).
1636 static void pushValue(const Value *V, unsigned InstID,
1637 SmallVectorImpl<unsigned> &Vals,
1638 ValueEnumerator &VE) {
1639 unsigned ValID = VE.getValueID(V);
1640 Vals.push_back(InstID - ValID);
1643 static void pushValueSigned(const Value *V, unsigned InstID,
1644 SmallVectorImpl<uint64_t> &Vals,
1645 ValueEnumerator &VE) {
1646 unsigned ValID = VE.getValueID(V);
1647 int64_t diff = ((int32_t)InstID - (int32_t)ValID);
1648 emitSignedInt64(Vals, diff);
1651 /// WriteInstruction - Emit an instruction to the specified stream.
1652 static void WriteInstruction(const Instruction &I, unsigned InstID,
1653 ValueEnumerator &VE, BitstreamWriter &Stream,
1654 SmallVectorImpl<unsigned> &Vals) {
1656 unsigned AbbrevToUse = 0;
1657 VE.setInstructionID(&I);
1658 switch (I.getOpcode()) {
1660 if (Instruction::isCast(I.getOpcode())) {
1661 Code = bitc::FUNC_CODE_INST_CAST;
1662 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
1663 AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
1664 Vals.push_back(VE.getTypeID(I.getType()));
1665 Vals.push_back(GetEncodedCastOpcode(I.getOpcode()));
1667 assert(isa<BinaryOperator>(I) && "Unknown instruction!");
1668 Code = bitc::FUNC_CODE_INST_BINOP;
1669 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
1670 AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
1671 pushValue(I.getOperand(1), InstID, Vals, VE);
1672 Vals.push_back(GetEncodedBinaryOpcode(I.getOpcode()));
1673 uint64_t Flags = GetOptimizationFlags(&I);
1675 if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV)
1676 AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV;
1677 Vals.push_back(Flags);
1682 case Instruction::GetElementPtr: {
1683 Code = bitc::FUNC_CODE_INST_GEP;
1684 AbbrevToUse = FUNCTION_INST_GEP_ABBREV;
1685 auto &GEPInst = cast<GetElementPtrInst>(I);
1686 Vals.push_back(GEPInst.isInBounds());
1687 Vals.push_back(VE.getTypeID(GEPInst.getSourceElementType()));
1688 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
1689 PushValueAndType(I.getOperand(i), InstID, Vals, VE);
1692 case Instruction::ExtractValue: {
1693 Code = bitc::FUNC_CODE_INST_EXTRACTVAL;
1694 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1695 const ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
1696 Vals.append(EVI->idx_begin(), EVI->idx_end());
1699 case Instruction::InsertValue: {
1700 Code = bitc::FUNC_CODE_INST_INSERTVAL;
1701 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1702 PushValueAndType(I.getOperand(1), InstID, Vals, VE);
1703 const InsertValueInst *IVI = cast<InsertValueInst>(&I);
1704 Vals.append(IVI->idx_begin(), IVI->idx_end());
1707 case Instruction::Select:
1708 Code = bitc::FUNC_CODE_INST_VSELECT;
1709 PushValueAndType(I.getOperand(1), InstID, Vals, VE);
1710 pushValue(I.getOperand(2), InstID, Vals, VE);
1711 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1713 case Instruction::ExtractElement:
1714 Code = bitc::FUNC_CODE_INST_EXTRACTELT;
1715 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1716 PushValueAndType(I.getOperand(1), InstID, Vals, VE);
1718 case Instruction::InsertElement:
1719 Code = bitc::FUNC_CODE_INST_INSERTELT;
1720 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1721 pushValue(I.getOperand(1), InstID, Vals, VE);
1722 PushValueAndType(I.getOperand(2), InstID, Vals, VE);
1724 case Instruction::ShuffleVector:
1725 Code = bitc::FUNC_CODE_INST_SHUFFLEVEC;
1726 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1727 pushValue(I.getOperand(1), InstID, Vals, VE);
1728 pushValue(I.getOperand(2), InstID, Vals, VE);
1730 case Instruction::ICmp:
1731 case Instruction::FCmp:
1732 // compare returning Int1Ty or vector of Int1Ty
1733 Code = bitc::FUNC_CODE_INST_CMP2;
1734 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1735 pushValue(I.getOperand(1), InstID, Vals, VE);
1736 Vals.push_back(cast<CmpInst>(I).getPredicate());
1739 case Instruction::Ret:
1741 Code = bitc::FUNC_CODE_INST_RET;
1742 unsigned NumOperands = I.getNumOperands();
1743 if (NumOperands == 0)
1744 AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
1745 else if (NumOperands == 1) {
1746 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
1747 AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
1749 for (unsigned i = 0, e = NumOperands; i != e; ++i)
1750 PushValueAndType(I.getOperand(i), InstID, Vals, VE);
1754 case Instruction::Br:
1756 Code = bitc::FUNC_CODE_INST_BR;
1757 const BranchInst &II = cast<BranchInst>(I);
1758 Vals.push_back(VE.getValueID(II.getSuccessor(0)));
1759 if (II.isConditional()) {
1760 Vals.push_back(VE.getValueID(II.getSuccessor(1)));
1761 pushValue(II.getCondition(), InstID, Vals, VE);
1765 case Instruction::Switch:
1767 Code = bitc::FUNC_CODE_INST_SWITCH;
1768 const SwitchInst &SI = cast<SwitchInst>(I);
1769 Vals.push_back(VE.getTypeID(SI.getCondition()->getType()));
1770 pushValue(SI.getCondition(), InstID, Vals, VE);
1771 Vals.push_back(VE.getValueID(SI.getDefaultDest()));
1772 for (SwitchInst::ConstCaseIt i = SI.case_begin(), e = SI.case_end();
1774 Vals.push_back(VE.getValueID(i.getCaseValue()));
1775 Vals.push_back(VE.getValueID(i.getCaseSuccessor()));
1779 case Instruction::IndirectBr:
1780 Code = bitc::FUNC_CODE_INST_INDIRECTBR;
1781 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
1782 // Encode the address operand as relative, but not the basic blocks.
1783 pushValue(I.getOperand(0), InstID, Vals, VE);
1784 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i)
1785 Vals.push_back(VE.getValueID(I.getOperand(i)));
1788 case Instruction::Invoke: {
1789 const InvokeInst *II = cast<InvokeInst>(&I);
1790 const Value *Callee(II->getCalledValue());
1791 PointerType *PTy = cast<PointerType>(Callee->getType());
1792 FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1793 Code = bitc::FUNC_CODE_INST_INVOKE;
1795 Vals.push_back(VE.getAttributeID(II->getAttributes()));
1796 Vals.push_back(II->getCallingConv());
1797 Vals.push_back(VE.getValueID(II->getNormalDest()));
1798 Vals.push_back(VE.getValueID(II->getUnwindDest()));
1799 PushValueAndType(Callee, InstID, Vals, VE);
1801 // Emit value #'s for the fixed parameters.
1802 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
1803 pushValue(I.getOperand(i), InstID, Vals, VE); // fixed param.
1805 // Emit type/value pairs for varargs params.
1806 if (FTy->isVarArg()) {
1807 for (unsigned i = FTy->getNumParams(), e = I.getNumOperands()-3;
1809 PushValueAndType(I.getOperand(i), InstID, Vals, VE); // vararg
1813 case Instruction::Resume:
1814 Code = bitc::FUNC_CODE_INST_RESUME;
1815 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1817 case Instruction::Unreachable:
1818 Code = bitc::FUNC_CODE_INST_UNREACHABLE;
1819 AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
1822 case Instruction::PHI: {
1823 const PHINode &PN = cast<PHINode>(I);
1824 Code = bitc::FUNC_CODE_INST_PHI;
1825 // With the newer instruction encoding, forward references could give
1826 // negative valued IDs. This is most common for PHIs, so we use
1828 SmallVector<uint64_t, 128> Vals64;
1829 Vals64.push_back(VE.getTypeID(PN.getType()));
1830 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
1831 pushValueSigned(PN.getIncomingValue(i), InstID, Vals64, VE);
1832 Vals64.push_back(VE.getValueID(PN.getIncomingBlock(i)));
1834 // Emit a Vals64 vector and exit.
1835 Stream.EmitRecord(Code, Vals64, AbbrevToUse);
1840 case Instruction::LandingPad: {
1841 const LandingPadInst &LP = cast<LandingPadInst>(I);
1842 Code = bitc::FUNC_CODE_INST_LANDINGPAD;
1843 Vals.push_back(VE.getTypeID(LP.getType()));
1844 PushValueAndType(LP.getPersonalityFn(), InstID, Vals, VE);
1845 Vals.push_back(LP.isCleanup());
1846 Vals.push_back(LP.getNumClauses());
1847 for (unsigned I = 0, E = LP.getNumClauses(); I != E; ++I) {
1849 Vals.push_back(LandingPadInst::Catch);
1851 Vals.push_back(LandingPadInst::Filter);
1852 PushValueAndType(LP.getClause(I), InstID, Vals, VE);
1857 case Instruction::Alloca: {
1858 Code = bitc::FUNC_CODE_INST_ALLOCA;
1859 Vals.push_back(VE.getTypeID(I.getType()));
1860 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
1861 Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
1862 const AllocaInst &AI = cast<AllocaInst>(I);
1863 unsigned AlignRecord = Log2_32(AI.getAlignment()) + 1;
1864 assert(Log2_32(Value::MaximumAlignment) + 1 < 1 << 5 &&
1865 "not enough bits for maximum alignment");
1866 assert(AlignRecord < 1 << 5 && "alignment greater than 1 << 64");
1867 AlignRecord |= AI.isUsedWithInAlloca() << 5;
1868 Vals.push_back(AlignRecord);
1872 case Instruction::Load:
1873 if (cast<LoadInst>(I).isAtomic()) {
1874 Code = bitc::FUNC_CODE_INST_LOADATOMIC;
1875 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1877 Code = bitc::FUNC_CODE_INST_LOAD;
1878 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE)) // ptr
1879 AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
1881 Vals.push_back(VE.getTypeID(I.getType()));
1882 Vals.push_back(Log2_32(cast<LoadInst>(I).getAlignment())+1);
1883 Vals.push_back(cast<LoadInst>(I).isVolatile());
1884 if (cast<LoadInst>(I).isAtomic()) {
1885 Vals.push_back(GetEncodedOrdering(cast<LoadInst>(I).getOrdering()));
1886 Vals.push_back(GetEncodedSynchScope(cast<LoadInst>(I).getSynchScope()));
1889 case Instruction::Store:
1890 if (cast<StoreInst>(I).isAtomic())
1891 Code = bitc::FUNC_CODE_INST_STOREATOMIC;
1893 Code = bitc::FUNC_CODE_INST_STORE;
1894 PushValueAndType(I.getOperand(1), InstID, Vals, VE); // ptrty + ptr
1895 pushValue(I.getOperand(0), InstID, Vals, VE); // val.
1896 Vals.push_back(Log2_32(cast<StoreInst>(I).getAlignment())+1);
1897 Vals.push_back(cast<StoreInst>(I).isVolatile());
1898 if (cast<StoreInst>(I).isAtomic()) {
1899 Vals.push_back(GetEncodedOrdering(cast<StoreInst>(I).getOrdering()));
1900 Vals.push_back(GetEncodedSynchScope(cast<StoreInst>(I).getSynchScope()));
1903 case Instruction::AtomicCmpXchg:
1904 Code = bitc::FUNC_CODE_INST_CMPXCHG;
1905 PushValueAndType(I.getOperand(0), InstID, Vals, VE); // ptrty + ptr
1906 pushValue(I.getOperand(1), InstID, Vals, VE); // cmp.
1907 pushValue(I.getOperand(2), InstID, Vals, VE); // newval.
1908 Vals.push_back(cast<AtomicCmpXchgInst>(I).isVolatile());
1909 Vals.push_back(GetEncodedOrdering(
1910 cast<AtomicCmpXchgInst>(I).getSuccessOrdering()));
1911 Vals.push_back(GetEncodedSynchScope(
1912 cast<AtomicCmpXchgInst>(I).getSynchScope()));
1913 Vals.push_back(GetEncodedOrdering(
1914 cast<AtomicCmpXchgInst>(I).getFailureOrdering()));
1915 Vals.push_back(cast<AtomicCmpXchgInst>(I).isWeak());
1917 case Instruction::AtomicRMW:
1918 Code = bitc::FUNC_CODE_INST_ATOMICRMW;
1919 PushValueAndType(I.getOperand(0), InstID, Vals, VE); // ptrty + ptr
1920 pushValue(I.getOperand(1), InstID, Vals, VE); // val.
1921 Vals.push_back(GetEncodedRMWOperation(
1922 cast<AtomicRMWInst>(I).getOperation()));
1923 Vals.push_back(cast<AtomicRMWInst>(I).isVolatile());
1924 Vals.push_back(GetEncodedOrdering(cast<AtomicRMWInst>(I).getOrdering()));
1925 Vals.push_back(GetEncodedSynchScope(
1926 cast<AtomicRMWInst>(I).getSynchScope()));
1928 case Instruction::Fence:
1929 Code = bitc::FUNC_CODE_INST_FENCE;
1930 Vals.push_back(GetEncodedOrdering(cast<FenceInst>(I).getOrdering()));
1931 Vals.push_back(GetEncodedSynchScope(cast<FenceInst>(I).getSynchScope()));
1933 case Instruction::Call: {
1934 const CallInst &CI = cast<CallInst>(I);
1935 PointerType *PTy = cast<PointerType>(CI.getCalledValue()->getType());
1936 FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1938 Code = bitc::FUNC_CODE_INST_CALL;
1940 Vals.push_back(VE.getAttributeID(CI.getAttributes()));
1941 Vals.push_back((CI.getCallingConv() << 1) | unsigned(CI.isTailCall()) |
1942 unsigned(CI.isMustTailCall()) << 14);
1943 PushValueAndType(CI.getCalledValue(), InstID, Vals, VE); // Callee
1945 // Emit value #'s for the fixed parameters.
1946 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
1947 // Check for labels (can happen with asm labels).
1948 if (FTy->getParamType(i)->isLabelTy())
1949 Vals.push_back(VE.getValueID(CI.getArgOperand(i)));
1951 pushValue(CI.getArgOperand(i), InstID, Vals, VE); // fixed param.
1954 // Emit type/value pairs for varargs params.
1955 if (FTy->isVarArg()) {
1956 for (unsigned i = FTy->getNumParams(), e = CI.getNumArgOperands();
1958 PushValueAndType(CI.getArgOperand(i), InstID, Vals, VE); // varargs
1962 case Instruction::VAArg:
1963 Code = bitc::FUNC_CODE_INST_VAARG;
1964 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); // valistty
1965 pushValue(I.getOperand(0), InstID, Vals, VE); // valist.
1966 Vals.push_back(VE.getTypeID(I.getType())); // restype.
1970 Stream.EmitRecord(Code, Vals, AbbrevToUse);
1974 // Emit names for globals/functions etc.
1975 static void WriteValueSymbolTable(const ValueSymbolTable &VST,
1976 const ValueEnumerator &VE,
1977 BitstreamWriter &Stream) {
1978 if (VST.empty()) return;
1979 Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
1981 // FIXME: Set up the abbrev, we know how many values there are!
1982 // FIXME: We know if the type names can use 7-bit ascii.
1983 SmallVector<unsigned, 64> NameVals;
1985 for (ValueSymbolTable::const_iterator SI = VST.begin(), SE = VST.end();
1988 const ValueName &Name = *SI;
1990 // Figure out the encoding to use for the name.
1992 bool isChar6 = true;
1993 for (const char *C = Name.getKeyData(), *E = C+Name.getKeyLength();
1996 isChar6 = BitCodeAbbrevOp::isChar6(*C);
1997 if ((unsigned char)*C & 128) {
1999 break; // don't bother scanning the rest.
2003 unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
2005 // VST_ENTRY: [valueid, namechar x N]
2006 // VST_BBENTRY: [bbid, namechar x N]
2008 if (isa<BasicBlock>(SI->getValue())) {
2009 Code = bitc::VST_CODE_BBENTRY;
2011 AbbrevToUse = VST_BBENTRY_6_ABBREV;
2013 Code = bitc::VST_CODE_ENTRY;
2015 AbbrevToUse = VST_ENTRY_6_ABBREV;
2017 AbbrevToUse = VST_ENTRY_7_ABBREV;
2020 NameVals.push_back(VE.getValueID(SI->getValue()));
2021 for (const char *P = Name.getKeyData(),
2022 *E = Name.getKeyData()+Name.getKeyLength(); P != E; ++P)
2023 NameVals.push_back((unsigned char)*P);
2025 // Emit the finished record.
2026 Stream.EmitRecord(Code, NameVals, AbbrevToUse);
2032 static void WriteUseList(ValueEnumerator &VE, UseListOrder &&Order,
2033 BitstreamWriter &Stream) {
2034 assert(Order.Shuffle.size() >= 2 && "Shuffle too small");
2036 if (isa<BasicBlock>(Order.V))
2037 Code = bitc::USELIST_CODE_BB;
2039 Code = bitc::USELIST_CODE_DEFAULT;
2041 SmallVector<uint64_t, 64> Record(Order.Shuffle.begin(), Order.Shuffle.end());
2042 Record.push_back(VE.getValueID(Order.V));
2043 Stream.EmitRecord(Code, Record);
2046 static void WriteUseListBlock(const Function *F, ValueEnumerator &VE,
2047 BitstreamWriter &Stream) {
2048 auto hasMore = [&]() {
2049 return !VE.UseListOrders.empty() && VE.UseListOrders.back().F == F;
2055 Stream.EnterSubblock(bitc::USELIST_BLOCK_ID, 3);
2057 WriteUseList(VE, std::move(VE.UseListOrders.back()), Stream);
2058 VE.UseListOrders.pop_back();
2063 /// WriteFunction - Emit a function body to the module stream.
2064 static void WriteFunction(const Function &F, ValueEnumerator &VE,
2065 BitstreamWriter &Stream) {
2066 Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 4);
2067 VE.incorporateFunction(F);
2069 SmallVector<unsigned, 64> Vals;
2071 // Emit the number of basic blocks, so the reader can create them ahead of
2073 Vals.push_back(VE.getBasicBlocks().size());
2074 Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals);
2077 // If there are function-local constants, emit them now.
2078 unsigned CstStart, CstEnd;
2079 VE.getFunctionConstantRange(CstStart, CstEnd);
2080 WriteConstants(CstStart, CstEnd, VE, Stream, false);
2082 // If there is function-local metadata, emit it now.
2083 WriteFunctionLocalMetadata(F, VE, Stream);
2085 // Keep a running idea of what the instruction ID is.
2086 unsigned InstID = CstEnd;
2088 bool NeedsMetadataAttachment = false;
2092 // Finally, emit all the instructions, in order.
2093 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
2094 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
2096 WriteInstruction(*I, InstID, VE, Stream, Vals);
2098 if (!I->getType()->isVoidTy())
2101 // If the instruction has metadata, write a metadata attachment later.
2102 NeedsMetadataAttachment |= I->hasMetadataOtherThanDebugLoc();
2104 // If the instruction has a debug location, emit it.
2105 DebugLoc DL = I->getDebugLoc();
2106 if (DL.isUnknown()) {
2108 } else if (DL == LastDL) {
2109 // Just repeat the same debug loc as last time.
2110 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC_AGAIN, Vals);
2113 DL.getScopeAndInlinedAt(Scope, IA, I->getContext());
2114 assert(Scope && "Expected valid scope");
2116 Vals.push_back(DL.getLine());
2117 Vals.push_back(DL.getCol());
2118 Vals.push_back(VE.getMetadataOrNullID(Scope));
2119 Vals.push_back(VE.getMetadataOrNullID(IA));
2120 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC, Vals);
2127 // Emit names for all the instructions etc.
2128 WriteValueSymbolTable(F.getValueSymbolTable(), VE, Stream);
2130 if (NeedsMetadataAttachment)
2131 WriteMetadataAttachment(F, VE, Stream);
2132 if (shouldPreserveBitcodeUseListOrder())
2133 WriteUseListBlock(&F, VE, Stream);
2138 // Emit blockinfo, which defines the standard abbreviations etc.
2139 static void WriteBlockInfo(const ValueEnumerator &VE, BitstreamWriter &Stream) {
2140 // We only want to emit block info records for blocks that have multiple
2141 // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK.
2142 // Other blocks can define their abbrevs inline.
2143 Stream.EnterBlockInfoBlock(2);
2145 { // 8-bit fixed-width VST_ENTRY/VST_BBENTRY strings.
2146 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2147 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3));
2148 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2149 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2150 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
2151 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
2152 Abbv) != VST_ENTRY_8_ABBREV)
2153 llvm_unreachable("Unexpected abbrev ordering!");
2156 { // 7-bit fixed width VST_ENTRY strings.
2157 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2158 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
2159 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2160 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2161 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
2162 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
2163 Abbv) != VST_ENTRY_7_ABBREV)
2164 llvm_unreachable("Unexpected abbrev ordering!");
2166 { // 6-bit char6 VST_ENTRY strings.
2167 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2168 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
2169 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2170 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2171 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
2172 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
2173 Abbv) != VST_ENTRY_6_ABBREV)
2174 llvm_unreachable("Unexpected abbrev ordering!");
2176 { // 6-bit char6 VST_BBENTRY strings.
2177 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2178 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY));
2179 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2180 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2181 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
2182 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
2183 Abbv) != VST_BBENTRY_6_ABBREV)
2184 llvm_unreachable("Unexpected abbrev ordering!");
2189 { // SETTYPE abbrev for CONSTANTS_BLOCK.
2190 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2191 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_SETTYPE));
2192 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
2193 VE.computeBitsRequiredForTypeIndicies()));
2194 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
2195 Abbv) != CONSTANTS_SETTYPE_ABBREV)
2196 llvm_unreachable("Unexpected abbrev ordering!");
2199 { // INTEGER abbrev for CONSTANTS_BLOCK.
2200 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2201 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_INTEGER));
2202 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2203 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
2204 Abbv) != CONSTANTS_INTEGER_ABBREV)
2205 llvm_unreachable("Unexpected abbrev ordering!");
2208 { // CE_CAST abbrev for CONSTANTS_BLOCK.
2209 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2210 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CE_CAST));
2211 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // cast opc
2212 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // typeid
2213 VE.computeBitsRequiredForTypeIndicies()));
2214 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
2216 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
2217 Abbv) != CONSTANTS_CE_CAST_Abbrev)
2218 llvm_unreachable("Unexpected abbrev ordering!");
2220 { // NULL abbrev for CONSTANTS_BLOCK.
2221 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2222 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_NULL));
2223 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
2224 Abbv) != CONSTANTS_NULL_Abbrev)
2225 llvm_unreachable("Unexpected abbrev ordering!");
2228 // FIXME: This should only use space for first class types!
2230 { // INST_LOAD abbrev for FUNCTION_BLOCK.
2231 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2232 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_LOAD));
2233 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Ptr
2234 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
2235 VE.computeBitsRequiredForTypeIndicies()));
2236 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align
2237 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile
2238 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
2239 Abbv) != FUNCTION_INST_LOAD_ABBREV)
2240 llvm_unreachable("Unexpected abbrev ordering!");
2242 { // INST_BINOP abbrev for FUNCTION_BLOCK.
2243 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2244 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
2245 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
2246 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
2247 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
2248 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
2249 Abbv) != FUNCTION_INST_BINOP_ABBREV)
2250 llvm_unreachable("Unexpected abbrev ordering!");
2252 { // INST_BINOP_FLAGS abbrev for FUNCTION_BLOCK.
2253 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2254 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
2255 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
2256 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
2257 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
2258 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7)); // flags
2259 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
2260 Abbv) != FUNCTION_INST_BINOP_FLAGS_ABBREV)
2261 llvm_unreachable("Unexpected abbrev ordering!");
2263 { // INST_CAST abbrev for FUNCTION_BLOCK.
2264 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2265 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST));
2266 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // OpVal
2267 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
2268 VE.computeBitsRequiredForTypeIndicies()));
2269 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
2270 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
2271 Abbv) != FUNCTION_INST_CAST_ABBREV)
2272 llvm_unreachable("Unexpected abbrev ordering!");
2275 { // INST_RET abbrev for FUNCTION_BLOCK.
2276 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2277 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
2278 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
2279 Abbv) != FUNCTION_INST_RET_VOID_ABBREV)
2280 llvm_unreachable("Unexpected abbrev ordering!");
2282 { // INST_RET abbrev for FUNCTION_BLOCK.
2283 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2284 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
2285 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ValID
2286 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
2287 Abbv) != FUNCTION_INST_RET_VAL_ABBREV)
2288 llvm_unreachable("Unexpected abbrev ordering!");
2290 { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK.
2291 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2292 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNREACHABLE));
2293 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
2294 Abbv) != FUNCTION_INST_UNREACHABLE_ABBREV)
2295 llvm_unreachable("Unexpected abbrev ordering!");
2298 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2299 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_GEP));
2300 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
2301 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
2302 Log2_32_Ceil(VE.getTypes().size() + 1)));
2303 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2304 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
2305 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
2306 FUNCTION_INST_GEP_ABBREV)
2307 llvm_unreachable("Unexpected abbrev ordering!");
2313 /// WriteModule - Emit the specified module to the bitstream.
2314 static void WriteModule(const Module *M, BitstreamWriter &Stream) {
2315 Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
2317 SmallVector<unsigned, 1> Vals;
2318 unsigned CurVersion = 1;
2319 Vals.push_back(CurVersion);
2320 Stream.EmitRecord(bitc::MODULE_CODE_VERSION, Vals);
2322 // Analyze the module, enumerating globals, functions, etc.
2323 ValueEnumerator VE(*M);
2325 // Emit blockinfo, which defines the standard abbreviations etc.
2326 WriteBlockInfo(VE, Stream);
2328 // Emit information about attribute groups.
2329 WriteAttributeGroupTable(VE, Stream);
2331 // Emit information about parameter attributes.
2332 WriteAttributeTable(VE, Stream);
2334 // Emit information describing all of the types in the module.
2335 WriteTypeTable(VE, Stream);
2337 writeComdats(VE, Stream);
2339 // Emit top-level description of module, including target triple, inline asm,
2340 // descriptors for global variables, and function prototype info.
2341 WriteModuleInfo(M, VE, Stream);
2344 WriteModuleConstants(VE, Stream);
2347 WriteModuleMetadata(M, VE, Stream);
2350 WriteModuleMetadataStore(M, Stream);
2352 // Emit names for globals/functions etc.
2353 WriteValueSymbolTable(M->getValueSymbolTable(), VE, Stream);
2355 // Emit module-level use-lists.
2356 if (shouldPreserveBitcodeUseListOrder())
2357 WriteUseListBlock(nullptr, VE, Stream);
2359 // Emit function bodies.
2360 for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F)
2361 if (!F->isDeclaration())
2362 WriteFunction(*F, VE, Stream);
2367 /// EmitDarwinBCHeader - If generating a bc file on darwin, we have to emit a
2368 /// header and trailer to make it compatible with the system archiver. To do
2369 /// this we emit the following header, and then emit a trailer that pads the
2370 /// file out to be a multiple of 16 bytes.
2372 /// struct bc_header {
2373 /// uint32_t Magic; // 0x0B17C0DE
2374 /// uint32_t Version; // Version, currently always 0.
2375 /// uint32_t BitcodeOffset; // Offset to traditional bitcode file.
2376 /// uint32_t BitcodeSize; // Size of traditional bitcode file.
2377 /// uint32_t CPUType; // CPU specifier.
2378 /// ... potentially more later ...
2381 DarwinBCSizeFieldOffset = 3*4, // Offset to bitcode_size.
2382 DarwinBCHeaderSize = 5*4
2385 static void WriteInt32ToBuffer(uint32_t Value, SmallVectorImpl<char> &Buffer,
2386 uint32_t &Position) {
2387 Buffer[Position + 0] = (unsigned char) (Value >> 0);
2388 Buffer[Position + 1] = (unsigned char) (Value >> 8);
2389 Buffer[Position + 2] = (unsigned char) (Value >> 16);
2390 Buffer[Position + 3] = (unsigned char) (Value >> 24);
2394 static void EmitDarwinBCHeaderAndTrailer(SmallVectorImpl<char> &Buffer,
2396 unsigned CPUType = ~0U;
2398 // Match x86_64-*, i[3-9]86-*, powerpc-*, powerpc64-*, arm-*, thumb-*,
2399 // armv[0-9]-*, thumbv[0-9]-*, armv5te-*, or armv6t2-*. The CPUType is a magic
2400 // number from /usr/include/mach/machine.h. It is ok to reproduce the
2401 // specific constants here because they are implicitly part of the Darwin ABI.
2403 DARWIN_CPU_ARCH_ABI64 = 0x01000000,
2404 DARWIN_CPU_TYPE_X86 = 7,
2405 DARWIN_CPU_TYPE_ARM = 12,
2406 DARWIN_CPU_TYPE_POWERPC = 18
2409 Triple::ArchType Arch = TT.getArch();
2410 if (Arch == Triple::x86_64)
2411 CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64;
2412 else if (Arch == Triple::x86)
2413 CPUType = DARWIN_CPU_TYPE_X86;
2414 else if (Arch == Triple::ppc)
2415 CPUType = DARWIN_CPU_TYPE_POWERPC;
2416 else if (Arch == Triple::ppc64)
2417 CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64;
2418 else if (Arch == Triple::arm || Arch == Triple::thumb)
2419 CPUType = DARWIN_CPU_TYPE_ARM;
2421 // Traditional Bitcode starts after header.
2422 assert(Buffer.size() >= DarwinBCHeaderSize &&
2423 "Expected header size to be reserved");
2424 unsigned BCOffset = DarwinBCHeaderSize;
2425 unsigned BCSize = Buffer.size()-DarwinBCHeaderSize;
2427 // Write the magic and version.
2428 unsigned Position = 0;
2429 WriteInt32ToBuffer(0x0B17C0DE , Buffer, Position);
2430 WriteInt32ToBuffer(0 , Buffer, Position); // Version.
2431 WriteInt32ToBuffer(BCOffset , Buffer, Position);
2432 WriteInt32ToBuffer(BCSize , Buffer, Position);
2433 WriteInt32ToBuffer(CPUType , Buffer, Position);
2435 // If the file is not a multiple of 16 bytes, insert dummy padding.
2436 while (Buffer.size() & 15)
2437 Buffer.push_back(0);
2440 /// WriteBitcodeToFile - Write the specified module to the specified output
2442 void llvm::WriteBitcodeToFile(const Module *M, raw_ostream &Out) {
2443 SmallVector<char, 0> Buffer;
2444 Buffer.reserve(256*1024);
2446 // If this is darwin or another generic macho target, reserve space for the
2448 Triple TT(M->getTargetTriple());
2449 if (TT.isOSDarwin())
2450 Buffer.insert(Buffer.begin(), DarwinBCHeaderSize, 0);
2452 // Emit the module into the buffer.
2454 BitstreamWriter Stream(Buffer);
2456 // Emit the file header.
2457 Stream.Emit((unsigned)'B', 8);
2458 Stream.Emit((unsigned)'C', 8);
2459 Stream.Emit(0x0, 4);
2460 Stream.Emit(0xC, 4);
2461 Stream.Emit(0xE, 4);
2462 Stream.Emit(0xD, 4);
2465 WriteModule(M, Stream);
2468 if (TT.isOSDarwin())
2469 EmitDarwinBCHeaderAndTrailer(Buffer, TT);
2471 // Write the generated bitstream to "Out".
2472 Out.write((char*)&Buffer.front(), Buffer.size());