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/CallSite.h"
20 #include "llvm/IR/Constants.h"
21 #include "llvm/IR/DebugInfoMetadata.h"
22 #include "llvm/IR/DerivedTypes.h"
23 #include "llvm/IR/InlineAsm.h"
24 #include "llvm/IR/Instructions.h"
25 #include "llvm/IR/LLVMContext.h"
26 #include "llvm/IR/Module.h"
27 #include "llvm/IR/Operator.h"
28 #include "llvm/IR/UseListOrder.h"
29 #include "llvm/IR/ValueSymbolTable.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/ErrorHandling.h"
32 #include "llvm/Support/MathExtras.h"
33 #include "llvm/Support/Program.h"
34 #include "llvm/Support/raw_ostream.h"
39 /// These are manifest constants used by the bitcode writer. They do not need to
40 /// be kept in sync with the reader, but need to be consistent within this file.
42 // VALUE_SYMTAB_BLOCK abbrev id's.
43 VST_ENTRY_8_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
48 // CONSTANTS_BLOCK abbrev id's.
49 CONSTANTS_SETTYPE_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
50 CONSTANTS_INTEGER_ABBREV,
51 CONSTANTS_CE_CAST_Abbrev,
52 CONSTANTS_NULL_Abbrev,
54 // FUNCTION_BLOCK abbrev id's.
55 FUNCTION_INST_LOAD_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
56 FUNCTION_INST_BINOP_ABBREV,
57 FUNCTION_INST_BINOP_FLAGS_ABBREV,
58 FUNCTION_INST_CAST_ABBREV,
59 FUNCTION_INST_RET_VOID_ABBREV,
60 FUNCTION_INST_RET_VAL_ABBREV,
61 FUNCTION_INST_UNREACHABLE_ABBREV,
62 FUNCTION_INST_GEP_ABBREV,
65 static unsigned GetEncodedCastOpcode(unsigned Opcode) {
67 default: llvm_unreachable("Unknown cast instruction!");
68 case Instruction::Trunc : return bitc::CAST_TRUNC;
69 case Instruction::ZExt : return bitc::CAST_ZEXT;
70 case Instruction::SExt : return bitc::CAST_SEXT;
71 case Instruction::FPToUI : return bitc::CAST_FPTOUI;
72 case Instruction::FPToSI : return bitc::CAST_FPTOSI;
73 case Instruction::UIToFP : return bitc::CAST_UITOFP;
74 case Instruction::SIToFP : return bitc::CAST_SITOFP;
75 case Instruction::FPTrunc : return bitc::CAST_FPTRUNC;
76 case Instruction::FPExt : return bitc::CAST_FPEXT;
77 case Instruction::PtrToInt: return bitc::CAST_PTRTOINT;
78 case Instruction::IntToPtr: return bitc::CAST_INTTOPTR;
79 case Instruction::BitCast : return bitc::CAST_BITCAST;
80 case Instruction::AddrSpaceCast: return bitc::CAST_ADDRSPACECAST;
84 static unsigned GetEncodedBinaryOpcode(unsigned Opcode) {
86 default: llvm_unreachable("Unknown binary instruction!");
87 case Instruction::Add:
88 case Instruction::FAdd: return bitc::BINOP_ADD;
89 case Instruction::Sub:
90 case Instruction::FSub: return bitc::BINOP_SUB;
91 case Instruction::Mul:
92 case Instruction::FMul: return bitc::BINOP_MUL;
93 case Instruction::UDiv: return bitc::BINOP_UDIV;
94 case Instruction::FDiv:
95 case Instruction::SDiv: return bitc::BINOP_SDIV;
96 case Instruction::URem: return bitc::BINOP_UREM;
97 case Instruction::FRem:
98 case Instruction::SRem: return bitc::BINOP_SREM;
99 case Instruction::Shl: return bitc::BINOP_SHL;
100 case Instruction::LShr: return bitc::BINOP_LSHR;
101 case Instruction::AShr: return bitc::BINOP_ASHR;
102 case Instruction::And: return bitc::BINOP_AND;
103 case Instruction::Or: return bitc::BINOP_OR;
104 case Instruction::Xor: return bitc::BINOP_XOR;
108 static unsigned GetEncodedRMWOperation(AtomicRMWInst::BinOp Op) {
110 default: llvm_unreachable("Unknown RMW operation!");
111 case AtomicRMWInst::Xchg: return bitc::RMW_XCHG;
112 case AtomicRMWInst::Add: return bitc::RMW_ADD;
113 case AtomicRMWInst::Sub: return bitc::RMW_SUB;
114 case AtomicRMWInst::And: return bitc::RMW_AND;
115 case AtomicRMWInst::Nand: return bitc::RMW_NAND;
116 case AtomicRMWInst::Or: return bitc::RMW_OR;
117 case AtomicRMWInst::Xor: return bitc::RMW_XOR;
118 case AtomicRMWInst::Max: return bitc::RMW_MAX;
119 case AtomicRMWInst::Min: return bitc::RMW_MIN;
120 case AtomicRMWInst::UMax: return bitc::RMW_UMAX;
121 case AtomicRMWInst::UMin: return bitc::RMW_UMIN;
125 static unsigned GetEncodedOrdering(AtomicOrdering Ordering) {
127 case NotAtomic: return bitc::ORDERING_NOTATOMIC;
128 case Unordered: return bitc::ORDERING_UNORDERED;
129 case Monotonic: return bitc::ORDERING_MONOTONIC;
130 case Acquire: return bitc::ORDERING_ACQUIRE;
131 case Release: return bitc::ORDERING_RELEASE;
132 case AcquireRelease: return bitc::ORDERING_ACQREL;
133 case SequentiallyConsistent: return bitc::ORDERING_SEQCST;
135 llvm_unreachable("Invalid ordering");
138 static unsigned GetEncodedSynchScope(SynchronizationScope SynchScope) {
139 switch (SynchScope) {
140 case SingleThread: return bitc::SYNCHSCOPE_SINGLETHREAD;
141 case CrossThread: return bitc::SYNCHSCOPE_CROSSTHREAD;
143 llvm_unreachable("Invalid synch scope");
146 static void WriteStringRecord(unsigned Code, StringRef Str,
147 unsigned AbbrevToUse, BitstreamWriter &Stream) {
148 SmallVector<unsigned, 64> Vals;
150 // Code: [strchar x N]
151 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
152 if (AbbrevToUse && !BitCodeAbbrevOp::isChar6(Str[i]))
154 Vals.push_back(Str[i]);
157 // Emit the finished record.
158 Stream.EmitRecord(Code, Vals, AbbrevToUse);
161 static uint64_t getAttrKindEncoding(Attribute::AttrKind Kind) {
163 case Attribute::Alignment:
164 return bitc::ATTR_KIND_ALIGNMENT;
165 case Attribute::AlwaysInline:
166 return bitc::ATTR_KIND_ALWAYS_INLINE;
167 case Attribute::ArgMemOnly:
168 return bitc::ATTR_KIND_ARGMEMONLY;
169 case Attribute::Builtin:
170 return bitc::ATTR_KIND_BUILTIN;
171 case Attribute::ByVal:
172 return bitc::ATTR_KIND_BY_VAL;
173 case Attribute::Convergent:
174 return bitc::ATTR_KIND_CONVERGENT;
175 case Attribute::InAlloca:
176 return bitc::ATTR_KIND_IN_ALLOCA;
177 case Attribute::Cold:
178 return bitc::ATTR_KIND_COLD;
179 case Attribute::InlineHint:
180 return bitc::ATTR_KIND_INLINE_HINT;
181 case Attribute::InReg:
182 return bitc::ATTR_KIND_IN_REG;
183 case Attribute::JumpTable:
184 return bitc::ATTR_KIND_JUMP_TABLE;
185 case Attribute::MinSize:
186 return bitc::ATTR_KIND_MIN_SIZE;
187 case Attribute::Naked:
188 return bitc::ATTR_KIND_NAKED;
189 case Attribute::Nest:
190 return bitc::ATTR_KIND_NEST;
191 case Attribute::NoAlias:
192 return bitc::ATTR_KIND_NO_ALIAS;
193 case Attribute::NoBuiltin:
194 return bitc::ATTR_KIND_NO_BUILTIN;
195 case Attribute::NoCapture:
196 return bitc::ATTR_KIND_NO_CAPTURE;
197 case Attribute::NoDuplicate:
198 return bitc::ATTR_KIND_NO_DUPLICATE;
199 case Attribute::NoImplicitFloat:
200 return bitc::ATTR_KIND_NO_IMPLICIT_FLOAT;
201 case Attribute::NoInline:
202 return bitc::ATTR_KIND_NO_INLINE;
203 case Attribute::NonLazyBind:
204 return bitc::ATTR_KIND_NON_LAZY_BIND;
205 case Attribute::NonNull:
206 return bitc::ATTR_KIND_NON_NULL;
207 case Attribute::Dereferenceable:
208 return bitc::ATTR_KIND_DEREFERENCEABLE;
209 case Attribute::DereferenceableOrNull:
210 return bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL;
211 case Attribute::NoRedZone:
212 return bitc::ATTR_KIND_NO_RED_ZONE;
213 case Attribute::NoReturn:
214 return bitc::ATTR_KIND_NO_RETURN;
215 case Attribute::NoUnwind:
216 return bitc::ATTR_KIND_NO_UNWIND;
217 case Attribute::OptimizeForSize:
218 return bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE;
219 case Attribute::OptimizeNone:
220 return bitc::ATTR_KIND_OPTIMIZE_NONE;
221 case Attribute::ReadNone:
222 return bitc::ATTR_KIND_READ_NONE;
223 case Attribute::ReadOnly:
224 return bitc::ATTR_KIND_READ_ONLY;
225 case Attribute::Returned:
226 return bitc::ATTR_KIND_RETURNED;
227 case Attribute::ReturnsTwice:
228 return bitc::ATTR_KIND_RETURNS_TWICE;
229 case Attribute::SExt:
230 return bitc::ATTR_KIND_S_EXT;
231 case Attribute::StackAlignment:
232 return bitc::ATTR_KIND_STACK_ALIGNMENT;
233 case Attribute::StackProtect:
234 return bitc::ATTR_KIND_STACK_PROTECT;
235 case Attribute::StackProtectReq:
236 return bitc::ATTR_KIND_STACK_PROTECT_REQ;
237 case Attribute::StackProtectStrong:
238 return bitc::ATTR_KIND_STACK_PROTECT_STRONG;
239 case Attribute::SafeStack:
240 return bitc::ATTR_KIND_SAFESTACK;
241 case Attribute::StructRet:
242 return bitc::ATTR_KIND_STRUCT_RET;
243 case Attribute::SanitizeAddress:
244 return bitc::ATTR_KIND_SANITIZE_ADDRESS;
245 case Attribute::SanitizeThread:
246 return bitc::ATTR_KIND_SANITIZE_THREAD;
247 case Attribute::SanitizeMemory:
248 return bitc::ATTR_KIND_SANITIZE_MEMORY;
249 case Attribute::UWTable:
250 return bitc::ATTR_KIND_UW_TABLE;
251 case Attribute::ZExt:
252 return bitc::ATTR_KIND_Z_EXT;
253 case Attribute::EndAttrKinds:
254 llvm_unreachable("Can not encode end-attribute kinds marker.");
255 case Attribute::None:
256 llvm_unreachable("Can not encode none-attribute.");
259 llvm_unreachable("Trying to encode unknown attribute");
262 static void WriteAttributeGroupTable(const ValueEnumerator &VE,
263 BitstreamWriter &Stream) {
264 const std::vector<AttributeSet> &AttrGrps = VE.getAttributeGroups();
265 if (AttrGrps.empty()) return;
267 Stream.EnterSubblock(bitc::PARAMATTR_GROUP_BLOCK_ID, 3);
269 SmallVector<uint64_t, 64> Record;
270 for (unsigned i = 0, e = AttrGrps.size(); i != e; ++i) {
271 AttributeSet AS = AttrGrps[i];
272 for (unsigned i = 0, e = AS.getNumSlots(); i != e; ++i) {
273 AttributeSet A = AS.getSlotAttributes(i);
275 Record.push_back(VE.getAttributeGroupID(A));
276 Record.push_back(AS.getSlotIndex(i));
278 for (AttributeSet::iterator I = AS.begin(0), E = AS.end(0);
281 if (Attr.isEnumAttribute()) {
283 Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
284 } else if (Attr.isIntAttribute()) {
286 Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
287 Record.push_back(Attr.getValueAsInt());
289 StringRef Kind = Attr.getKindAsString();
290 StringRef Val = Attr.getValueAsString();
292 Record.push_back(Val.empty() ? 3 : 4);
293 Record.append(Kind.begin(), Kind.end());
296 Record.append(Val.begin(), Val.end());
302 Stream.EmitRecord(bitc::PARAMATTR_GRP_CODE_ENTRY, Record);
310 static void WriteAttributeTable(const ValueEnumerator &VE,
311 BitstreamWriter &Stream) {
312 const std::vector<AttributeSet> &Attrs = VE.getAttributes();
313 if (Attrs.empty()) return;
315 Stream.EnterSubblock(bitc::PARAMATTR_BLOCK_ID, 3);
317 SmallVector<uint64_t, 64> Record;
318 for (unsigned i = 0, e = Attrs.size(); i != e; ++i) {
319 const AttributeSet &A = Attrs[i];
320 for (unsigned i = 0, e = A.getNumSlots(); i != e; ++i)
321 Record.push_back(VE.getAttributeGroupID(A.getSlotAttributes(i)));
323 Stream.EmitRecord(bitc::PARAMATTR_CODE_ENTRY, Record);
330 /// WriteTypeTable - Write out the type table for a module.
331 static void WriteTypeTable(const ValueEnumerator &VE, BitstreamWriter &Stream) {
332 const ValueEnumerator::TypeList &TypeList = VE.getTypes();
334 Stream.EnterSubblock(bitc::TYPE_BLOCK_ID_NEW, 4 /*count from # abbrevs */);
335 SmallVector<uint64_t, 64> TypeVals;
337 uint64_t NumBits = VE.computeBitsRequiredForTypeIndicies();
339 // Abbrev for TYPE_CODE_POINTER.
340 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
341 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_POINTER));
342 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
343 Abbv->Add(BitCodeAbbrevOp(0)); // Addrspace = 0
344 unsigned PtrAbbrev = Stream.EmitAbbrev(Abbv);
346 // Abbrev for TYPE_CODE_FUNCTION.
347 Abbv = new BitCodeAbbrev();
348 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_FUNCTION));
349 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // isvararg
350 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
351 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
353 unsigned FunctionAbbrev = Stream.EmitAbbrev(Abbv);
355 // Abbrev for TYPE_CODE_STRUCT_ANON.
356 Abbv = new BitCodeAbbrev();
357 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_ANON));
358 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
359 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
360 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
362 unsigned StructAnonAbbrev = Stream.EmitAbbrev(Abbv);
364 // Abbrev for TYPE_CODE_STRUCT_NAME.
365 Abbv = new BitCodeAbbrev();
366 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAME));
367 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
368 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
369 unsigned StructNameAbbrev = Stream.EmitAbbrev(Abbv);
371 // Abbrev for TYPE_CODE_STRUCT_NAMED.
372 Abbv = new BitCodeAbbrev();
373 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAMED));
374 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
375 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
376 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
378 unsigned StructNamedAbbrev = Stream.EmitAbbrev(Abbv);
380 // Abbrev for TYPE_CODE_ARRAY.
381 Abbv = new BitCodeAbbrev();
382 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_ARRAY));
383 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // size
384 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
386 unsigned ArrayAbbrev = Stream.EmitAbbrev(Abbv);
388 // Emit an entry count so the reader can reserve space.
389 TypeVals.push_back(TypeList.size());
390 Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals);
393 // Loop over all of the types, emitting each in turn.
394 for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
395 Type *T = TypeList[i];
399 switch (T->getTypeID()) {
400 case Type::VoidTyID: Code = bitc::TYPE_CODE_VOID; break;
401 case Type::HalfTyID: Code = bitc::TYPE_CODE_HALF; break;
402 case Type::FloatTyID: Code = bitc::TYPE_CODE_FLOAT; break;
403 case Type::DoubleTyID: Code = bitc::TYPE_CODE_DOUBLE; break;
404 case Type::X86_FP80TyID: Code = bitc::TYPE_CODE_X86_FP80; break;
405 case Type::FP128TyID: Code = bitc::TYPE_CODE_FP128; break;
406 case Type::PPC_FP128TyID: Code = bitc::TYPE_CODE_PPC_FP128; break;
407 case Type::LabelTyID: Code = bitc::TYPE_CODE_LABEL; break;
408 case Type::MetadataTyID: Code = bitc::TYPE_CODE_METADATA; break;
409 case Type::X86_MMXTyID: Code = bitc::TYPE_CODE_X86_MMX; break;
410 case Type::TokenTyID: Code = bitc::TYPE_CODE_TOKEN; break;
411 case Type::IntegerTyID:
413 Code = bitc::TYPE_CODE_INTEGER;
414 TypeVals.push_back(cast<IntegerType>(T)->getBitWidth());
416 case Type::PointerTyID: {
417 PointerType *PTy = cast<PointerType>(T);
418 // POINTER: [pointee type, address space]
419 Code = bitc::TYPE_CODE_POINTER;
420 TypeVals.push_back(VE.getTypeID(PTy->getElementType()));
421 unsigned AddressSpace = PTy->getAddressSpace();
422 TypeVals.push_back(AddressSpace);
423 if (AddressSpace == 0) AbbrevToUse = PtrAbbrev;
426 case Type::FunctionTyID: {
427 FunctionType *FT = cast<FunctionType>(T);
428 // FUNCTION: [isvararg, retty, paramty x N]
429 Code = bitc::TYPE_CODE_FUNCTION;
430 TypeVals.push_back(FT->isVarArg());
431 TypeVals.push_back(VE.getTypeID(FT->getReturnType()));
432 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
433 TypeVals.push_back(VE.getTypeID(FT->getParamType(i)));
434 AbbrevToUse = FunctionAbbrev;
437 case Type::StructTyID: {
438 StructType *ST = cast<StructType>(T);
439 // STRUCT: [ispacked, eltty x N]
440 TypeVals.push_back(ST->isPacked());
441 // Output all of the element types.
442 for (StructType::element_iterator I = ST->element_begin(),
443 E = ST->element_end(); I != E; ++I)
444 TypeVals.push_back(VE.getTypeID(*I));
446 if (ST->isLiteral()) {
447 Code = bitc::TYPE_CODE_STRUCT_ANON;
448 AbbrevToUse = StructAnonAbbrev;
450 if (ST->isOpaque()) {
451 Code = bitc::TYPE_CODE_OPAQUE;
453 Code = bitc::TYPE_CODE_STRUCT_NAMED;
454 AbbrevToUse = StructNamedAbbrev;
457 // Emit the name if it is present.
458 if (!ST->getName().empty())
459 WriteStringRecord(bitc::TYPE_CODE_STRUCT_NAME, ST->getName(),
460 StructNameAbbrev, Stream);
464 case Type::ArrayTyID: {
465 ArrayType *AT = cast<ArrayType>(T);
466 // ARRAY: [numelts, eltty]
467 Code = bitc::TYPE_CODE_ARRAY;
468 TypeVals.push_back(AT->getNumElements());
469 TypeVals.push_back(VE.getTypeID(AT->getElementType()));
470 AbbrevToUse = ArrayAbbrev;
473 case Type::VectorTyID: {
474 VectorType *VT = cast<VectorType>(T);
475 // VECTOR [numelts, eltty]
476 Code = bitc::TYPE_CODE_VECTOR;
477 TypeVals.push_back(VT->getNumElements());
478 TypeVals.push_back(VE.getTypeID(VT->getElementType()));
483 // Emit the finished record.
484 Stream.EmitRecord(Code, TypeVals, AbbrevToUse);
491 static unsigned getEncodedLinkage(const GlobalValue &GV) {
492 switch (GV.getLinkage()) {
493 case GlobalValue::ExternalLinkage:
495 case GlobalValue::WeakAnyLinkage:
497 case GlobalValue::AppendingLinkage:
499 case GlobalValue::InternalLinkage:
501 case GlobalValue::LinkOnceAnyLinkage:
503 case GlobalValue::ExternalWeakLinkage:
505 case GlobalValue::CommonLinkage:
507 case GlobalValue::PrivateLinkage:
509 case GlobalValue::WeakODRLinkage:
511 case GlobalValue::LinkOnceODRLinkage:
513 case GlobalValue::AvailableExternallyLinkage:
516 llvm_unreachable("Invalid linkage");
519 static unsigned getEncodedVisibility(const GlobalValue &GV) {
520 switch (GV.getVisibility()) {
521 case GlobalValue::DefaultVisibility: return 0;
522 case GlobalValue::HiddenVisibility: return 1;
523 case GlobalValue::ProtectedVisibility: return 2;
525 llvm_unreachable("Invalid visibility");
528 static unsigned getEncodedDLLStorageClass(const GlobalValue &GV) {
529 switch (GV.getDLLStorageClass()) {
530 case GlobalValue::DefaultStorageClass: return 0;
531 case GlobalValue::DLLImportStorageClass: return 1;
532 case GlobalValue::DLLExportStorageClass: return 2;
534 llvm_unreachable("Invalid DLL storage class");
537 static unsigned getEncodedThreadLocalMode(const GlobalValue &GV) {
538 switch (GV.getThreadLocalMode()) {
539 case GlobalVariable::NotThreadLocal: return 0;
540 case GlobalVariable::GeneralDynamicTLSModel: return 1;
541 case GlobalVariable::LocalDynamicTLSModel: return 2;
542 case GlobalVariable::InitialExecTLSModel: return 3;
543 case GlobalVariable::LocalExecTLSModel: return 4;
545 llvm_unreachable("Invalid TLS model");
548 static unsigned getEncodedComdatSelectionKind(const Comdat &C) {
549 switch (C.getSelectionKind()) {
551 return bitc::COMDAT_SELECTION_KIND_ANY;
552 case Comdat::ExactMatch:
553 return bitc::COMDAT_SELECTION_KIND_EXACT_MATCH;
554 case Comdat::Largest:
555 return bitc::COMDAT_SELECTION_KIND_LARGEST;
556 case Comdat::NoDuplicates:
557 return bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES;
558 case Comdat::SameSize:
559 return bitc::COMDAT_SELECTION_KIND_SAME_SIZE;
561 llvm_unreachable("Invalid selection kind");
564 static void writeComdats(const ValueEnumerator &VE, BitstreamWriter &Stream) {
565 SmallVector<uint16_t, 64> Vals;
566 for (const Comdat *C : VE.getComdats()) {
567 // COMDAT: [selection_kind, name]
568 Vals.push_back(getEncodedComdatSelectionKind(*C));
569 size_t Size = C->getName().size();
570 assert(isUInt<16>(Size));
571 Vals.push_back(Size);
572 for (char Chr : C->getName())
573 Vals.push_back((unsigned char)Chr);
574 Stream.EmitRecord(bitc::MODULE_CODE_COMDAT, Vals, /*AbbrevToUse=*/0);
579 /// Write a record that will eventually hold the word offset of the
580 /// module-level VST. For now the offset is 0, which will be backpatched
581 /// after the real VST is written. Returns the bit offset to backpatch.
582 static uint64_t WriteValueSymbolTableForwardDecl(const ValueSymbolTable &VST,
583 BitstreamWriter &Stream) {
584 if (VST.empty()) return 0;
586 // Write a placeholder value in for the offset of the real VST,
587 // which is written after the function blocks so that it can include
588 // the offset of each function. The placeholder offset will be
589 // updated when the real VST is written.
590 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
591 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_VSTOFFSET));
592 // Blocks are 32-bit aligned, so we can use a 32-bit word offset to
593 // hold the real VST offset. Must use fixed instead of VBR as we don't
594 // know how many VBR chunks to reserve ahead of time.
595 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
596 unsigned VSTOffsetAbbrev = Stream.EmitAbbrev(Abbv);
598 // Emit the placeholder
599 uint64_t Vals[] = {bitc::MODULE_CODE_VSTOFFSET, 0};
600 Stream.EmitRecordWithAbbrev(VSTOffsetAbbrev, Vals);
602 // Compute and return the bit offset to the placeholder, which will be
603 // patched when the real VST is written. We can simply subtract the 32-bit
604 // fixed size from the current bit number to get the location to backpatch.
605 return Stream.GetCurrentBitNo() - 32;
608 /// Emit top-level description of module, including target triple, inline asm,
609 /// descriptors for global variables, and function prototype info.
610 /// Returns the bit offset to backpatch with the location of the real VST.
611 static uint64_t WriteModuleInfo(const Module *M, const ValueEnumerator &VE,
612 BitstreamWriter &Stream) {
613 // Emit various pieces of data attached to a module.
614 if (!M->getTargetTriple().empty())
615 WriteStringRecord(bitc::MODULE_CODE_TRIPLE, M->getTargetTriple(),
617 const std::string &DL = M->getDataLayoutStr();
619 WriteStringRecord(bitc::MODULE_CODE_DATALAYOUT, DL, 0 /*TODO*/, Stream);
620 if (!M->getModuleInlineAsm().empty())
621 WriteStringRecord(bitc::MODULE_CODE_ASM, M->getModuleInlineAsm(),
624 // Emit information about sections and GC, computing how many there are. Also
625 // compute the maximum alignment value.
626 std::map<std::string, unsigned> SectionMap;
627 std::map<std::string, unsigned> GCMap;
628 unsigned MaxAlignment = 0;
629 unsigned MaxGlobalType = 0;
630 for (const GlobalValue &GV : M->globals()) {
631 MaxAlignment = std::max(MaxAlignment, GV.getAlignment());
632 MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV.getValueType()));
633 if (GV.hasSection()) {
634 // Give section names unique ID's.
635 unsigned &Entry = SectionMap[GV.getSection()];
637 WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, GV.getSection(),
639 Entry = SectionMap.size();
643 for (const Function &F : *M) {
644 MaxAlignment = std::max(MaxAlignment, F.getAlignment());
645 if (F.hasSection()) {
646 // Give section names unique ID's.
647 unsigned &Entry = SectionMap[F.getSection()];
649 WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, F.getSection(),
651 Entry = SectionMap.size();
655 // Same for GC names.
656 unsigned &Entry = GCMap[F.getGC()];
658 WriteStringRecord(bitc::MODULE_CODE_GCNAME, F.getGC(),
660 Entry = GCMap.size();
665 // Emit abbrev for globals, now that we know # sections and max alignment.
666 unsigned SimpleGVarAbbrev = 0;
667 if (!M->global_empty()) {
668 // Add an abbrev for common globals with no visibility or thread localness.
669 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
670 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GLOBALVAR));
671 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
672 Log2_32_Ceil(MaxGlobalType+1)));
673 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // AddrSpace << 2
674 //| explicitType << 1
676 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Initializer.
677 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5)); // Linkage.
678 if (MaxAlignment == 0) // Alignment.
679 Abbv->Add(BitCodeAbbrevOp(0));
681 unsigned MaxEncAlignment = Log2_32(MaxAlignment)+1;
682 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
683 Log2_32_Ceil(MaxEncAlignment+1)));
685 if (SectionMap.empty()) // Section.
686 Abbv->Add(BitCodeAbbrevOp(0));
688 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
689 Log2_32_Ceil(SectionMap.size()+1)));
690 // Don't bother emitting vis + thread local.
691 SimpleGVarAbbrev = Stream.EmitAbbrev(Abbv);
694 // Emit the global variable information.
695 SmallVector<unsigned, 64> Vals;
696 for (const GlobalVariable &GV : M->globals()) {
697 unsigned AbbrevToUse = 0;
699 // GLOBALVAR: [type, isconst, initid,
700 // linkage, alignment, section, visibility, threadlocal,
701 // unnamed_addr, externally_initialized, dllstorageclass,
703 Vals.push_back(VE.getTypeID(GV.getValueType()));
704 Vals.push_back(GV.getType()->getAddressSpace() << 2 | 2 | GV.isConstant());
705 Vals.push_back(GV.isDeclaration() ? 0 :
706 (VE.getValueID(GV.getInitializer()) + 1));
707 Vals.push_back(getEncodedLinkage(GV));
708 Vals.push_back(Log2_32(GV.getAlignment())+1);
709 Vals.push_back(GV.hasSection() ? SectionMap[GV.getSection()] : 0);
710 if (GV.isThreadLocal() ||
711 GV.getVisibility() != GlobalValue::DefaultVisibility ||
712 GV.hasUnnamedAddr() || GV.isExternallyInitialized() ||
713 GV.getDLLStorageClass() != GlobalValue::DefaultStorageClass ||
715 Vals.push_back(getEncodedVisibility(GV));
716 Vals.push_back(getEncodedThreadLocalMode(GV));
717 Vals.push_back(GV.hasUnnamedAddr());
718 Vals.push_back(GV.isExternallyInitialized());
719 Vals.push_back(getEncodedDLLStorageClass(GV));
720 Vals.push_back(GV.hasComdat() ? VE.getComdatID(GV.getComdat()) : 0);
722 AbbrevToUse = SimpleGVarAbbrev;
725 Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse);
729 // Emit the function proto information.
730 for (const Function &F : *M) {
731 // FUNCTION: [type, callingconv, isproto, linkage, paramattrs, alignment,
732 // section, visibility, gc, unnamed_addr, prologuedata,
733 // dllstorageclass, comdat, prefixdata, personalityfn]
734 Vals.push_back(VE.getTypeID(F.getFunctionType()));
735 Vals.push_back(F.getCallingConv());
736 Vals.push_back(F.isDeclaration());
737 Vals.push_back(getEncodedLinkage(F));
738 Vals.push_back(VE.getAttributeID(F.getAttributes()));
739 Vals.push_back(Log2_32(F.getAlignment())+1);
740 Vals.push_back(F.hasSection() ? SectionMap[F.getSection()] : 0);
741 Vals.push_back(getEncodedVisibility(F));
742 Vals.push_back(F.hasGC() ? GCMap[F.getGC()] : 0);
743 Vals.push_back(F.hasUnnamedAddr());
744 Vals.push_back(F.hasPrologueData() ? (VE.getValueID(F.getPrologueData()) + 1)
746 Vals.push_back(getEncodedDLLStorageClass(F));
747 Vals.push_back(F.hasComdat() ? VE.getComdatID(F.getComdat()) : 0);
748 Vals.push_back(F.hasPrefixData() ? (VE.getValueID(F.getPrefixData()) + 1)
751 F.hasPersonalityFn() ? (VE.getValueID(F.getPersonalityFn()) + 1) : 0);
753 unsigned AbbrevToUse = 0;
754 Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse);
758 // Emit the alias information.
759 for (const GlobalAlias &A : M->aliases()) {
760 // ALIAS: [alias type, aliasee val#, linkage, visibility]
761 Vals.push_back(VE.getTypeID(A.getValueType()));
762 Vals.push_back(A.getType()->getAddressSpace());
763 Vals.push_back(VE.getValueID(A.getAliasee()));
764 Vals.push_back(getEncodedLinkage(A));
765 Vals.push_back(getEncodedVisibility(A));
766 Vals.push_back(getEncodedDLLStorageClass(A));
767 Vals.push_back(getEncodedThreadLocalMode(A));
768 Vals.push_back(A.hasUnnamedAddr());
769 unsigned AbbrevToUse = 0;
770 Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse);
774 uint64_t VSTOffsetPlaceholder =
775 WriteValueSymbolTableForwardDecl(M->getValueSymbolTable(), Stream);
776 return VSTOffsetPlaceholder;
779 static uint64_t GetOptimizationFlags(const Value *V) {
782 if (const auto *OBO = dyn_cast<OverflowingBinaryOperator>(V)) {
783 if (OBO->hasNoSignedWrap())
784 Flags |= 1 << bitc::OBO_NO_SIGNED_WRAP;
785 if (OBO->hasNoUnsignedWrap())
786 Flags |= 1 << bitc::OBO_NO_UNSIGNED_WRAP;
787 } else if (const auto *PEO = dyn_cast<PossiblyExactOperator>(V)) {
789 Flags |= 1 << bitc::PEO_EXACT;
790 } else if (const auto *FPMO = dyn_cast<FPMathOperator>(V)) {
791 if (FPMO->hasUnsafeAlgebra())
792 Flags |= FastMathFlags::UnsafeAlgebra;
793 if (FPMO->hasNoNaNs())
794 Flags |= FastMathFlags::NoNaNs;
795 if (FPMO->hasNoInfs())
796 Flags |= FastMathFlags::NoInfs;
797 if (FPMO->hasNoSignedZeros())
798 Flags |= FastMathFlags::NoSignedZeros;
799 if (FPMO->hasAllowReciprocal())
800 Flags |= FastMathFlags::AllowReciprocal;
806 static void WriteValueAsMetadata(const ValueAsMetadata *MD,
807 const ValueEnumerator &VE,
808 BitstreamWriter &Stream,
809 SmallVectorImpl<uint64_t> &Record) {
810 // Mimic an MDNode with a value as one operand.
811 Value *V = MD->getValue();
812 Record.push_back(VE.getTypeID(V->getType()));
813 Record.push_back(VE.getValueID(V));
814 Stream.EmitRecord(bitc::METADATA_VALUE, Record, 0);
818 static void WriteMDTuple(const MDTuple *N, const ValueEnumerator &VE,
819 BitstreamWriter &Stream,
820 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev) {
821 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
822 Metadata *MD = N->getOperand(i);
823 assert(!(MD && isa<LocalAsMetadata>(MD)) &&
824 "Unexpected function-local metadata");
825 Record.push_back(VE.getMetadataOrNullID(MD));
827 Stream.EmitRecord(N->isDistinct() ? bitc::METADATA_DISTINCT_NODE
828 : bitc::METADATA_NODE,
833 static void WriteDILocation(const DILocation *N, const ValueEnumerator &VE,
834 BitstreamWriter &Stream,
835 SmallVectorImpl<uint64_t> &Record,
837 Record.push_back(N->isDistinct());
838 Record.push_back(N->getLine());
839 Record.push_back(N->getColumn());
840 Record.push_back(VE.getMetadataID(N->getScope()));
841 Record.push_back(VE.getMetadataOrNullID(N->getInlinedAt()));
843 Stream.EmitRecord(bitc::METADATA_LOCATION, Record, Abbrev);
847 static void WriteGenericDINode(const GenericDINode *N,
848 const ValueEnumerator &VE,
849 BitstreamWriter &Stream,
850 SmallVectorImpl<uint64_t> &Record,
852 Record.push_back(N->isDistinct());
853 Record.push_back(N->getTag());
854 Record.push_back(0); // Per-tag version field; unused for now.
856 for (auto &I : N->operands())
857 Record.push_back(VE.getMetadataOrNullID(I));
859 Stream.EmitRecord(bitc::METADATA_GENERIC_DEBUG, Record, Abbrev);
863 static uint64_t rotateSign(int64_t I) {
865 return I < 0 ? ~(U << 1) : U << 1;
868 static void WriteDISubrange(const DISubrange *N, const ValueEnumerator &,
869 BitstreamWriter &Stream,
870 SmallVectorImpl<uint64_t> &Record,
872 Record.push_back(N->isDistinct());
873 Record.push_back(N->getCount());
874 Record.push_back(rotateSign(N->getLowerBound()));
876 Stream.EmitRecord(bitc::METADATA_SUBRANGE, Record, Abbrev);
880 static void WriteDIEnumerator(const DIEnumerator *N, const ValueEnumerator &VE,
881 BitstreamWriter &Stream,
882 SmallVectorImpl<uint64_t> &Record,
884 Record.push_back(N->isDistinct());
885 Record.push_back(rotateSign(N->getValue()));
886 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
888 Stream.EmitRecord(bitc::METADATA_ENUMERATOR, Record, Abbrev);
892 static void WriteDIBasicType(const DIBasicType *N, const ValueEnumerator &VE,
893 BitstreamWriter &Stream,
894 SmallVectorImpl<uint64_t> &Record,
896 Record.push_back(N->isDistinct());
897 Record.push_back(N->getTag());
898 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
899 Record.push_back(N->getSizeInBits());
900 Record.push_back(N->getAlignInBits());
901 Record.push_back(N->getEncoding());
903 Stream.EmitRecord(bitc::METADATA_BASIC_TYPE, Record, Abbrev);
907 static void WriteDIDerivedType(const DIDerivedType *N,
908 const ValueEnumerator &VE,
909 BitstreamWriter &Stream,
910 SmallVectorImpl<uint64_t> &Record,
912 Record.push_back(N->isDistinct());
913 Record.push_back(N->getTag());
914 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
915 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
916 Record.push_back(N->getLine());
917 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
918 Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
919 Record.push_back(N->getSizeInBits());
920 Record.push_back(N->getAlignInBits());
921 Record.push_back(N->getOffsetInBits());
922 Record.push_back(N->getFlags());
923 Record.push_back(VE.getMetadataOrNullID(N->getExtraData()));
925 Stream.EmitRecord(bitc::METADATA_DERIVED_TYPE, Record, Abbrev);
929 static void WriteDICompositeType(const DICompositeType *N,
930 const ValueEnumerator &VE,
931 BitstreamWriter &Stream,
932 SmallVectorImpl<uint64_t> &Record,
934 Record.push_back(N->isDistinct());
935 Record.push_back(N->getTag());
936 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
937 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
938 Record.push_back(N->getLine());
939 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
940 Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
941 Record.push_back(N->getSizeInBits());
942 Record.push_back(N->getAlignInBits());
943 Record.push_back(N->getOffsetInBits());
944 Record.push_back(N->getFlags());
945 Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
946 Record.push_back(N->getRuntimeLang());
947 Record.push_back(VE.getMetadataOrNullID(N->getVTableHolder()));
948 Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
949 Record.push_back(VE.getMetadataOrNullID(N->getRawIdentifier()));
951 Stream.EmitRecord(bitc::METADATA_COMPOSITE_TYPE, Record, Abbrev);
955 static void WriteDISubroutineType(const DISubroutineType *N,
956 const ValueEnumerator &VE,
957 BitstreamWriter &Stream,
958 SmallVectorImpl<uint64_t> &Record,
960 Record.push_back(N->isDistinct());
961 Record.push_back(N->getFlags());
962 Record.push_back(VE.getMetadataOrNullID(N->getTypeArray().get()));
964 Stream.EmitRecord(bitc::METADATA_SUBROUTINE_TYPE, Record, Abbrev);
968 static void WriteDIFile(const DIFile *N, const ValueEnumerator &VE,
969 BitstreamWriter &Stream,
970 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev) {
971 Record.push_back(N->isDistinct());
972 Record.push_back(VE.getMetadataOrNullID(N->getRawFilename()));
973 Record.push_back(VE.getMetadataOrNullID(N->getRawDirectory()));
975 Stream.EmitRecord(bitc::METADATA_FILE, Record, Abbrev);
979 static void WriteDICompileUnit(const DICompileUnit *N,
980 const ValueEnumerator &VE,
981 BitstreamWriter &Stream,
982 SmallVectorImpl<uint64_t> &Record,
984 assert(N->isDistinct() && "Expected distinct compile units");
985 Record.push_back(/* IsDistinct */ true);
986 Record.push_back(N->getSourceLanguage());
987 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
988 Record.push_back(VE.getMetadataOrNullID(N->getRawProducer()));
989 Record.push_back(N->isOptimized());
990 Record.push_back(VE.getMetadataOrNullID(N->getRawFlags()));
991 Record.push_back(N->getRuntimeVersion());
992 Record.push_back(VE.getMetadataOrNullID(N->getRawSplitDebugFilename()));
993 Record.push_back(N->getEmissionKind());
994 Record.push_back(VE.getMetadataOrNullID(N->getEnumTypes().get()));
995 Record.push_back(VE.getMetadataOrNullID(N->getRetainedTypes().get()));
996 Record.push_back(VE.getMetadataOrNullID(N->getSubprograms().get()));
997 Record.push_back(VE.getMetadataOrNullID(N->getGlobalVariables().get()));
998 Record.push_back(VE.getMetadataOrNullID(N->getImportedEntities().get()));
999 Record.push_back(N->getDWOId());
1001 Stream.EmitRecord(bitc::METADATA_COMPILE_UNIT, Record, Abbrev);
1005 static void WriteDISubprogram(const DISubprogram *N, const ValueEnumerator &VE,
1006 BitstreamWriter &Stream,
1007 SmallVectorImpl<uint64_t> &Record,
1009 Record.push_back(N->isDistinct());
1010 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1011 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1012 Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
1013 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1014 Record.push_back(N->getLine());
1015 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1016 Record.push_back(N->isLocalToUnit());
1017 Record.push_back(N->isDefinition());
1018 Record.push_back(N->getScopeLine());
1019 Record.push_back(VE.getMetadataOrNullID(N->getContainingType()));
1020 Record.push_back(N->getVirtuality());
1021 Record.push_back(N->getVirtualIndex());
1022 Record.push_back(N->getFlags());
1023 Record.push_back(N->isOptimized());
1024 Record.push_back(VE.getMetadataOrNullID(N->getRawFunction()));
1025 Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
1026 Record.push_back(VE.getMetadataOrNullID(N->getDeclaration()));
1027 Record.push_back(VE.getMetadataOrNullID(N->getVariables().get()));
1029 Stream.EmitRecord(bitc::METADATA_SUBPROGRAM, Record, Abbrev);
1033 static void WriteDILexicalBlock(const DILexicalBlock *N,
1034 const ValueEnumerator &VE,
1035 BitstreamWriter &Stream,
1036 SmallVectorImpl<uint64_t> &Record,
1038 Record.push_back(N->isDistinct());
1039 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1040 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1041 Record.push_back(N->getLine());
1042 Record.push_back(N->getColumn());
1044 Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK, Record, Abbrev);
1048 static void WriteDILexicalBlockFile(const DILexicalBlockFile *N,
1049 const ValueEnumerator &VE,
1050 BitstreamWriter &Stream,
1051 SmallVectorImpl<uint64_t> &Record,
1053 Record.push_back(N->isDistinct());
1054 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1055 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1056 Record.push_back(N->getDiscriminator());
1058 Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK_FILE, Record, Abbrev);
1062 static void WriteDINamespace(const DINamespace *N, const ValueEnumerator &VE,
1063 BitstreamWriter &Stream,
1064 SmallVectorImpl<uint64_t> &Record,
1066 Record.push_back(N->isDistinct());
1067 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1068 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1069 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1070 Record.push_back(N->getLine());
1072 Stream.EmitRecord(bitc::METADATA_NAMESPACE, Record, Abbrev);
1076 static void WriteDIModule(const DIModule *N, const ValueEnumerator &VE,
1077 BitstreamWriter &Stream,
1078 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev) {
1079 Record.push_back(N->isDistinct());
1080 for (auto &I : N->operands())
1081 Record.push_back(VE.getMetadataOrNullID(I));
1083 Stream.EmitRecord(bitc::METADATA_MODULE, Record, Abbrev);
1087 static void WriteDITemplateTypeParameter(const DITemplateTypeParameter *N,
1088 const ValueEnumerator &VE,
1089 BitstreamWriter &Stream,
1090 SmallVectorImpl<uint64_t> &Record,
1092 Record.push_back(N->isDistinct());
1093 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1094 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1096 Stream.EmitRecord(bitc::METADATA_TEMPLATE_TYPE, Record, Abbrev);
1100 static void WriteDITemplateValueParameter(const DITemplateValueParameter *N,
1101 const ValueEnumerator &VE,
1102 BitstreamWriter &Stream,
1103 SmallVectorImpl<uint64_t> &Record,
1105 Record.push_back(N->isDistinct());
1106 Record.push_back(N->getTag());
1107 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1108 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1109 Record.push_back(VE.getMetadataOrNullID(N->getValue()));
1111 Stream.EmitRecord(bitc::METADATA_TEMPLATE_VALUE, Record, Abbrev);
1115 static void WriteDIGlobalVariable(const DIGlobalVariable *N,
1116 const ValueEnumerator &VE,
1117 BitstreamWriter &Stream,
1118 SmallVectorImpl<uint64_t> &Record,
1120 Record.push_back(N->isDistinct());
1121 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1122 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1123 Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
1124 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1125 Record.push_back(N->getLine());
1126 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1127 Record.push_back(N->isLocalToUnit());
1128 Record.push_back(N->isDefinition());
1129 Record.push_back(VE.getMetadataOrNullID(N->getRawVariable()));
1130 Record.push_back(VE.getMetadataOrNullID(N->getStaticDataMemberDeclaration()));
1132 Stream.EmitRecord(bitc::METADATA_GLOBAL_VAR, Record, Abbrev);
1136 static void WriteDILocalVariable(const DILocalVariable *N,
1137 const ValueEnumerator &VE,
1138 BitstreamWriter &Stream,
1139 SmallVectorImpl<uint64_t> &Record,
1141 Record.push_back(N->isDistinct());
1142 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1143 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1144 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1145 Record.push_back(N->getLine());
1146 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1147 Record.push_back(N->getArg());
1148 Record.push_back(N->getFlags());
1150 Stream.EmitRecord(bitc::METADATA_LOCAL_VAR, Record, Abbrev);
1154 static void WriteDIExpression(const DIExpression *N, const ValueEnumerator &,
1155 BitstreamWriter &Stream,
1156 SmallVectorImpl<uint64_t> &Record,
1158 Record.reserve(N->getElements().size() + 1);
1160 Record.push_back(N->isDistinct());
1161 Record.append(N->elements_begin(), N->elements_end());
1163 Stream.EmitRecord(bitc::METADATA_EXPRESSION, Record, Abbrev);
1167 static void WriteDIObjCProperty(const DIObjCProperty *N,
1168 const ValueEnumerator &VE,
1169 BitstreamWriter &Stream,
1170 SmallVectorImpl<uint64_t> &Record,
1172 Record.push_back(N->isDistinct());
1173 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1174 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1175 Record.push_back(N->getLine());
1176 Record.push_back(VE.getMetadataOrNullID(N->getRawSetterName()));
1177 Record.push_back(VE.getMetadataOrNullID(N->getRawGetterName()));
1178 Record.push_back(N->getAttributes());
1179 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1181 Stream.EmitRecord(bitc::METADATA_OBJC_PROPERTY, Record, Abbrev);
1185 static void WriteDIImportedEntity(const DIImportedEntity *N,
1186 const ValueEnumerator &VE,
1187 BitstreamWriter &Stream,
1188 SmallVectorImpl<uint64_t> &Record,
1190 Record.push_back(N->isDistinct());
1191 Record.push_back(N->getTag());
1192 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1193 Record.push_back(VE.getMetadataOrNullID(N->getEntity()));
1194 Record.push_back(N->getLine());
1195 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1197 Stream.EmitRecord(bitc::METADATA_IMPORTED_ENTITY, Record, Abbrev);
1201 static void WriteModuleMetadata(const Module *M,
1202 const ValueEnumerator &VE,
1203 BitstreamWriter &Stream) {
1204 const auto &MDs = VE.getMDs();
1205 if (MDs.empty() && M->named_metadata_empty())
1208 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
1210 unsigned MDSAbbrev = 0;
1211 if (VE.hasMDString()) {
1212 // Abbrev for METADATA_STRING.
1213 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1214 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_STRING));
1215 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1216 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
1217 MDSAbbrev = Stream.EmitAbbrev(Abbv);
1220 // Initialize MDNode abbreviations.
1221 #define HANDLE_MDNODE_LEAF(CLASS) unsigned CLASS##Abbrev = 0;
1222 #include "llvm/IR/Metadata.def"
1224 if (VE.hasDILocation()) {
1225 // Abbrev for METADATA_LOCATION.
1227 // Assume the column is usually under 128, and always output the inlined-at
1228 // location (it's never more expensive than building an array size 1).
1229 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1230 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_LOCATION));
1231 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1232 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1233 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1234 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1235 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1236 DILocationAbbrev = Stream.EmitAbbrev(Abbv);
1239 if (VE.hasGenericDINode()) {
1240 // Abbrev for METADATA_GENERIC_DEBUG.
1242 // Assume the column is usually under 128, and always output the inlined-at
1243 // location (it's never more expensive than building an array size 1).
1244 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1245 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_GENERIC_DEBUG));
1246 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1247 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1248 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1249 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1250 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1251 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1252 GenericDINodeAbbrev = Stream.EmitAbbrev(Abbv);
1255 unsigned NameAbbrev = 0;
1256 if (!M->named_metadata_empty()) {
1257 // Abbrev for METADATA_NAME.
1258 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1259 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_NAME));
1260 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1261 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
1262 NameAbbrev = Stream.EmitAbbrev(Abbv);
1265 SmallVector<uint64_t, 64> Record;
1266 for (const Metadata *MD : MDs) {
1267 if (const MDNode *N = dyn_cast<MDNode>(MD)) {
1268 assert(N->isResolved() && "Expected forward references to be resolved");
1270 switch (N->getMetadataID()) {
1272 llvm_unreachable("Invalid MDNode subclass");
1273 #define HANDLE_MDNODE_LEAF(CLASS) \
1274 case Metadata::CLASS##Kind: \
1275 Write##CLASS(cast<CLASS>(N), VE, Stream, Record, CLASS##Abbrev); \
1277 #include "llvm/IR/Metadata.def"
1280 if (const auto *MDC = dyn_cast<ConstantAsMetadata>(MD)) {
1281 WriteValueAsMetadata(MDC, VE, Stream, Record);
1284 const MDString *MDS = cast<MDString>(MD);
1285 // Code: [strchar x N]
1286 Record.append(MDS->bytes_begin(), MDS->bytes_end());
1288 // Emit the finished record.
1289 Stream.EmitRecord(bitc::METADATA_STRING, Record, MDSAbbrev);
1293 // Write named metadata.
1294 for (const NamedMDNode &NMD : M->named_metadata()) {
1296 StringRef Str = NMD.getName();
1297 Record.append(Str.bytes_begin(), Str.bytes_end());
1298 Stream.EmitRecord(bitc::METADATA_NAME, Record, NameAbbrev);
1301 // Write named metadata operands.
1302 for (const MDNode *N : NMD.operands())
1303 Record.push_back(VE.getMetadataID(N));
1304 Stream.EmitRecord(bitc::METADATA_NAMED_NODE, Record, 0);
1311 static void WriteFunctionLocalMetadata(const Function &F,
1312 const ValueEnumerator &VE,
1313 BitstreamWriter &Stream) {
1314 bool StartedMetadataBlock = false;
1315 SmallVector<uint64_t, 64> Record;
1316 const SmallVectorImpl<const LocalAsMetadata *> &MDs =
1317 VE.getFunctionLocalMDs();
1318 for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
1319 assert(MDs[i] && "Expected valid function-local metadata");
1320 if (!StartedMetadataBlock) {
1321 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
1322 StartedMetadataBlock = true;
1324 WriteValueAsMetadata(MDs[i], VE, Stream, Record);
1327 if (StartedMetadataBlock)
1331 static void WriteMetadataAttachment(const Function &F,
1332 const ValueEnumerator &VE,
1333 BitstreamWriter &Stream) {
1334 Stream.EnterSubblock(bitc::METADATA_ATTACHMENT_ID, 3);
1336 SmallVector<uint64_t, 64> Record;
1338 // Write metadata attachments
1339 // METADATA_ATTACHMENT - [m x [value, [n x [id, mdnode]]]
1340 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
1341 F.getAllMetadata(MDs);
1343 for (const auto &I : MDs) {
1344 Record.push_back(I.first);
1345 Record.push_back(VE.getMetadataID(I.second));
1347 Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
1351 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1352 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
1355 I->getAllMetadataOtherThanDebugLoc(MDs);
1357 // If no metadata, ignore instruction.
1358 if (MDs.empty()) continue;
1360 Record.push_back(VE.getInstructionID(I));
1362 for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
1363 Record.push_back(MDs[i].first);
1364 Record.push_back(VE.getMetadataID(MDs[i].second));
1366 Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
1373 static void WriteModuleMetadataStore(const Module *M, BitstreamWriter &Stream) {
1374 SmallVector<uint64_t, 64> Record;
1376 // Write metadata kinds
1377 // METADATA_KIND - [n x [id, name]]
1378 SmallVector<StringRef, 8> Names;
1379 M->getMDKindNames(Names);
1381 if (Names.empty()) return;
1383 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
1385 for (unsigned MDKindID = 0, e = Names.size(); MDKindID != e; ++MDKindID) {
1386 Record.push_back(MDKindID);
1387 StringRef KName = Names[MDKindID];
1388 Record.append(KName.begin(), KName.end());
1390 Stream.EmitRecord(bitc::METADATA_KIND, Record, 0);
1397 static void WriteOperandBundleTags(const Module *M, BitstreamWriter &Stream) {
1398 // Write metadata kinds
1400 // OPERAND_BUNDLE_TAGS_BLOCK_ID : N x OPERAND_BUNDLE_TAG
1402 // OPERAND_BUNDLE_TAG - [strchr x N]
1404 SmallVector<StringRef, 8> Tags;
1405 M->getOperandBundleTags(Tags);
1410 Stream.EnterSubblock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID, 3);
1412 SmallVector<uint64_t, 64> Record;
1414 for (auto Tag : Tags) {
1415 Record.append(Tag.begin(), Tag.end());
1417 Stream.EmitRecord(bitc::OPERAND_BUNDLE_TAG, Record, 0);
1424 static void emitSignedInt64(SmallVectorImpl<uint64_t> &Vals, uint64_t V) {
1425 if ((int64_t)V >= 0)
1426 Vals.push_back(V << 1);
1428 Vals.push_back((-V << 1) | 1);
1431 static void WriteConstants(unsigned FirstVal, unsigned LastVal,
1432 const ValueEnumerator &VE,
1433 BitstreamWriter &Stream, bool isGlobal) {
1434 if (FirstVal == LastVal) return;
1436 Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 4);
1438 unsigned AggregateAbbrev = 0;
1439 unsigned String8Abbrev = 0;
1440 unsigned CString7Abbrev = 0;
1441 unsigned CString6Abbrev = 0;
1442 // If this is a constant pool for the module, emit module-specific abbrevs.
1444 // Abbrev for CST_CODE_AGGREGATE.
1445 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1446 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_AGGREGATE));
1447 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1448 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal+1)));
1449 AggregateAbbrev = Stream.EmitAbbrev(Abbv);
1451 // Abbrev for CST_CODE_STRING.
1452 Abbv = new BitCodeAbbrev();
1453 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_STRING));
1454 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1455 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
1456 String8Abbrev = Stream.EmitAbbrev(Abbv);
1457 // Abbrev for CST_CODE_CSTRING.
1458 Abbv = new BitCodeAbbrev();
1459 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
1460 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1461 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
1462 CString7Abbrev = Stream.EmitAbbrev(Abbv);
1463 // Abbrev for CST_CODE_CSTRING.
1464 Abbv = new BitCodeAbbrev();
1465 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
1466 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1467 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
1468 CString6Abbrev = Stream.EmitAbbrev(Abbv);
1471 SmallVector<uint64_t, 64> Record;
1473 const ValueEnumerator::ValueList &Vals = VE.getValues();
1474 Type *LastTy = nullptr;
1475 for (unsigned i = FirstVal; i != LastVal; ++i) {
1476 const Value *V = Vals[i].first;
1477 // If we need to switch types, do so now.
1478 if (V->getType() != LastTy) {
1479 LastTy = V->getType();
1480 Record.push_back(VE.getTypeID(LastTy));
1481 Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record,
1482 CONSTANTS_SETTYPE_ABBREV);
1486 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
1487 Record.push_back(unsigned(IA->hasSideEffects()) |
1488 unsigned(IA->isAlignStack()) << 1 |
1489 unsigned(IA->getDialect()&1) << 2);
1491 // Add the asm string.
1492 const std::string &AsmStr = IA->getAsmString();
1493 Record.push_back(AsmStr.size());
1494 Record.append(AsmStr.begin(), AsmStr.end());
1496 // Add the constraint string.
1497 const std::string &ConstraintStr = IA->getConstraintString();
1498 Record.push_back(ConstraintStr.size());
1499 Record.append(ConstraintStr.begin(), ConstraintStr.end());
1500 Stream.EmitRecord(bitc::CST_CODE_INLINEASM, Record);
1504 const Constant *C = cast<Constant>(V);
1505 unsigned Code = -1U;
1506 unsigned AbbrevToUse = 0;
1507 if (C->isNullValue()) {
1508 Code = bitc::CST_CODE_NULL;
1509 } else if (isa<UndefValue>(C)) {
1510 Code = bitc::CST_CODE_UNDEF;
1511 } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {
1512 if (IV->getBitWidth() <= 64) {
1513 uint64_t V = IV->getSExtValue();
1514 emitSignedInt64(Record, V);
1515 Code = bitc::CST_CODE_INTEGER;
1516 AbbrevToUse = CONSTANTS_INTEGER_ABBREV;
1517 } else { // Wide integers, > 64 bits in size.
1518 // We have an arbitrary precision integer value to write whose
1519 // bit width is > 64. However, in canonical unsigned integer
1520 // format it is likely that the high bits are going to be zero.
1521 // So, we only write the number of active words.
1522 unsigned NWords = IV->getValue().getActiveWords();
1523 const uint64_t *RawWords = IV->getValue().getRawData();
1524 for (unsigned i = 0; i != NWords; ++i) {
1525 emitSignedInt64(Record, RawWords[i]);
1527 Code = bitc::CST_CODE_WIDE_INTEGER;
1529 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
1530 Code = bitc::CST_CODE_FLOAT;
1531 Type *Ty = CFP->getType();
1532 if (Ty->isHalfTy() || Ty->isFloatTy() || Ty->isDoubleTy()) {
1533 Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
1534 } else if (Ty->isX86_FP80Ty()) {
1535 // api needed to prevent premature destruction
1536 // bits are not in the same order as a normal i80 APInt, compensate.
1537 APInt api = CFP->getValueAPF().bitcastToAPInt();
1538 const uint64_t *p = api.getRawData();
1539 Record.push_back((p[1] << 48) | (p[0] >> 16));
1540 Record.push_back(p[0] & 0xffffLL);
1541 } else if (Ty->isFP128Ty() || Ty->isPPC_FP128Ty()) {
1542 APInt api = CFP->getValueAPF().bitcastToAPInt();
1543 const uint64_t *p = api.getRawData();
1544 Record.push_back(p[0]);
1545 Record.push_back(p[1]);
1547 assert (0 && "Unknown FP type!");
1549 } else if (isa<ConstantDataSequential>(C) &&
1550 cast<ConstantDataSequential>(C)->isString()) {
1551 const ConstantDataSequential *Str = cast<ConstantDataSequential>(C);
1552 // Emit constant strings specially.
1553 unsigned NumElts = Str->getNumElements();
1554 // If this is a null-terminated string, use the denser CSTRING encoding.
1555 if (Str->isCString()) {
1556 Code = bitc::CST_CODE_CSTRING;
1557 --NumElts; // Don't encode the null, which isn't allowed by char6.
1559 Code = bitc::CST_CODE_STRING;
1560 AbbrevToUse = String8Abbrev;
1562 bool isCStr7 = Code == bitc::CST_CODE_CSTRING;
1563 bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING;
1564 for (unsigned i = 0; i != NumElts; ++i) {
1565 unsigned char V = Str->getElementAsInteger(i);
1566 Record.push_back(V);
1567 isCStr7 &= (V & 128) == 0;
1569 isCStrChar6 = BitCodeAbbrevOp::isChar6(V);
1573 AbbrevToUse = CString6Abbrev;
1575 AbbrevToUse = CString7Abbrev;
1576 } else if (const ConstantDataSequential *CDS =
1577 dyn_cast<ConstantDataSequential>(C)) {
1578 Code = bitc::CST_CODE_DATA;
1579 Type *EltTy = CDS->getType()->getElementType();
1580 if (isa<IntegerType>(EltTy)) {
1581 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
1582 Record.push_back(CDS->getElementAsInteger(i));
1583 } else if (EltTy->isFloatTy()) {
1584 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1585 union { float F; uint32_t I; };
1586 F = CDS->getElementAsFloat(i);
1587 Record.push_back(I);
1590 assert(EltTy->isDoubleTy() && "Unknown ConstantData element type");
1591 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1592 union { double F; uint64_t I; };
1593 F = CDS->getElementAsDouble(i);
1594 Record.push_back(I);
1597 } else if (isa<ConstantArray>(C) || isa<ConstantStruct>(C) ||
1598 isa<ConstantVector>(C)) {
1599 Code = bitc::CST_CODE_AGGREGATE;
1600 for (const Value *Op : C->operands())
1601 Record.push_back(VE.getValueID(Op));
1602 AbbrevToUse = AggregateAbbrev;
1603 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1604 switch (CE->getOpcode()) {
1606 if (Instruction::isCast(CE->getOpcode())) {
1607 Code = bitc::CST_CODE_CE_CAST;
1608 Record.push_back(GetEncodedCastOpcode(CE->getOpcode()));
1609 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
1610 Record.push_back(VE.getValueID(C->getOperand(0)));
1611 AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;
1613 assert(CE->getNumOperands() == 2 && "Unknown constant expr!");
1614 Code = bitc::CST_CODE_CE_BINOP;
1615 Record.push_back(GetEncodedBinaryOpcode(CE->getOpcode()));
1616 Record.push_back(VE.getValueID(C->getOperand(0)));
1617 Record.push_back(VE.getValueID(C->getOperand(1)));
1618 uint64_t Flags = GetOptimizationFlags(CE);
1620 Record.push_back(Flags);
1623 case Instruction::GetElementPtr: {
1624 Code = bitc::CST_CODE_CE_GEP;
1625 const auto *GO = cast<GEPOperator>(C);
1626 if (GO->isInBounds())
1627 Code = bitc::CST_CODE_CE_INBOUNDS_GEP;
1628 Record.push_back(VE.getTypeID(GO->getSourceElementType()));
1629 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
1630 Record.push_back(VE.getTypeID(C->getOperand(i)->getType()));
1631 Record.push_back(VE.getValueID(C->getOperand(i)));
1635 case Instruction::Select:
1636 Code = bitc::CST_CODE_CE_SELECT;
1637 Record.push_back(VE.getValueID(C->getOperand(0)));
1638 Record.push_back(VE.getValueID(C->getOperand(1)));
1639 Record.push_back(VE.getValueID(C->getOperand(2)));
1641 case Instruction::ExtractElement:
1642 Code = bitc::CST_CODE_CE_EXTRACTELT;
1643 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
1644 Record.push_back(VE.getValueID(C->getOperand(0)));
1645 Record.push_back(VE.getTypeID(C->getOperand(1)->getType()));
1646 Record.push_back(VE.getValueID(C->getOperand(1)));
1648 case Instruction::InsertElement:
1649 Code = bitc::CST_CODE_CE_INSERTELT;
1650 Record.push_back(VE.getValueID(C->getOperand(0)));
1651 Record.push_back(VE.getValueID(C->getOperand(1)));
1652 Record.push_back(VE.getTypeID(C->getOperand(2)->getType()));
1653 Record.push_back(VE.getValueID(C->getOperand(2)));
1655 case Instruction::ShuffleVector:
1656 // If the return type and argument types are the same, this is a
1657 // standard shufflevector instruction. If the types are different,
1658 // then the shuffle is widening or truncating the input vectors, and
1659 // the argument type must also be encoded.
1660 if (C->getType() == C->getOperand(0)->getType()) {
1661 Code = bitc::CST_CODE_CE_SHUFFLEVEC;
1663 Code = bitc::CST_CODE_CE_SHUFVEC_EX;
1664 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
1666 Record.push_back(VE.getValueID(C->getOperand(0)));
1667 Record.push_back(VE.getValueID(C->getOperand(1)));
1668 Record.push_back(VE.getValueID(C->getOperand(2)));
1670 case Instruction::ICmp:
1671 case Instruction::FCmp:
1672 Code = bitc::CST_CODE_CE_CMP;
1673 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
1674 Record.push_back(VE.getValueID(C->getOperand(0)));
1675 Record.push_back(VE.getValueID(C->getOperand(1)));
1676 Record.push_back(CE->getPredicate());
1679 } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) {
1680 Code = bitc::CST_CODE_BLOCKADDRESS;
1681 Record.push_back(VE.getTypeID(BA->getFunction()->getType()));
1682 Record.push_back(VE.getValueID(BA->getFunction()));
1683 Record.push_back(VE.getGlobalBasicBlockID(BA->getBasicBlock()));
1688 llvm_unreachable("Unknown constant!");
1690 Stream.EmitRecord(Code, Record, AbbrevToUse);
1697 static void WriteModuleConstants(const ValueEnumerator &VE,
1698 BitstreamWriter &Stream) {
1699 const ValueEnumerator::ValueList &Vals = VE.getValues();
1701 // Find the first constant to emit, which is the first non-globalvalue value.
1702 // We know globalvalues have been emitted by WriteModuleInfo.
1703 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
1704 if (!isa<GlobalValue>(Vals[i].first)) {
1705 WriteConstants(i, Vals.size(), VE, Stream, true);
1711 /// PushValueAndType - The file has to encode both the value and type id for
1712 /// many values, because we need to know what type to create for forward
1713 /// references. However, most operands are not forward references, so this type
1714 /// field is not needed.
1716 /// This function adds V's value ID to Vals. If the value ID is higher than the
1717 /// instruction ID, then it is a forward reference, and it also includes the
1718 /// type ID. The value ID that is written is encoded relative to the InstID.
1719 static bool PushValueAndType(const Value *V, unsigned InstID,
1720 SmallVectorImpl<unsigned> &Vals,
1721 ValueEnumerator &VE) {
1722 unsigned ValID = VE.getValueID(V);
1723 // Make encoding relative to the InstID.
1724 Vals.push_back(InstID - ValID);
1725 if (ValID >= InstID) {
1726 Vals.push_back(VE.getTypeID(V->getType()));
1732 static void WriteOperandBundles(BitstreamWriter &Stream, ImmutableCallSite CS,
1733 unsigned InstID, ValueEnumerator &VE) {
1734 SmallVector<unsigned, 64> Record;
1735 LLVMContext &C = CS.getInstruction()->getContext();
1737 for (unsigned i = 0, e = CS.getNumOperandBundles(); i != e; ++i) {
1738 const auto &Bundle = CS.getOperandBundle(i);
1739 Record.push_back(C.getOperandBundleTagID(Bundle.Tag));
1741 for (auto &Input : Bundle.Inputs)
1742 PushValueAndType(Input, InstID, Record, VE);
1744 Stream.EmitRecord(bitc::FUNC_CODE_OPERAND_BUNDLE, Record);
1749 /// pushValue - Like PushValueAndType, but where the type of the value is
1750 /// omitted (perhaps it was already encoded in an earlier operand).
1751 static void pushValue(const Value *V, unsigned InstID,
1752 SmallVectorImpl<unsigned> &Vals,
1753 ValueEnumerator &VE) {
1754 unsigned ValID = VE.getValueID(V);
1755 Vals.push_back(InstID - ValID);
1758 static void pushValueSigned(const Value *V, unsigned InstID,
1759 SmallVectorImpl<uint64_t> &Vals,
1760 ValueEnumerator &VE) {
1761 unsigned ValID = VE.getValueID(V);
1762 int64_t diff = ((int32_t)InstID - (int32_t)ValID);
1763 emitSignedInt64(Vals, diff);
1766 /// WriteInstruction - Emit an instruction to the specified stream.
1767 static void WriteInstruction(const Instruction &I, unsigned InstID,
1768 ValueEnumerator &VE, BitstreamWriter &Stream,
1769 SmallVectorImpl<unsigned> &Vals) {
1771 unsigned AbbrevToUse = 0;
1772 VE.setInstructionID(&I);
1773 switch (I.getOpcode()) {
1775 if (Instruction::isCast(I.getOpcode())) {
1776 Code = bitc::FUNC_CODE_INST_CAST;
1777 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
1778 AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
1779 Vals.push_back(VE.getTypeID(I.getType()));
1780 Vals.push_back(GetEncodedCastOpcode(I.getOpcode()));
1782 assert(isa<BinaryOperator>(I) && "Unknown instruction!");
1783 Code = bitc::FUNC_CODE_INST_BINOP;
1784 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
1785 AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
1786 pushValue(I.getOperand(1), InstID, Vals, VE);
1787 Vals.push_back(GetEncodedBinaryOpcode(I.getOpcode()));
1788 uint64_t Flags = GetOptimizationFlags(&I);
1790 if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV)
1791 AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV;
1792 Vals.push_back(Flags);
1797 case Instruction::GetElementPtr: {
1798 Code = bitc::FUNC_CODE_INST_GEP;
1799 AbbrevToUse = FUNCTION_INST_GEP_ABBREV;
1800 auto &GEPInst = cast<GetElementPtrInst>(I);
1801 Vals.push_back(GEPInst.isInBounds());
1802 Vals.push_back(VE.getTypeID(GEPInst.getSourceElementType()));
1803 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
1804 PushValueAndType(I.getOperand(i), InstID, Vals, VE);
1807 case Instruction::ExtractValue: {
1808 Code = bitc::FUNC_CODE_INST_EXTRACTVAL;
1809 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1810 const ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
1811 Vals.append(EVI->idx_begin(), EVI->idx_end());
1814 case Instruction::InsertValue: {
1815 Code = bitc::FUNC_CODE_INST_INSERTVAL;
1816 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1817 PushValueAndType(I.getOperand(1), InstID, Vals, VE);
1818 const InsertValueInst *IVI = cast<InsertValueInst>(&I);
1819 Vals.append(IVI->idx_begin(), IVI->idx_end());
1822 case Instruction::Select:
1823 Code = bitc::FUNC_CODE_INST_VSELECT;
1824 PushValueAndType(I.getOperand(1), InstID, Vals, VE);
1825 pushValue(I.getOperand(2), InstID, Vals, VE);
1826 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1828 case Instruction::ExtractElement:
1829 Code = bitc::FUNC_CODE_INST_EXTRACTELT;
1830 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1831 PushValueAndType(I.getOperand(1), InstID, Vals, VE);
1833 case Instruction::InsertElement:
1834 Code = bitc::FUNC_CODE_INST_INSERTELT;
1835 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1836 pushValue(I.getOperand(1), InstID, Vals, VE);
1837 PushValueAndType(I.getOperand(2), InstID, Vals, VE);
1839 case Instruction::ShuffleVector:
1840 Code = bitc::FUNC_CODE_INST_SHUFFLEVEC;
1841 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1842 pushValue(I.getOperand(1), InstID, Vals, VE);
1843 pushValue(I.getOperand(2), InstID, Vals, VE);
1845 case Instruction::ICmp:
1846 case Instruction::FCmp: {
1847 // compare returning Int1Ty or vector of Int1Ty
1848 Code = bitc::FUNC_CODE_INST_CMP2;
1849 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1850 pushValue(I.getOperand(1), InstID, Vals, VE);
1851 Vals.push_back(cast<CmpInst>(I).getPredicate());
1852 uint64_t Flags = GetOptimizationFlags(&I);
1854 Vals.push_back(Flags);
1858 case Instruction::Ret:
1860 Code = bitc::FUNC_CODE_INST_RET;
1861 unsigned NumOperands = I.getNumOperands();
1862 if (NumOperands == 0)
1863 AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
1864 else if (NumOperands == 1) {
1865 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
1866 AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
1868 for (unsigned i = 0, e = NumOperands; i != e; ++i)
1869 PushValueAndType(I.getOperand(i), InstID, Vals, VE);
1873 case Instruction::Br:
1875 Code = bitc::FUNC_CODE_INST_BR;
1876 const BranchInst &II = cast<BranchInst>(I);
1877 Vals.push_back(VE.getValueID(II.getSuccessor(0)));
1878 if (II.isConditional()) {
1879 Vals.push_back(VE.getValueID(II.getSuccessor(1)));
1880 pushValue(II.getCondition(), InstID, Vals, VE);
1884 case Instruction::Switch:
1886 Code = bitc::FUNC_CODE_INST_SWITCH;
1887 const SwitchInst &SI = cast<SwitchInst>(I);
1888 Vals.push_back(VE.getTypeID(SI.getCondition()->getType()));
1889 pushValue(SI.getCondition(), InstID, Vals, VE);
1890 Vals.push_back(VE.getValueID(SI.getDefaultDest()));
1891 for (SwitchInst::ConstCaseIt i = SI.case_begin(), e = SI.case_end();
1893 Vals.push_back(VE.getValueID(i.getCaseValue()));
1894 Vals.push_back(VE.getValueID(i.getCaseSuccessor()));
1898 case Instruction::IndirectBr:
1899 Code = bitc::FUNC_CODE_INST_INDIRECTBR;
1900 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
1901 // Encode the address operand as relative, but not the basic blocks.
1902 pushValue(I.getOperand(0), InstID, Vals, VE);
1903 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i)
1904 Vals.push_back(VE.getValueID(I.getOperand(i)));
1907 case Instruction::Invoke: {
1908 const InvokeInst *II = cast<InvokeInst>(&I);
1909 const Value *Callee = II->getCalledValue();
1910 FunctionType *FTy = II->getFunctionType();
1912 if (II->hasOperandBundles())
1913 WriteOperandBundles(Stream, II, InstID, VE);
1915 Code = bitc::FUNC_CODE_INST_INVOKE;
1917 Vals.push_back(VE.getAttributeID(II->getAttributes()));
1918 Vals.push_back(II->getCallingConv() | 1 << 13);
1919 Vals.push_back(VE.getValueID(II->getNormalDest()));
1920 Vals.push_back(VE.getValueID(II->getUnwindDest()));
1921 Vals.push_back(VE.getTypeID(FTy));
1922 PushValueAndType(Callee, InstID, Vals, VE);
1924 // Emit value #'s for the fixed parameters.
1925 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
1926 pushValue(I.getOperand(i), InstID, Vals, VE); // fixed param.
1928 // Emit type/value pairs for varargs params.
1929 if (FTy->isVarArg()) {
1930 for (unsigned i = FTy->getNumParams(), e = I.getNumOperands()-3;
1932 PushValueAndType(I.getOperand(i), InstID, Vals, VE); // vararg
1936 case Instruction::Resume:
1937 Code = bitc::FUNC_CODE_INST_RESUME;
1938 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1940 case Instruction::CleanupRet: {
1941 Code = bitc::FUNC_CODE_INST_CLEANUPRET;
1942 const auto &CRI = cast<CleanupReturnInst>(I);
1943 pushValue(CRI.getCleanupPad(), InstID, Vals, VE);
1944 if (CRI.hasUnwindDest())
1945 Vals.push_back(VE.getValueID(CRI.getUnwindDest()));
1948 case Instruction::CatchRet: {
1949 Code = bitc::FUNC_CODE_INST_CATCHRET;
1950 const auto &CRI = cast<CatchReturnInst>(I);
1951 pushValue(CRI.getCatchPad(), InstID, Vals, VE);
1952 Vals.push_back(VE.getValueID(CRI.getSuccessor()));
1955 case Instruction::CatchPad: {
1956 Code = bitc::FUNC_CODE_INST_CATCHPAD;
1957 const auto &CPI = cast<CatchPadInst>(I);
1958 Vals.push_back(VE.getValueID(CPI.getNormalDest()));
1959 Vals.push_back(VE.getValueID(CPI.getUnwindDest()));
1960 unsigned NumArgOperands = CPI.getNumArgOperands();
1961 Vals.push_back(NumArgOperands);
1962 for (unsigned Op = 0; Op != NumArgOperands; ++Op)
1963 PushValueAndType(CPI.getArgOperand(Op), InstID, Vals, VE);
1966 case Instruction::TerminatePad: {
1967 Code = bitc::FUNC_CODE_INST_TERMINATEPAD;
1968 const auto &TPI = cast<TerminatePadInst>(I);
1969 Vals.push_back(TPI.hasUnwindDest());
1970 if (TPI.hasUnwindDest())
1971 Vals.push_back(VE.getValueID(TPI.getUnwindDest()));
1972 unsigned NumArgOperands = TPI.getNumArgOperands();
1973 Vals.push_back(NumArgOperands);
1974 for (unsigned Op = 0; Op != NumArgOperands; ++Op)
1975 PushValueAndType(TPI.getArgOperand(Op), InstID, Vals, VE);
1978 case Instruction::CleanupPad: {
1979 Code = bitc::FUNC_CODE_INST_CLEANUPPAD;
1980 const auto &CPI = cast<CleanupPadInst>(I);
1981 unsigned NumOperands = CPI.getNumOperands();
1982 Vals.push_back(NumOperands);
1983 for (unsigned Op = 0; Op != NumOperands; ++Op)
1984 PushValueAndType(CPI.getOperand(Op), InstID, Vals, VE);
1987 case Instruction::CatchEndPad: {
1988 Code = bitc::FUNC_CODE_INST_CATCHENDPAD;
1989 const auto &CEPI = cast<CatchEndPadInst>(I);
1990 if (CEPI.hasUnwindDest())
1991 Vals.push_back(VE.getValueID(CEPI.getUnwindDest()));
1994 case Instruction::CleanupEndPad: {
1995 Code = bitc::FUNC_CODE_INST_CLEANUPENDPAD;
1996 const auto &CEPI = cast<CleanupEndPadInst>(I);
1997 pushValue(CEPI.getCleanupPad(), InstID, Vals, VE);
1998 if (CEPI.hasUnwindDest())
1999 Vals.push_back(VE.getValueID(CEPI.getUnwindDest()));
2002 case Instruction::Unreachable:
2003 Code = bitc::FUNC_CODE_INST_UNREACHABLE;
2004 AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
2007 case Instruction::PHI: {
2008 const PHINode &PN = cast<PHINode>(I);
2009 Code = bitc::FUNC_CODE_INST_PHI;
2010 // With the newer instruction encoding, forward references could give
2011 // negative valued IDs. This is most common for PHIs, so we use
2013 SmallVector<uint64_t, 128> Vals64;
2014 Vals64.push_back(VE.getTypeID(PN.getType()));
2015 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
2016 pushValueSigned(PN.getIncomingValue(i), InstID, Vals64, VE);
2017 Vals64.push_back(VE.getValueID(PN.getIncomingBlock(i)));
2019 // Emit a Vals64 vector and exit.
2020 Stream.EmitRecord(Code, Vals64, AbbrevToUse);
2025 case Instruction::LandingPad: {
2026 const LandingPadInst &LP = cast<LandingPadInst>(I);
2027 Code = bitc::FUNC_CODE_INST_LANDINGPAD;
2028 Vals.push_back(VE.getTypeID(LP.getType()));
2029 Vals.push_back(LP.isCleanup());
2030 Vals.push_back(LP.getNumClauses());
2031 for (unsigned I = 0, E = LP.getNumClauses(); I != E; ++I) {
2033 Vals.push_back(LandingPadInst::Catch);
2035 Vals.push_back(LandingPadInst::Filter);
2036 PushValueAndType(LP.getClause(I), InstID, Vals, VE);
2041 case Instruction::Alloca: {
2042 Code = bitc::FUNC_CODE_INST_ALLOCA;
2043 const AllocaInst &AI = cast<AllocaInst>(I);
2044 Vals.push_back(VE.getTypeID(AI.getAllocatedType()));
2045 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
2046 Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
2047 unsigned AlignRecord = Log2_32(AI.getAlignment()) + 1;
2048 assert(Log2_32(Value::MaximumAlignment) + 1 < 1 << 5 &&
2049 "not enough bits for maximum alignment");
2050 assert(AlignRecord < 1 << 5 && "alignment greater than 1 << 64");
2051 AlignRecord |= AI.isUsedWithInAlloca() << 5;
2052 AlignRecord |= 1 << 6;
2053 // Reserve bit 7 for SwiftError flag.
2054 // AlignRecord |= AI.isSwiftError() << 7;
2055 Vals.push_back(AlignRecord);
2059 case Instruction::Load:
2060 if (cast<LoadInst>(I).isAtomic()) {
2061 Code = bitc::FUNC_CODE_INST_LOADATOMIC;
2062 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
2064 Code = bitc::FUNC_CODE_INST_LOAD;
2065 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE)) // ptr
2066 AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
2068 Vals.push_back(VE.getTypeID(I.getType()));
2069 Vals.push_back(Log2_32(cast<LoadInst>(I).getAlignment())+1);
2070 Vals.push_back(cast<LoadInst>(I).isVolatile());
2071 if (cast<LoadInst>(I).isAtomic()) {
2072 Vals.push_back(GetEncodedOrdering(cast<LoadInst>(I).getOrdering()));
2073 Vals.push_back(GetEncodedSynchScope(cast<LoadInst>(I).getSynchScope()));
2076 case Instruction::Store:
2077 if (cast<StoreInst>(I).isAtomic())
2078 Code = bitc::FUNC_CODE_INST_STOREATOMIC;
2080 Code = bitc::FUNC_CODE_INST_STORE;
2081 PushValueAndType(I.getOperand(1), InstID, Vals, VE); // ptrty + ptr
2082 PushValueAndType(I.getOperand(0), InstID, Vals, VE); // valty + val
2083 Vals.push_back(Log2_32(cast<StoreInst>(I).getAlignment())+1);
2084 Vals.push_back(cast<StoreInst>(I).isVolatile());
2085 if (cast<StoreInst>(I).isAtomic()) {
2086 Vals.push_back(GetEncodedOrdering(cast<StoreInst>(I).getOrdering()));
2087 Vals.push_back(GetEncodedSynchScope(cast<StoreInst>(I).getSynchScope()));
2090 case Instruction::AtomicCmpXchg:
2091 Code = bitc::FUNC_CODE_INST_CMPXCHG;
2092 PushValueAndType(I.getOperand(0), InstID, Vals, VE); // ptrty + ptr
2093 PushValueAndType(I.getOperand(1), InstID, Vals, VE); // cmp.
2094 pushValue(I.getOperand(2), InstID, Vals, VE); // newval.
2095 Vals.push_back(cast<AtomicCmpXchgInst>(I).isVolatile());
2096 Vals.push_back(GetEncodedOrdering(
2097 cast<AtomicCmpXchgInst>(I).getSuccessOrdering()));
2098 Vals.push_back(GetEncodedSynchScope(
2099 cast<AtomicCmpXchgInst>(I).getSynchScope()));
2100 Vals.push_back(GetEncodedOrdering(
2101 cast<AtomicCmpXchgInst>(I).getFailureOrdering()));
2102 Vals.push_back(cast<AtomicCmpXchgInst>(I).isWeak());
2104 case Instruction::AtomicRMW:
2105 Code = bitc::FUNC_CODE_INST_ATOMICRMW;
2106 PushValueAndType(I.getOperand(0), InstID, Vals, VE); // ptrty + ptr
2107 pushValue(I.getOperand(1), InstID, Vals, VE); // val.
2108 Vals.push_back(GetEncodedRMWOperation(
2109 cast<AtomicRMWInst>(I).getOperation()));
2110 Vals.push_back(cast<AtomicRMWInst>(I).isVolatile());
2111 Vals.push_back(GetEncodedOrdering(cast<AtomicRMWInst>(I).getOrdering()));
2112 Vals.push_back(GetEncodedSynchScope(
2113 cast<AtomicRMWInst>(I).getSynchScope()));
2115 case Instruction::Fence:
2116 Code = bitc::FUNC_CODE_INST_FENCE;
2117 Vals.push_back(GetEncodedOrdering(cast<FenceInst>(I).getOrdering()));
2118 Vals.push_back(GetEncodedSynchScope(cast<FenceInst>(I).getSynchScope()));
2120 case Instruction::Call: {
2121 const CallInst &CI = cast<CallInst>(I);
2122 FunctionType *FTy = CI.getFunctionType();
2124 if (CI.hasOperandBundles())
2125 WriteOperandBundles(Stream, &CI, InstID, VE);
2127 Code = bitc::FUNC_CODE_INST_CALL;
2129 Vals.push_back(VE.getAttributeID(CI.getAttributes()));
2130 Vals.push_back((CI.getCallingConv() << 1) | unsigned(CI.isTailCall()) |
2131 unsigned(CI.isMustTailCall()) << 14 | 1 << 15);
2132 Vals.push_back(VE.getTypeID(FTy));
2133 PushValueAndType(CI.getCalledValue(), InstID, Vals, VE); // Callee
2135 // Emit value #'s for the fixed parameters.
2136 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
2137 // Check for labels (can happen with asm labels).
2138 if (FTy->getParamType(i)->isLabelTy())
2139 Vals.push_back(VE.getValueID(CI.getArgOperand(i)));
2141 pushValue(CI.getArgOperand(i), InstID, Vals, VE); // fixed param.
2144 // Emit type/value pairs for varargs params.
2145 if (FTy->isVarArg()) {
2146 for (unsigned i = FTy->getNumParams(), e = CI.getNumArgOperands();
2148 PushValueAndType(CI.getArgOperand(i), InstID, Vals, VE); // varargs
2152 case Instruction::VAArg:
2153 Code = bitc::FUNC_CODE_INST_VAARG;
2154 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); // valistty
2155 pushValue(I.getOperand(0), InstID, Vals, VE); // valist.
2156 Vals.push_back(VE.getTypeID(I.getType())); // restype.
2160 Stream.EmitRecord(Code, Vals, AbbrevToUse);
2164 enum StringEncoding { SE_Char6, SE_Fixed7, SE_Fixed8 };
2166 /// Determine the encoding to use for the given string name and length.
2167 static StringEncoding getStringEncoding(const char *Str, unsigned StrLen) {
2168 bool isChar6 = true;
2169 for (const char *C = Str, *E = C + StrLen; C != E; ++C) {
2171 isChar6 = BitCodeAbbrevOp::isChar6(*C);
2172 if ((unsigned char)*C & 128)
2173 // don't bother scanning the rest.
2182 /// Emit names for globals/functions etc. The VSTOffsetPlaceholder,
2183 /// BitcodeStartBit and FunctionIndex are only passed for the module-level
2184 /// VST, where we are including a function bitcode index and need to
2185 /// backpatch the VST forward declaration record.
2186 static void WriteValueSymbolTable(
2187 const ValueSymbolTable &VST, const ValueEnumerator &VE,
2188 BitstreamWriter &Stream, uint64_t VSTOffsetPlaceholder = 0,
2189 uint64_t BitcodeStartBit = 0,
2190 DenseMap<const Function *, uint64_t> *FunctionIndex = nullptr) {
2192 // WriteValueSymbolTableForwardDecl should have returned early as
2193 // well. Ensure this handling remains in sync by asserting that
2194 // the placeholder offset is not set.
2195 assert(VSTOffsetPlaceholder == 0);
2199 if (VSTOffsetPlaceholder > 0) {
2200 // Get the offset of the VST we are writing, and backpatch it into
2201 // the VST forward declaration record.
2202 uint64_t VSTOffset = Stream.GetCurrentBitNo();
2203 // The BitcodeStartBit was the stream offset of the actual bitcode
2204 // (e.g. excluding any initial darwin header).
2205 VSTOffset -= BitcodeStartBit;
2206 assert((VSTOffset & 31) == 0 && "VST block not 32-bit aligned");
2207 Stream.BackpatchWord(VSTOffsetPlaceholder, VSTOffset / 32);
2210 Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
2212 // For the module-level VST, add abbrev Ids for the VST_CODE_FNENTRY
2213 // records, which are not used in the per-function VSTs.
2214 unsigned FnEntry8BitAbbrev;
2215 unsigned FnEntry7BitAbbrev;
2216 unsigned FnEntry6BitAbbrev;
2217 if (VSTOffsetPlaceholder > 0) {
2218 // 8-bit fixed-width VST_FNENTRY function strings.
2219 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2220 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_FNENTRY));
2221 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
2222 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // funcoffset
2223 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2224 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
2225 FnEntry8BitAbbrev = Stream.EmitAbbrev(Abbv);
2227 // 7-bit fixed width VST_FNENTRY function strings.
2228 Abbv = new BitCodeAbbrev();
2229 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_FNENTRY));
2230 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
2231 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // funcoffset
2232 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2233 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
2234 FnEntry7BitAbbrev = Stream.EmitAbbrev(Abbv);
2236 // 6-bit char6 VST_FNENTRY function strings.
2237 Abbv = new BitCodeAbbrev();
2238 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_FNENTRY));
2239 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
2240 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // funcoffset
2241 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2242 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
2243 FnEntry6BitAbbrev = Stream.EmitAbbrev(Abbv);
2246 // FIXME: Set up the abbrev, we know how many values there are!
2247 // FIXME: We know if the type names can use 7-bit ascii.
2248 SmallVector<unsigned, 64> NameVals;
2250 for (const ValueName &Name : VST) {
2251 // Figure out the encoding to use for the name.
2252 StringEncoding Bits =
2253 getStringEncoding(Name.getKeyData(), Name.getKeyLength());
2255 unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
2256 NameVals.push_back(VE.getValueID(Name.getValue()));
2258 Function *F = dyn_cast<Function>(Name.getValue());
2260 // If value is an alias, need to get the aliased base object to
2261 // see if it is a function.
2262 auto *GA = dyn_cast<GlobalAlias>(Name.getValue());
2263 if (GA && GA->getBaseObject())
2264 F = dyn_cast<Function>(GA->getBaseObject());
2267 // VST_ENTRY: [valueid, namechar x N]
2268 // VST_FNENTRY: [valueid, funcoffset, namechar x N]
2269 // VST_BBENTRY: [bbid, namechar x N]
2271 if (isa<BasicBlock>(Name.getValue())) {
2272 Code = bitc::VST_CODE_BBENTRY;
2273 if (Bits == SE_Char6)
2274 AbbrevToUse = VST_BBENTRY_6_ABBREV;
2275 } else if (F && !F->isDeclaration()) {
2276 // Must be the module-level VST, where we pass in the Index and
2277 // have a VSTOffsetPlaceholder. The function-level VST should not
2278 // contain any Function symbols.
2279 assert(FunctionIndex);
2280 assert(VSTOffsetPlaceholder > 0);
2282 // Save the word offset of the function (from the start of the
2283 // actual bitcode written to the stream).
2284 assert(FunctionIndex->count(F) == 1);
2285 uint64_t BitcodeIndex = (*FunctionIndex)[F] - BitcodeStartBit;
2286 assert((BitcodeIndex & 31) == 0 && "function block not 32-bit aligned");
2287 NameVals.push_back(BitcodeIndex / 32);
2289 Code = bitc::VST_CODE_FNENTRY;
2290 AbbrevToUse = FnEntry8BitAbbrev;
2291 if (Bits == SE_Char6)
2292 AbbrevToUse = FnEntry6BitAbbrev;
2293 else if (Bits == SE_Fixed7)
2294 AbbrevToUse = FnEntry7BitAbbrev;
2296 Code = bitc::VST_CODE_ENTRY;
2297 if (Bits == SE_Char6)
2298 AbbrevToUse = VST_ENTRY_6_ABBREV;
2299 else if (Bits == SE_Fixed7)
2300 AbbrevToUse = VST_ENTRY_7_ABBREV;
2303 for (const char *P = Name.getKeyData(),
2304 *E = Name.getKeyData()+Name.getKeyLength(); P != E; ++P)
2305 NameVals.push_back((unsigned char)*P);
2307 // Emit the finished record.
2308 Stream.EmitRecord(Code, NameVals, AbbrevToUse);
2314 static void WriteUseList(ValueEnumerator &VE, UseListOrder &&Order,
2315 BitstreamWriter &Stream) {
2316 assert(Order.Shuffle.size() >= 2 && "Shuffle too small");
2318 if (isa<BasicBlock>(Order.V))
2319 Code = bitc::USELIST_CODE_BB;
2321 Code = bitc::USELIST_CODE_DEFAULT;
2323 SmallVector<uint64_t, 64> Record(Order.Shuffle.begin(), Order.Shuffle.end());
2324 Record.push_back(VE.getValueID(Order.V));
2325 Stream.EmitRecord(Code, Record);
2328 static void WriteUseListBlock(const Function *F, ValueEnumerator &VE,
2329 BitstreamWriter &Stream) {
2330 assert(VE.shouldPreserveUseListOrder() &&
2331 "Expected to be preserving use-list order");
2333 auto hasMore = [&]() {
2334 return !VE.UseListOrders.empty() && VE.UseListOrders.back().F == F;
2340 Stream.EnterSubblock(bitc::USELIST_BLOCK_ID, 3);
2342 WriteUseList(VE, std::move(VE.UseListOrders.back()), Stream);
2343 VE.UseListOrders.pop_back();
2348 /// WriteFunction - Emit a function body to the module stream.
2349 static void WriteFunction(const Function &F, ValueEnumerator &VE,
2350 BitstreamWriter &Stream,
2351 DenseMap<const Function *, uint64_t> &FunctionIndex) {
2352 // Save the bitcode index of the start of this function block for recording
2354 uint64_t BitcodeIndex = Stream.GetCurrentBitNo();
2355 FunctionIndex[&F] = BitcodeIndex;
2357 Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 4);
2358 VE.incorporateFunction(F);
2360 SmallVector<unsigned, 64> Vals;
2362 // Emit the number of basic blocks, so the reader can create them ahead of
2364 Vals.push_back(VE.getBasicBlocks().size());
2365 Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals);
2368 // If there are function-local constants, emit them now.
2369 unsigned CstStart, CstEnd;
2370 VE.getFunctionConstantRange(CstStart, CstEnd);
2371 WriteConstants(CstStart, CstEnd, VE, Stream, false);
2373 // If there is function-local metadata, emit it now.
2374 WriteFunctionLocalMetadata(F, VE, Stream);
2376 // Keep a running idea of what the instruction ID is.
2377 unsigned InstID = CstEnd;
2379 bool NeedsMetadataAttachment = F.hasMetadata();
2381 DILocation *LastDL = nullptr;
2383 // Finally, emit all the instructions, in order.
2384 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
2385 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
2387 WriteInstruction(*I, InstID, VE, Stream, Vals);
2389 if (!I->getType()->isVoidTy())
2392 // If the instruction has metadata, write a metadata attachment later.
2393 NeedsMetadataAttachment |= I->hasMetadataOtherThanDebugLoc();
2395 // If the instruction has a debug location, emit it.
2396 DILocation *DL = I->getDebugLoc();
2401 // Just repeat the same debug loc as last time.
2402 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC_AGAIN, Vals);
2406 Vals.push_back(DL->getLine());
2407 Vals.push_back(DL->getColumn());
2408 Vals.push_back(VE.getMetadataOrNullID(DL->getScope()));
2409 Vals.push_back(VE.getMetadataOrNullID(DL->getInlinedAt()));
2410 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC, Vals);
2416 // Emit names for all the instructions etc.
2417 WriteValueSymbolTable(F.getValueSymbolTable(), VE, Stream);
2419 if (NeedsMetadataAttachment)
2420 WriteMetadataAttachment(F, VE, Stream);
2421 if (VE.shouldPreserveUseListOrder())
2422 WriteUseListBlock(&F, VE, Stream);
2427 // Emit blockinfo, which defines the standard abbreviations etc.
2428 static void WriteBlockInfo(const ValueEnumerator &VE, BitstreamWriter &Stream) {
2429 // We only want to emit block info records for blocks that have multiple
2430 // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK.
2431 // Other blocks can define their abbrevs inline.
2432 Stream.EnterBlockInfoBlock(2);
2434 { // 8-bit fixed-width VST_ENTRY/VST_BBENTRY strings.
2435 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2436 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3));
2437 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2438 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2439 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
2440 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
2441 Abbv) != VST_ENTRY_8_ABBREV)
2442 llvm_unreachable("Unexpected abbrev ordering!");
2445 { // 7-bit fixed width VST_ENTRY strings.
2446 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2447 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
2448 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2449 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2450 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
2451 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
2452 Abbv) != VST_ENTRY_7_ABBREV)
2453 llvm_unreachable("Unexpected abbrev ordering!");
2455 { // 6-bit char6 VST_ENTRY strings.
2456 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2457 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
2458 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2459 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2460 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
2461 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
2462 Abbv) != VST_ENTRY_6_ABBREV)
2463 llvm_unreachable("Unexpected abbrev ordering!");
2465 { // 6-bit char6 VST_BBENTRY strings.
2466 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2467 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY));
2468 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2469 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2470 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
2471 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
2472 Abbv) != VST_BBENTRY_6_ABBREV)
2473 llvm_unreachable("Unexpected abbrev ordering!");
2478 { // SETTYPE abbrev for CONSTANTS_BLOCK.
2479 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2480 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_SETTYPE));
2481 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
2482 VE.computeBitsRequiredForTypeIndicies()));
2483 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
2484 Abbv) != CONSTANTS_SETTYPE_ABBREV)
2485 llvm_unreachable("Unexpected abbrev ordering!");
2488 { // INTEGER abbrev for CONSTANTS_BLOCK.
2489 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2490 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_INTEGER));
2491 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2492 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
2493 Abbv) != CONSTANTS_INTEGER_ABBREV)
2494 llvm_unreachable("Unexpected abbrev ordering!");
2497 { // CE_CAST abbrev for CONSTANTS_BLOCK.
2498 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2499 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CE_CAST));
2500 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // cast opc
2501 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // typeid
2502 VE.computeBitsRequiredForTypeIndicies()));
2503 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
2505 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
2506 Abbv) != CONSTANTS_CE_CAST_Abbrev)
2507 llvm_unreachable("Unexpected abbrev ordering!");
2509 { // NULL abbrev for CONSTANTS_BLOCK.
2510 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2511 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_NULL));
2512 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
2513 Abbv) != CONSTANTS_NULL_Abbrev)
2514 llvm_unreachable("Unexpected abbrev ordering!");
2517 // FIXME: This should only use space for first class types!
2519 { // INST_LOAD abbrev for FUNCTION_BLOCK.
2520 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2521 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_LOAD));
2522 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Ptr
2523 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
2524 VE.computeBitsRequiredForTypeIndicies()));
2525 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align
2526 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile
2527 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
2528 Abbv) != FUNCTION_INST_LOAD_ABBREV)
2529 llvm_unreachable("Unexpected abbrev ordering!");
2531 { // INST_BINOP abbrev for FUNCTION_BLOCK.
2532 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2533 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
2534 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
2535 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
2536 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
2537 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
2538 Abbv) != FUNCTION_INST_BINOP_ABBREV)
2539 llvm_unreachable("Unexpected abbrev ordering!");
2541 { // INST_BINOP_FLAGS abbrev for FUNCTION_BLOCK.
2542 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2543 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
2544 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
2545 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
2546 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
2547 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7)); // flags
2548 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
2549 Abbv) != FUNCTION_INST_BINOP_FLAGS_ABBREV)
2550 llvm_unreachable("Unexpected abbrev ordering!");
2552 { // INST_CAST abbrev for FUNCTION_BLOCK.
2553 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2554 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST));
2555 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // OpVal
2556 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
2557 VE.computeBitsRequiredForTypeIndicies()));
2558 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
2559 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
2560 Abbv) != FUNCTION_INST_CAST_ABBREV)
2561 llvm_unreachable("Unexpected abbrev ordering!");
2564 { // INST_RET abbrev for FUNCTION_BLOCK.
2565 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2566 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
2567 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
2568 Abbv) != FUNCTION_INST_RET_VOID_ABBREV)
2569 llvm_unreachable("Unexpected abbrev ordering!");
2571 { // INST_RET abbrev for FUNCTION_BLOCK.
2572 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2573 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
2574 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ValID
2575 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
2576 Abbv) != FUNCTION_INST_RET_VAL_ABBREV)
2577 llvm_unreachable("Unexpected abbrev ordering!");
2579 { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK.
2580 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2581 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNREACHABLE));
2582 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
2583 Abbv) != FUNCTION_INST_UNREACHABLE_ABBREV)
2584 llvm_unreachable("Unexpected abbrev ordering!");
2587 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2588 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_GEP));
2589 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
2590 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
2591 Log2_32_Ceil(VE.getTypes().size() + 1)));
2592 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2593 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
2594 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
2595 FUNCTION_INST_GEP_ABBREV)
2596 llvm_unreachable("Unexpected abbrev ordering!");
2602 /// WriteModule - Emit the specified module to the bitstream.
2603 static void WriteModule(const Module *M, BitstreamWriter &Stream,
2604 bool ShouldPreserveUseListOrder,
2605 uint64_t BitcodeStartBit) {
2606 Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
2608 SmallVector<unsigned, 1> Vals;
2609 unsigned CurVersion = 1;
2610 Vals.push_back(CurVersion);
2611 Stream.EmitRecord(bitc::MODULE_CODE_VERSION, Vals);
2613 // Analyze the module, enumerating globals, functions, etc.
2614 ValueEnumerator VE(*M, ShouldPreserveUseListOrder);
2616 // Emit blockinfo, which defines the standard abbreviations etc.
2617 WriteBlockInfo(VE, Stream);
2619 // Emit information about attribute groups.
2620 WriteAttributeGroupTable(VE, Stream);
2622 // Emit information about parameter attributes.
2623 WriteAttributeTable(VE, Stream);
2625 // Emit information describing all of the types in the module.
2626 WriteTypeTable(VE, Stream);
2628 writeComdats(VE, Stream);
2630 // Emit top-level description of module, including target triple, inline asm,
2631 // descriptors for global variables, and function prototype info.
2632 uint64_t VSTOffsetPlaceholder = WriteModuleInfo(M, VE, Stream);
2635 WriteModuleConstants(VE, Stream);
2638 WriteModuleMetadata(M, VE, Stream);
2641 WriteModuleMetadataStore(M, Stream);
2643 // Emit module-level use-lists.
2644 if (VE.shouldPreserveUseListOrder())
2645 WriteUseListBlock(nullptr, VE, Stream);
2647 WriteOperandBundleTags(M, Stream);
2649 // Emit function bodies.
2650 DenseMap<const Function *, uint64_t> FunctionIndex;
2651 for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F)
2652 if (!F->isDeclaration())
2653 WriteFunction(*F, VE, Stream, FunctionIndex);
2655 WriteValueSymbolTable(M->getValueSymbolTable(), VE, Stream,
2656 VSTOffsetPlaceholder, BitcodeStartBit, &FunctionIndex);
2661 /// EmitDarwinBCHeader - If generating a bc file on darwin, we have to emit a
2662 /// header and trailer to make it compatible with the system archiver. To do
2663 /// this we emit the following header, and then emit a trailer that pads the
2664 /// file out to be a multiple of 16 bytes.
2666 /// struct bc_header {
2667 /// uint32_t Magic; // 0x0B17C0DE
2668 /// uint32_t Version; // Version, currently always 0.
2669 /// uint32_t BitcodeOffset; // Offset to traditional bitcode file.
2670 /// uint32_t BitcodeSize; // Size of traditional bitcode file.
2671 /// uint32_t CPUType; // CPU specifier.
2672 /// ... potentially more later ...
2675 DarwinBCSizeFieldOffset = 3*4, // Offset to bitcode_size.
2676 DarwinBCHeaderSize = 5*4
2679 static void WriteInt32ToBuffer(uint32_t Value, SmallVectorImpl<char> &Buffer,
2680 uint32_t &Position) {
2681 support::endian::write32le(&Buffer[Position], Value);
2685 static void EmitDarwinBCHeaderAndTrailer(SmallVectorImpl<char> &Buffer,
2687 unsigned CPUType = ~0U;
2689 // Match x86_64-*, i[3-9]86-*, powerpc-*, powerpc64-*, arm-*, thumb-*,
2690 // armv[0-9]-*, thumbv[0-9]-*, armv5te-*, or armv6t2-*. The CPUType is a magic
2691 // number from /usr/include/mach/machine.h. It is ok to reproduce the
2692 // specific constants here because they are implicitly part of the Darwin ABI.
2694 DARWIN_CPU_ARCH_ABI64 = 0x01000000,
2695 DARWIN_CPU_TYPE_X86 = 7,
2696 DARWIN_CPU_TYPE_ARM = 12,
2697 DARWIN_CPU_TYPE_POWERPC = 18
2700 Triple::ArchType Arch = TT.getArch();
2701 if (Arch == Triple::x86_64)
2702 CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64;
2703 else if (Arch == Triple::x86)
2704 CPUType = DARWIN_CPU_TYPE_X86;
2705 else if (Arch == Triple::ppc)
2706 CPUType = DARWIN_CPU_TYPE_POWERPC;
2707 else if (Arch == Triple::ppc64)
2708 CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64;
2709 else if (Arch == Triple::arm || Arch == Triple::thumb)
2710 CPUType = DARWIN_CPU_TYPE_ARM;
2712 // Traditional Bitcode starts after header.
2713 assert(Buffer.size() >= DarwinBCHeaderSize &&
2714 "Expected header size to be reserved");
2715 unsigned BCOffset = DarwinBCHeaderSize;
2716 unsigned BCSize = Buffer.size()-DarwinBCHeaderSize;
2718 // Write the magic and version.
2719 unsigned Position = 0;
2720 WriteInt32ToBuffer(0x0B17C0DE , Buffer, Position);
2721 WriteInt32ToBuffer(0 , Buffer, Position); // Version.
2722 WriteInt32ToBuffer(BCOffset , Buffer, Position);
2723 WriteInt32ToBuffer(BCSize , Buffer, Position);
2724 WriteInt32ToBuffer(CPUType , Buffer, Position);
2726 // If the file is not a multiple of 16 bytes, insert dummy padding.
2727 while (Buffer.size() & 15)
2728 Buffer.push_back(0);
2731 /// WriteBitcodeToFile - Write the specified module to the specified output
2733 void llvm::WriteBitcodeToFile(const Module *M, raw_ostream &Out,
2734 bool ShouldPreserveUseListOrder) {
2735 SmallVector<char, 0> Buffer;
2736 Buffer.reserve(256*1024);
2738 // If this is darwin or another generic macho target, reserve space for the
2740 Triple TT(M->getTargetTriple());
2741 if (TT.isOSDarwin())
2742 Buffer.insert(Buffer.begin(), DarwinBCHeaderSize, 0);
2744 // Emit the module into the buffer.
2746 BitstreamWriter Stream(Buffer);
2747 // Save the start bit of the actual bitcode, in case there is space
2748 // saved at the start for the darwin header above. The reader stream
2749 // will start at the bitcode, and we need the offset of the VST
2751 uint64_t BitcodeStartBit = Stream.GetCurrentBitNo();
2753 // Emit the file header.
2754 Stream.Emit((unsigned)'B', 8);
2755 Stream.Emit((unsigned)'C', 8);
2756 Stream.Emit(0x0, 4);
2757 Stream.Emit(0xC, 4);
2758 Stream.Emit(0xE, 4);
2759 Stream.Emit(0xD, 4);
2762 WriteModule(M, Stream, ShouldPreserveUseListOrder, BitcodeStartBit);
2765 if (TT.isOSDarwin())
2766 EmitDarwinBCHeaderAndTrailer(Buffer, TT);
2768 // Write the generated bitstream to "Out".
2769 Out.write((char*)&Buffer.front(), Buffer.size());