1 //===--- Bitcode/Writer/BitcodeWriter.cpp - Bitcode Writer ----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Bitcode writer implementation.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Bitcode/ReaderWriter.h"
15 #include "ValueEnumerator.h"
16 #include "llvm/ADT/Triple.h"
17 #include "llvm/Bitcode/BitstreamWriter.h"
18 #include "llvm/Bitcode/LLVMBitCodes.h"
19 #include "llvm/IR/Constants.h"
20 #include "llvm/IR/DerivedTypes.h"
21 #include "llvm/IR/InlineAsm.h"
22 #include "llvm/IR/Instructions.h"
23 #include "llvm/IR/Module.h"
24 #include "llvm/IR/Operator.h"
25 #include "llvm/IR/UseListOrder.h"
26 #include "llvm/IR/ValueSymbolTable.h"
27 #include "llvm/Support/CommandLine.h"
28 #include "llvm/Support/ErrorHandling.h"
29 #include "llvm/Support/MathExtras.h"
30 #include "llvm/Support/Program.h"
31 #include "llvm/Support/raw_ostream.h"
36 /// These are manifest constants used by the bitcode writer. They do not need to
37 /// be kept in sync with the reader, but need to be consistent within this file.
39 // VALUE_SYMTAB_BLOCK abbrev id's.
40 VST_ENTRY_8_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
45 // CONSTANTS_BLOCK abbrev id's.
46 CONSTANTS_SETTYPE_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
47 CONSTANTS_INTEGER_ABBREV,
48 CONSTANTS_CE_CAST_Abbrev,
49 CONSTANTS_NULL_Abbrev,
51 // FUNCTION_BLOCK abbrev id's.
52 FUNCTION_INST_LOAD_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
53 FUNCTION_INST_BINOP_ABBREV,
54 FUNCTION_INST_BINOP_FLAGS_ABBREV,
55 FUNCTION_INST_CAST_ABBREV,
56 FUNCTION_INST_RET_VOID_ABBREV,
57 FUNCTION_INST_RET_VAL_ABBREV,
58 FUNCTION_INST_UNREACHABLE_ABBREV
61 static unsigned GetEncodedCastOpcode(unsigned Opcode) {
63 default: llvm_unreachable("Unknown cast instruction!");
64 case Instruction::Trunc : return bitc::CAST_TRUNC;
65 case Instruction::ZExt : return bitc::CAST_ZEXT;
66 case Instruction::SExt : return bitc::CAST_SEXT;
67 case Instruction::FPToUI : return bitc::CAST_FPTOUI;
68 case Instruction::FPToSI : return bitc::CAST_FPTOSI;
69 case Instruction::UIToFP : return bitc::CAST_UITOFP;
70 case Instruction::SIToFP : return bitc::CAST_SITOFP;
71 case Instruction::FPTrunc : return bitc::CAST_FPTRUNC;
72 case Instruction::FPExt : return bitc::CAST_FPEXT;
73 case Instruction::PtrToInt: return bitc::CAST_PTRTOINT;
74 case Instruction::IntToPtr: return bitc::CAST_INTTOPTR;
75 case Instruction::BitCast : return bitc::CAST_BITCAST;
76 case Instruction::AddrSpaceCast: return bitc::CAST_ADDRSPACECAST;
80 static unsigned GetEncodedBinaryOpcode(unsigned Opcode) {
82 default: llvm_unreachable("Unknown binary instruction!");
83 case Instruction::Add:
84 case Instruction::FAdd: return bitc::BINOP_ADD;
85 case Instruction::Sub:
86 case Instruction::FSub: return bitc::BINOP_SUB;
87 case Instruction::Mul:
88 case Instruction::FMul: return bitc::BINOP_MUL;
89 case Instruction::UDiv: return bitc::BINOP_UDIV;
90 case Instruction::FDiv:
91 case Instruction::SDiv: return bitc::BINOP_SDIV;
92 case Instruction::URem: return bitc::BINOP_UREM;
93 case Instruction::FRem:
94 case Instruction::SRem: return bitc::BINOP_SREM;
95 case Instruction::Shl: return bitc::BINOP_SHL;
96 case Instruction::LShr: return bitc::BINOP_LSHR;
97 case Instruction::AShr: return bitc::BINOP_ASHR;
98 case Instruction::And: return bitc::BINOP_AND;
99 case Instruction::Or: return bitc::BINOP_OR;
100 case Instruction::Xor: return bitc::BINOP_XOR;
104 static unsigned GetEncodedRMWOperation(AtomicRMWInst::BinOp Op) {
106 default: llvm_unreachable("Unknown RMW operation!");
107 case AtomicRMWInst::Xchg: return bitc::RMW_XCHG;
108 case AtomicRMWInst::Add: return bitc::RMW_ADD;
109 case AtomicRMWInst::Sub: return bitc::RMW_SUB;
110 case AtomicRMWInst::And: return bitc::RMW_AND;
111 case AtomicRMWInst::Nand: return bitc::RMW_NAND;
112 case AtomicRMWInst::Or: return bitc::RMW_OR;
113 case AtomicRMWInst::Xor: return bitc::RMW_XOR;
114 case AtomicRMWInst::Max: return bitc::RMW_MAX;
115 case AtomicRMWInst::Min: return bitc::RMW_MIN;
116 case AtomicRMWInst::UMax: return bitc::RMW_UMAX;
117 case AtomicRMWInst::UMin: return bitc::RMW_UMIN;
121 static unsigned GetEncodedOrdering(AtomicOrdering Ordering) {
123 case NotAtomic: return bitc::ORDERING_NOTATOMIC;
124 case Unordered: return bitc::ORDERING_UNORDERED;
125 case Monotonic: return bitc::ORDERING_MONOTONIC;
126 case Acquire: return bitc::ORDERING_ACQUIRE;
127 case Release: return bitc::ORDERING_RELEASE;
128 case AcquireRelease: return bitc::ORDERING_ACQREL;
129 case SequentiallyConsistent: return bitc::ORDERING_SEQCST;
131 llvm_unreachable("Invalid ordering");
134 static unsigned GetEncodedSynchScope(SynchronizationScope SynchScope) {
135 switch (SynchScope) {
136 case SingleThread: return bitc::SYNCHSCOPE_SINGLETHREAD;
137 case CrossThread: return bitc::SYNCHSCOPE_CROSSTHREAD;
139 llvm_unreachable("Invalid synch scope");
142 static void WriteStringRecord(unsigned Code, StringRef Str,
143 unsigned AbbrevToUse, BitstreamWriter &Stream) {
144 SmallVector<unsigned, 64> Vals;
146 // Code: [strchar x N]
147 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
148 if (AbbrevToUse && !BitCodeAbbrevOp::isChar6(Str[i]))
150 Vals.push_back(Str[i]);
153 // Emit the finished record.
154 Stream.EmitRecord(Code, Vals, AbbrevToUse);
157 static uint64_t getAttrKindEncoding(Attribute::AttrKind Kind) {
159 case Attribute::Alignment:
160 return bitc::ATTR_KIND_ALIGNMENT;
161 case Attribute::AlwaysInline:
162 return bitc::ATTR_KIND_ALWAYS_INLINE;
163 case Attribute::Builtin:
164 return bitc::ATTR_KIND_BUILTIN;
165 case Attribute::ByVal:
166 return bitc::ATTR_KIND_BY_VAL;
167 case Attribute::InAlloca:
168 return bitc::ATTR_KIND_IN_ALLOCA;
169 case Attribute::Cold:
170 return bitc::ATTR_KIND_COLD;
171 case Attribute::InlineHint:
172 return bitc::ATTR_KIND_INLINE_HINT;
173 case Attribute::InReg:
174 return bitc::ATTR_KIND_IN_REG;
175 case Attribute::JumpTable:
176 return bitc::ATTR_KIND_JUMP_TABLE;
177 case Attribute::MinSize:
178 return bitc::ATTR_KIND_MIN_SIZE;
179 case Attribute::Naked:
180 return bitc::ATTR_KIND_NAKED;
181 case Attribute::Nest:
182 return bitc::ATTR_KIND_NEST;
183 case Attribute::NoAlias:
184 return bitc::ATTR_KIND_NO_ALIAS;
185 case Attribute::NoBuiltin:
186 return bitc::ATTR_KIND_NO_BUILTIN;
187 case Attribute::NoCapture:
188 return bitc::ATTR_KIND_NO_CAPTURE;
189 case Attribute::NoDuplicate:
190 return bitc::ATTR_KIND_NO_DUPLICATE;
191 case Attribute::NoImplicitFloat:
192 return bitc::ATTR_KIND_NO_IMPLICIT_FLOAT;
193 case Attribute::NoInline:
194 return bitc::ATTR_KIND_NO_INLINE;
195 case Attribute::NonLazyBind:
196 return bitc::ATTR_KIND_NON_LAZY_BIND;
197 case Attribute::NonNull:
198 return bitc::ATTR_KIND_NON_NULL;
199 case Attribute::Dereferenceable:
200 return bitc::ATTR_KIND_DEREFERENCEABLE;
201 case Attribute::NoRedZone:
202 return bitc::ATTR_KIND_NO_RED_ZONE;
203 case Attribute::NoReturn:
204 return bitc::ATTR_KIND_NO_RETURN;
205 case Attribute::NoUnwind:
206 return bitc::ATTR_KIND_NO_UNWIND;
207 case Attribute::OptimizeForSize:
208 return bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE;
209 case Attribute::OptimizeNone:
210 return bitc::ATTR_KIND_OPTIMIZE_NONE;
211 case Attribute::ReadNone:
212 return bitc::ATTR_KIND_READ_NONE;
213 case Attribute::ReadOnly:
214 return bitc::ATTR_KIND_READ_ONLY;
215 case Attribute::Returned:
216 return bitc::ATTR_KIND_RETURNED;
217 case Attribute::ReturnsTwice:
218 return bitc::ATTR_KIND_RETURNS_TWICE;
219 case Attribute::SExt:
220 return bitc::ATTR_KIND_S_EXT;
221 case Attribute::StackAlignment:
222 return bitc::ATTR_KIND_STACK_ALIGNMENT;
223 case Attribute::StackProtect:
224 return bitc::ATTR_KIND_STACK_PROTECT;
225 case Attribute::StackProtectReq:
226 return bitc::ATTR_KIND_STACK_PROTECT_REQ;
227 case Attribute::StackProtectStrong:
228 return bitc::ATTR_KIND_STACK_PROTECT_STRONG;
229 case Attribute::StructRet:
230 return bitc::ATTR_KIND_STRUCT_RET;
231 case Attribute::SanitizeAddress:
232 return bitc::ATTR_KIND_SANITIZE_ADDRESS;
233 case Attribute::SanitizeThread:
234 return bitc::ATTR_KIND_SANITIZE_THREAD;
235 case Attribute::SanitizeMemory:
236 return bitc::ATTR_KIND_SANITIZE_MEMORY;
237 case Attribute::UWTable:
238 return bitc::ATTR_KIND_UW_TABLE;
239 case Attribute::ZExt:
240 return bitc::ATTR_KIND_Z_EXT;
241 case Attribute::EndAttrKinds:
242 llvm_unreachable("Can not encode end-attribute kinds marker.");
243 case Attribute::None:
244 llvm_unreachable("Can not encode none-attribute.");
247 llvm_unreachable("Trying to encode unknown attribute");
250 static void WriteAttributeGroupTable(const ValueEnumerator &VE,
251 BitstreamWriter &Stream) {
252 const std::vector<AttributeSet> &AttrGrps = VE.getAttributeGroups();
253 if (AttrGrps.empty()) return;
255 Stream.EnterSubblock(bitc::PARAMATTR_GROUP_BLOCK_ID, 3);
257 SmallVector<uint64_t, 64> Record;
258 for (unsigned i = 0, e = AttrGrps.size(); i != e; ++i) {
259 AttributeSet AS = AttrGrps[i];
260 for (unsigned i = 0, e = AS.getNumSlots(); i != e; ++i) {
261 AttributeSet A = AS.getSlotAttributes(i);
263 Record.push_back(VE.getAttributeGroupID(A));
264 Record.push_back(AS.getSlotIndex(i));
266 for (AttributeSet::iterator I = AS.begin(0), E = AS.end(0);
269 if (Attr.isEnumAttribute()) {
271 Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
272 } else if (Attr.isIntAttribute()) {
274 Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
275 Record.push_back(Attr.getValueAsInt());
277 StringRef Kind = Attr.getKindAsString();
278 StringRef Val = Attr.getValueAsString();
280 Record.push_back(Val.empty() ? 3 : 4);
281 Record.append(Kind.begin(), Kind.end());
284 Record.append(Val.begin(), Val.end());
290 Stream.EmitRecord(bitc::PARAMATTR_GRP_CODE_ENTRY, Record);
298 static void WriteAttributeTable(const ValueEnumerator &VE,
299 BitstreamWriter &Stream) {
300 const std::vector<AttributeSet> &Attrs = VE.getAttributes();
301 if (Attrs.empty()) return;
303 Stream.EnterSubblock(bitc::PARAMATTR_BLOCK_ID, 3);
305 SmallVector<uint64_t, 64> Record;
306 for (unsigned i = 0, e = Attrs.size(); i != e; ++i) {
307 const AttributeSet &A = Attrs[i];
308 for (unsigned i = 0, e = A.getNumSlots(); i != e; ++i)
309 Record.push_back(VE.getAttributeGroupID(A.getSlotAttributes(i)));
311 Stream.EmitRecord(bitc::PARAMATTR_CODE_ENTRY, Record);
318 /// WriteTypeTable - Write out the type table for a module.
319 static void WriteTypeTable(const ValueEnumerator &VE, BitstreamWriter &Stream) {
320 const ValueEnumerator::TypeList &TypeList = VE.getTypes();
322 Stream.EnterSubblock(bitc::TYPE_BLOCK_ID_NEW, 4 /*count from # abbrevs */);
323 SmallVector<uint64_t, 64> TypeVals;
325 uint64_t NumBits = Log2_32_Ceil(VE.getTypes().size()+1);
327 // Abbrev for TYPE_CODE_POINTER.
328 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
329 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_POINTER));
330 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
331 Abbv->Add(BitCodeAbbrevOp(0)); // Addrspace = 0
332 unsigned PtrAbbrev = Stream.EmitAbbrev(Abbv);
334 // Abbrev for TYPE_CODE_FUNCTION.
335 Abbv = new BitCodeAbbrev();
336 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_FUNCTION));
337 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // isvararg
338 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
339 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
341 unsigned FunctionAbbrev = Stream.EmitAbbrev(Abbv);
343 // Abbrev for TYPE_CODE_STRUCT_ANON.
344 Abbv = new BitCodeAbbrev();
345 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_ANON));
346 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
347 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
348 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
350 unsigned StructAnonAbbrev = Stream.EmitAbbrev(Abbv);
352 // Abbrev for TYPE_CODE_STRUCT_NAME.
353 Abbv = new BitCodeAbbrev();
354 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAME));
355 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
356 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
357 unsigned StructNameAbbrev = Stream.EmitAbbrev(Abbv);
359 // Abbrev for TYPE_CODE_STRUCT_NAMED.
360 Abbv = new BitCodeAbbrev();
361 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAMED));
362 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
363 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
364 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
366 unsigned StructNamedAbbrev = Stream.EmitAbbrev(Abbv);
368 // Abbrev for TYPE_CODE_ARRAY.
369 Abbv = new BitCodeAbbrev();
370 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_ARRAY));
371 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // size
372 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
374 unsigned ArrayAbbrev = Stream.EmitAbbrev(Abbv);
376 // Emit an entry count so the reader can reserve space.
377 TypeVals.push_back(TypeList.size());
378 Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals);
381 // Loop over all of the types, emitting each in turn.
382 for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
383 Type *T = TypeList[i];
387 switch (T->getTypeID()) {
388 case Type::VoidTyID: Code = bitc::TYPE_CODE_VOID; break;
389 case Type::HalfTyID: Code = bitc::TYPE_CODE_HALF; break;
390 case Type::FloatTyID: Code = bitc::TYPE_CODE_FLOAT; break;
391 case Type::DoubleTyID: Code = bitc::TYPE_CODE_DOUBLE; break;
392 case Type::X86_FP80TyID: Code = bitc::TYPE_CODE_X86_FP80; break;
393 case Type::FP128TyID: Code = bitc::TYPE_CODE_FP128; break;
394 case Type::PPC_FP128TyID: Code = bitc::TYPE_CODE_PPC_FP128; break;
395 case Type::LabelTyID: Code = bitc::TYPE_CODE_LABEL; break;
396 case Type::MetadataTyID: Code = bitc::TYPE_CODE_METADATA; break;
397 case Type::X86_MMXTyID: Code = bitc::TYPE_CODE_X86_MMX; break;
398 case Type::IntegerTyID:
400 Code = bitc::TYPE_CODE_INTEGER;
401 TypeVals.push_back(cast<IntegerType>(T)->getBitWidth());
403 case Type::PointerTyID: {
404 PointerType *PTy = cast<PointerType>(T);
405 // POINTER: [pointee type, address space]
406 Code = bitc::TYPE_CODE_POINTER;
407 TypeVals.push_back(VE.getTypeID(PTy->getElementType()));
408 unsigned AddressSpace = PTy->getAddressSpace();
409 TypeVals.push_back(AddressSpace);
410 if (AddressSpace == 0) AbbrevToUse = PtrAbbrev;
413 case Type::FunctionTyID: {
414 FunctionType *FT = cast<FunctionType>(T);
415 // FUNCTION: [isvararg, retty, paramty x N]
416 Code = bitc::TYPE_CODE_FUNCTION;
417 TypeVals.push_back(FT->isVarArg());
418 TypeVals.push_back(VE.getTypeID(FT->getReturnType()));
419 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
420 TypeVals.push_back(VE.getTypeID(FT->getParamType(i)));
421 AbbrevToUse = FunctionAbbrev;
424 case Type::StructTyID: {
425 StructType *ST = cast<StructType>(T);
426 // STRUCT: [ispacked, eltty x N]
427 TypeVals.push_back(ST->isPacked());
428 // Output all of the element types.
429 for (StructType::element_iterator I = ST->element_begin(),
430 E = ST->element_end(); I != E; ++I)
431 TypeVals.push_back(VE.getTypeID(*I));
433 if (ST->isLiteral()) {
434 Code = bitc::TYPE_CODE_STRUCT_ANON;
435 AbbrevToUse = StructAnonAbbrev;
437 if (ST->isOpaque()) {
438 Code = bitc::TYPE_CODE_OPAQUE;
440 Code = bitc::TYPE_CODE_STRUCT_NAMED;
441 AbbrevToUse = StructNamedAbbrev;
444 // Emit the name if it is present.
445 if (!ST->getName().empty())
446 WriteStringRecord(bitc::TYPE_CODE_STRUCT_NAME, ST->getName(),
447 StructNameAbbrev, Stream);
451 case Type::ArrayTyID: {
452 ArrayType *AT = cast<ArrayType>(T);
453 // ARRAY: [numelts, eltty]
454 Code = bitc::TYPE_CODE_ARRAY;
455 TypeVals.push_back(AT->getNumElements());
456 TypeVals.push_back(VE.getTypeID(AT->getElementType()));
457 AbbrevToUse = ArrayAbbrev;
460 case Type::VectorTyID: {
461 VectorType *VT = cast<VectorType>(T);
462 // VECTOR [numelts, eltty]
463 Code = bitc::TYPE_CODE_VECTOR;
464 TypeVals.push_back(VT->getNumElements());
465 TypeVals.push_back(VE.getTypeID(VT->getElementType()));
470 // Emit the finished record.
471 Stream.EmitRecord(Code, TypeVals, AbbrevToUse);
478 static unsigned getEncodedLinkage(const GlobalValue &GV) {
479 switch (GV.getLinkage()) {
480 case GlobalValue::ExternalLinkage:
482 case GlobalValue::WeakAnyLinkage:
484 case GlobalValue::AppendingLinkage:
486 case GlobalValue::InternalLinkage:
488 case GlobalValue::LinkOnceAnyLinkage:
490 case GlobalValue::ExternalWeakLinkage:
492 case GlobalValue::CommonLinkage:
494 case GlobalValue::PrivateLinkage:
496 case GlobalValue::WeakODRLinkage:
498 case GlobalValue::LinkOnceODRLinkage:
500 case GlobalValue::AvailableExternallyLinkage:
503 llvm_unreachable("Invalid linkage");
506 static unsigned getEncodedVisibility(const GlobalValue &GV) {
507 switch (GV.getVisibility()) {
508 case GlobalValue::DefaultVisibility: return 0;
509 case GlobalValue::HiddenVisibility: return 1;
510 case GlobalValue::ProtectedVisibility: return 2;
512 llvm_unreachable("Invalid visibility");
515 static unsigned getEncodedDLLStorageClass(const GlobalValue &GV) {
516 switch (GV.getDLLStorageClass()) {
517 case GlobalValue::DefaultStorageClass: return 0;
518 case GlobalValue::DLLImportStorageClass: return 1;
519 case GlobalValue::DLLExportStorageClass: return 2;
521 llvm_unreachable("Invalid DLL storage class");
524 static unsigned getEncodedThreadLocalMode(const GlobalValue &GV) {
525 switch (GV.getThreadLocalMode()) {
526 case GlobalVariable::NotThreadLocal: return 0;
527 case GlobalVariable::GeneralDynamicTLSModel: return 1;
528 case GlobalVariable::LocalDynamicTLSModel: return 2;
529 case GlobalVariable::InitialExecTLSModel: return 3;
530 case GlobalVariable::LocalExecTLSModel: return 4;
532 llvm_unreachable("Invalid TLS model");
535 static unsigned getEncodedComdatSelectionKind(const Comdat &C) {
536 switch (C.getSelectionKind()) {
538 return bitc::COMDAT_SELECTION_KIND_ANY;
539 case Comdat::ExactMatch:
540 return bitc::COMDAT_SELECTION_KIND_EXACT_MATCH;
541 case Comdat::Largest:
542 return bitc::COMDAT_SELECTION_KIND_LARGEST;
543 case Comdat::NoDuplicates:
544 return bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES;
545 case Comdat::SameSize:
546 return bitc::COMDAT_SELECTION_KIND_SAME_SIZE;
548 llvm_unreachable("Invalid selection kind");
551 static void writeComdats(const ValueEnumerator &VE, BitstreamWriter &Stream) {
552 SmallVector<uint8_t, 64> Vals;
553 for (const Comdat *C : VE.getComdats()) {
554 // COMDAT: [selection_kind, name]
555 Vals.push_back(getEncodedComdatSelectionKind(*C));
556 Vals.push_back(C->getName().size());
557 for (char Chr : C->getName())
558 Vals.push_back((unsigned char)Chr);
559 Stream.EmitRecord(bitc::MODULE_CODE_COMDAT, Vals, /*AbbrevToUse=*/0);
564 // Emit top-level description of module, including target triple, inline asm,
565 // descriptors for global variables, and function prototype info.
566 static void WriteModuleInfo(const Module *M, const ValueEnumerator &VE,
567 BitstreamWriter &Stream) {
568 // Emit various pieces of data attached to a module.
569 if (!M->getTargetTriple().empty())
570 WriteStringRecord(bitc::MODULE_CODE_TRIPLE, M->getTargetTriple(),
572 const std::string &DL = M->getDataLayoutStr();
574 WriteStringRecord(bitc::MODULE_CODE_DATALAYOUT, DL, 0 /*TODO*/, Stream);
575 if (!M->getModuleInlineAsm().empty())
576 WriteStringRecord(bitc::MODULE_CODE_ASM, M->getModuleInlineAsm(),
579 // Emit information about sections and GC, computing how many there are. Also
580 // compute the maximum alignment value.
581 std::map<std::string, unsigned> SectionMap;
582 std::map<std::string, unsigned> GCMap;
583 unsigned MaxAlignment = 0;
584 unsigned MaxGlobalType = 0;
585 for (const GlobalValue &GV : M->globals()) {
586 MaxAlignment = std::max(MaxAlignment, GV.getAlignment());
587 MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV.getType()));
588 if (GV.hasSection()) {
589 // Give section names unique ID's.
590 unsigned &Entry = SectionMap[GV.getSection()];
592 WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, GV.getSection(),
594 Entry = SectionMap.size();
598 for (const Function &F : *M) {
599 MaxAlignment = std::max(MaxAlignment, F.getAlignment());
600 if (F.hasSection()) {
601 // Give section names unique ID's.
602 unsigned &Entry = SectionMap[F.getSection()];
604 WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, F.getSection(),
606 Entry = SectionMap.size();
610 // Same for GC names.
611 unsigned &Entry = GCMap[F.getGC()];
613 WriteStringRecord(bitc::MODULE_CODE_GCNAME, F.getGC(),
615 Entry = GCMap.size();
620 // Emit abbrev for globals, now that we know # sections and max alignment.
621 unsigned SimpleGVarAbbrev = 0;
622 if (!M->global_empty()) {
623 // Add an abbrev for common globals with no visibility or thread localness.
624 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
625 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GLOBALVAR));
626 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
627 Log2_32_Ceil(MaxGlobalType+1)));
628 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Constant.
629 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Initializer.
630 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // Linkage.
631 if (MaxAlignment == 0) // Alignment.
632 Abbv->Add(BitCodeAbbrevOp(0));
634 unsigned MaxEncAlignment = Log2_32(MaxAlignment)+1;
635 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
636 Log2_32_Ceil(MaxEncAlignment+1)));
638 if (SectionMap.empty()) // Section.
639 Abbv->Add(BitCodeAbbrevOp(0));
641 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
642 Log2_32_Ceil(SectionMap.size()+1)));
643 // Don't bother emitting vis + thread local.
644 SimpleGVarAbbrev = Stream.EmitAbbrev(Abbv);
647 // Emit the global variable information.
648 SmallVector<unsigned, 64> Vals;
649 for (const GlobalVariable &GV : M->globals()) {
650 unsigned AbbrevToUse = 0;
652 // GLOBALVAR: [type, isconst, initid,
653 // linkage, alignment, section, visibility, threadlocal,
654 // unnamed_addr, externally_initialized, dllstorageclass]
655 Vals.push_back(VE.getTypeID(GV.getType()));
656 Vals.push_back(GV.isConstant());
657 Vals.push_back(GV.isDeclaration() ? 0 :
658 (VE.getValueID(GV.getInitializer()) + 1));
659 Vals.push_back(getEncodedLinkage(GV));
660 Vals.push_back(Log2_32(GV.getAlignment())+1);
661 Vals.push_back(GV.hasSection() ? SectionMap[GV.getSection()] : 0);
662 if (GV.isThreadLocal() ||
663 GV.getVisibility() != GlobalValue::DefaultVisibility ||
664 GV.hasUnnamedAddr() || GV.isExternallyInitialized() ||
665 GV.getDLLStorageClass() != GlobalValue::DefaultStorageClass ||
667 Vals.push_back(getEncodedVisibility(GV));
668 Vals.push_back(getEncodedThreadLocalMode(GV));
669 Vals.push_back(GV.hasUnnamedAddr());
670 Vals.push_back(GV.isExternallyInitialized());
671 Vals.push_back(getEncodedDLLStorageClass(GV));
672 Vals.push_back(GV.hasComdat() ? VE.getComdatID(GV.getComdat()) : 0);
674 AbbrevToUse = SimpleGVarAbbrev;
677 Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse);
681 // Emit the function proto information.
682 for (const Function &F : *M) {
683 // FUNCTION: [type, callingconv, isproto, linkage, paramattrs, alignment,
684 // section, visibility, gc, unnamed_addr, prologuedata,
685 // dllstorageclass, comdat, prefixdata]
686 Vals.push_back(VE.getTypeID(F.getType()));
687 Vals.push_back(F.getCallingConv());
688 Vals.push_back(F.isDeclaration());
689 Vals.push_back(getEncodedLinkage(F));
690 Vals.push_back(VE.getAttributeID(F.getAttributes()));
691 Vals.push_back(Log2_32(F.getAlignment())+1);
692 Vals.push_back(F.hasSection() ? SectionMap[F.getSection()] : 0);
693 Vals.push_back(getEncodedVisibility(F));
694 Vals.push_back(F.hasGC() ? GCMap[F.getGC()] : 0);
695 Vals.push_back(F.hasUnnamedAddr());
696 Vals.push_back(F.hasPrologueData() ? (VE.getValueID(F.getPrologueData()) + 1)
698 Vals.push_back(getEncodedDLLStorageClass(F));
699 Vals.push_back(F.hasComdat() ? VE.getComdatID(F.getComdat()) : 0);
700 Vals.push_back(F.hasPrefixData() ? (VE.getValueID(F.getPrefixData()) + 1)
703 unsigned AbbrevToUse = 0;
704 Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse);
708 // Emit the alias information.
709 for (const GlobalAlias &A : M->aliases()) {
710 // ALIAS: [alias type, aliasee val#, linkage, visibility]
711 Vals.push_back(VE.getTypeID(A.getType()));
712 Vals.push_back(VE.getValueID(A.getAliasee()));
713 Vals.push_back(getEncodedLinkage(A));
714 Vals.push_back(getEncodedVisibility(A));
715 Vals.push_back(getEncodedDLLStorageClass(A));
716 Vals.push_back(getEncodedThreadLocalMode(A));
717 Vals.push_back(A.hasUnnamedAddr());
718 unsigned AbbrevToUse = 0;
719 Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse);
724 static uint64_t GetOptimizationFlags(const Value *V) {
727 if (const auto *OBO = dyn_cast<OverflowingBinaryOperator>(V)) {
728 if (OBO->hasNoSignedWrap())
729 Flags |= 1 << bitc::OBO_NO_SIGNED_WRAP;
730 if (OBO->hasNoUnsignedWrap())
731 Flags |= 1 << bitc::OBO_NO_UNSIGNED_WRAP;
732 } else if (const auto *PEO = dyn_cast<PossiblyExactOperator>(V)) {
734 Flags |= 1 << bitc::PEO_EXACT;
735 } else if (const auto *FPMO = dyn_cast<FPMathOperator>(V)) {
736 if (FPMO->hasUnsafeAlgebra())
737 Flags |= FastMathFlags::UnsafeAlgebra;
738 if (FPMO->hasNoNaNs())
739 Flags |= FastMathFlags::NoNaNs;
740 if (FPMO->hasNoInfs())
741 Flags |= FastMathFlags::NoInfs;
742 if (FPMO->hasNoSignedZeros())
743 Flags |= FastMathFlags::NoSignedZeros;
744 if (FPMO->hasAllowReciprocal())
745 Flags |= FastMathFlags::AllowReciprocal;
751 static void WriteValueAsMetadata(const ValueAsMetadata *MD,
752 const ValueEnumerator &VE,
753 BitstreamWriter &Stream,
754 SmallVectorImpl<uint64_t> &Record) {
755 // Mimic an MDNode with a value as one operand.
756 Value *V = MD->getValue();
757 Record.push_back(VE.getTypeID(V->getType()));
758 Record.push_back(VE.getValueID(V));
759 Stream.EmitRecord(bitc::METADATA_VALUE, Record, 0);
763 static void WriteMDNode(const MDNode *N,
764 const ValueEnumerator &VE,
765 BitstreamWriter &Stream,
766 SmallVectorImpl<uint64_t> &Record) {
767 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
768 Metadata *MD = N->getOperand(i);
773 assert(!isa<LocalAsMetadata>(MD) && "Unexpected function-local metadata");
774 Record.push_back(VE.getMetadataID(MD) + 1);
776 Stream.EmitRecord(N->isDistinct() ? bitc::METADATA_DISTINCT_NODE
777 : bitc::METADATA_NODE,
782 static void WriteModuleMetadata(const Module *M,
783 const ValueEnumerator &VE,
784 BitstreamWriter &Stream) {
785 const auto &MDs = VE.getMDs();
786 if (MDs.empty() && M->named_metadata_empty())
789 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
791 unsigned MDSAbbrev = 0;
792 if (VE.hasMDString()) {
793 // Abbrev for METADATA_STRING.
794 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
795 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_STRING));
796 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
797 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
798 MDSAbbrev = Stream.EmitAbbrev(Abbv);
801 unsigned NameAbbrev = 0;
802 if (!M->named_metadata_empty()) {
803 // Abbrev for METADATA_NAME.
804 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
805 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_NAME));
806 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
807 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
808 NameAbbrev = Stream.EmitAbbrev(Abbv);
811 SmallVector<uint64_t, 64> Record;
812 for (const Metadata *MD : MDs) {
813 if (const MDNode *N = dyn_cast<MDNode>(MD)) {
814 WriteMDNode(N, VE, Stream, Record);
817 if (const auto *MDC = dyn_cast<ConstantAsMetadata>(MD)) {
818 WriteValueAsMetadata(MDC, VE, Stream, Record);
821 const MDString *MDS = cast<MDString>(MD);
822 // Code: [strchar x N]
823 Record.append(MDS->bytes_begin(), MDS->bytes_end());
825 // Emit the finished record.
826 Stream.EmitRecord(bitc::METADATA_STRING, Record, MDSAbbrev);
830 // Write named metadata.
831 for (const NamedMDNode &NMD : M->named_metadata()) {
833 StringRef Str = NMD.getName();
834 Record.append(Str.bytes_begin(), Str.bytes_end());
835 Stream.EmitRecord(bitc::METADATA_NAME, Record, NameAbbrev);
838 // Write named metadata operands.
839 for (unsigned i = 0, e = NMD.getNumOperands(); i != e; ++i)
840 Record.push_back(VE.getMetadataID(NMD.getOperand(i)));
841 Stream.EmitRecord(bitc::METADATA_NAMED_NODE, Record, 0);
848 static void WriteFunctionLocalMetadata(const Function &F,
849 const ValueEnumerator &VE,
850 BitstreamWriter &Stream) {
851 bool StartedMetadataBlock = false;
852 SmallVector<uint64_t, 64> Record;
853 const SmallVectorImpl<const LocalAsMetadata *> &MDs =
854 VE.getFunctionLocalMDs();
855 for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
856 assert(MDs[i] && "Expected valid function-local metadata");
857 if (!StartedMetadataBlock) {
858 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
859 StartedMetadataBlock = true;
861 WriteValueAsMetadata(MDs[i], VE, Stream, Record);
864 if (StartedMetadataBlock)
868 static void WriteMetadataAttachment(const Function &F,
869 const ValueEnumerator &VE,
870 BitstreamWriter &Stream) {
871 Stream.EnterSubblock(bitc::METADATA_ATTACHMENT_ID, 3);
873 SmallVector<uint64_t, 64> Record;
875 // Write metadata attachments
876 // METADATA_ATTACHMENT - [m x [value, [n x [id, mdnode]]]
877 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
879 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
880 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
883 I->getAllMetadataOtherThanDebugLoc(MDs);
885 // If no metadata, ignore instruction.
886 if (MDs.empty()) continue;
888 Record.push_back(VE.getInstructionID(I));
890 for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
891 Record.push_back(MDs[i].first);
892 Record.push_back(VE.getMetadataID(MDs[i].second));
894 Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
901 static void WriteModuleMetadataStore(const Module *M, BitstreamWriter &Stream) {
902 SmallVector<uint64_t, 64> Record;
904 // Write metadata kinds
905 // METADATA_KIND - [n x [id, name]]
906 SmallVector<StringRef, 8> Names;
907 M->getMDKindNames(Names);
909 if (Names.empty()) return;
911 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
913 for (unsigned MDKindID = 0, e = Names.size(); MDKindID != e; ++MDKindID) {
914 Record.push_back(MDKindID);
915 StringRef KName = Names[MDKindID];
916 Record.append(KName.begin(), KName.end());
918 Stream.EmitRecord(bitc::METADATA_KIND, Record, 0);
925 static void emitSignedInt64(SmallVectorImpl<uint64_t> &Vals, uint64_t V) {
927 Vals.push_back(V << 1);
929 Vals.push_back((-V << 1) | 1);
932 static void WriteConstants(unsigned FirstVal, unsigned LastVal,
933 const ValueEnumerator &VE,
934 BitstreamWriter &Stream, bool isGlobal) {
935 if (FirstVal == LastVal) return;
937 Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 4);
939 unsigned AggregateAbbrev = 0;
940 unsigned String8Abbrev = 0;
941 unsigned CString7Abbrev = 0;
942 unsigned CString6Abbrev = 0;
943 // If this is a constant pool for the module, emit module-specific abbrevs.
945 // Abbrev for CST_CODE_AGGREGATE.
946 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
947 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_AGGREGATE));
948 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
949 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal+1)));
950 AggregateAbbrev = Stream.EmitAbbrev(Abbv);
952 // Abbrev for CST_CODE_STRING.
953 Abbv = new BitCodeAbbrev();
954 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_STRING));
955 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
956 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
957 String8Abbrev = Stream.EmitAbbrev(Abbv);
958 // Abbrev for CST_CODE_CSTRING.
959 Abbv = new BitCodeAbbrev();
960 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
961 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
962 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
963 CString7Abbrev = Stream.EmitAbbrev(Abbv);
964 // Abbrev for CST_CODE_CSTRING.
965 Abbv = new BitCodeAbbrev();
966 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
967 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
968 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
969 CString6Abbrev = Stream.EmitAbbrev(Abbv);
972 SmallVector<uint64_t, 64> Record;
974 const ValueEnumerator::ValueList &Vals = VE.getValues();
975 Type *LastTy = nullptr;
976 for (unsigned i = FirstVal; i != LastVal; ++i) {
977 const Value *V = Vals[i].first;
978 // If we need to switch types, do so now.
979 if (V->getType() != LastTy) {
980 LastTy = V->getType();
981 Record.push_back(VE.getTypeID(LastTy));
982 Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record,
983 CONSTANTS_SETTYPE_ABBREV);
987 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
988 Record.push_back(unsigned(IA->hasSideEffects()) |
989 unsigned(IA->isAlignStack()) << 1 |
990 unsigned(IA->getDialect()&1) << 2);
992 // Add the asm string.
993 const std::string &AsmStr = IA->getAsmString();
994 Record.push_back(AsmStr.size());
995 for (unsigned i = 0, e = AsmStr.size(); i != e; ++i)
996 Record.push_back(AsmStr[i]);
998 // Add the constraint string.
999 const std::string &ConstraintStr = IA->getConstraintString();
1000 Record.push_back(ConstraintStr.size());
1001 for (unsigned i = 0, e = ConstraintStr.size(); i != e; ++i)
1002 Record.push_back(ConstraintStr[i]);
1003 Stream.EmitRecord(bitc::CST_CODE_INLINEASM, Record);
1007 const Constant *C = cast<Constant>(V);
1008 unsigned Code = -1U;
1009 unsigned AbbrevToUse = 0;
1010 if (C->isNullValue()) {
1011 Code = bitc::CST_CODE_NULL;
1012 } else if (isa<UndefValue>(C)) {
1013 Code = bitc::CST_CODE_UNDEF;
1014 } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {
1015 if (IV->getBitWidth() <= 64) {
1016 uint64_t V = IV->getSExtValue();
1017 emitSignedInt64(Record, V);
1018 Code = bitc::CST_CODE_INTEGER;
1019 AbbrevToUse = CONSTANTS_INTEGER_ABBREV;
1020 } else { // Wide integers, > 64 bits in size.
1021 // We have an arbitrary precision integer value to write whose
1022 // bit width is > 64. However, in canonical unsigned integer
1023 // format it is likely that the high bits are going to be zero.
1024 // So, we only write the number of active words.
1025 unsigned NWords = IV->getValue().getActiveWords();
1026 const uint64_t *RawWords = IV->getValue().getRawData();
1027 for (unsigned i = 0; i != NWords; ++i) {
1028 emitSignedInt64(Record, RawWords[i]);
1030 Code = bitc::CST_CODE_WIDE_INTEGER;
1032 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
1033 Code = bitc::CST_CODE_FLOAT;
1034 Type *Ty = CFP->getType();
1035 if (Ty->isHalfTy() || Ty->isFloatTy() || Ty->isDoubleTy()) {
1036 Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
1037 } else if (Ty->isX86_FP80Ty()) {
1038 // api needed to prevent premature destruction
1039 // bits are not in the same order as a normal i80 APInt, compensate.
1040 APInt api = CFP->getValueAPF().bitcastToAPInt();
1041 const uint64_t *p = api.getRawData();
1042 Record.push_back((p[1] << 48) | (p[0] >> 16));
1043 Record.push_back(p[0] & 0xffffLL);
1044 } else if (Ty->isFP128Ty() || Ty->isPPC_FP128Ty()) {
1045 APInt api = CFP->getValueAPF().bitcastToAPInt();
1046 const uint64_t *p = api.getRawData();
1047 Record.push_back(p[0]);
1048 Record.push_back(p[1]);
1050 assert (0 && "Unknown FP type!");
1052 } else if (isa<ConstantDataSequential>(C) &&
1053 cast<ConstantDataSequential>(C)->isString()) {
1054 const ConstantDataSequential *Str = cast<ConstantDataSequential>(C);
1055 // Emit constant strings specially.
1056 unsigned NumElts = Str->getNumElements();
1057 // If this is a null-terminated string, use the denser CSTRING encoding.
1058 if (Str->isCString()) {
1059 Code = bitc::CST_CODE_CSTRING;
1060 --NumElts; // Don't encode the null, which isn't allowed by char6.
1062 Code = bitc::CST_CODE_STRING;
1063 AbbrevToUse = String8Abbrev;
1065 bool isCStr7 = Code == bitc::CST_CODE_CSTRING;
1066 bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING;
1067 for (unsigned i = 0; i != NumElts; ++i) {
1068 unsigned char V = Str->getElementAsInteger(i);
1069 Record.push_back(V);
1070 isCStr7 &= (V & 128) == 0;
1072 isCStrChar6 = BitCodeAbbrevOp::isChar6(V);
1076 AbbrevToUse = CString6Abbrev;
1078 AbbrevToUse = CString7Abbrev;
1079 } else if (const ConstantDataSequential *CDS =
1080 dyn_cast<ConstantDataSequential>(C)) {
1081 Code = bitc::CST_CODE_DATA;
1082 Type *EltTy = CDS->getType()->getElementType();
1083 if (isa<IntegerType>(EltTy)) {
1084 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
1085 Record.push_back(CDS->getElementAsInteger(i));
1086 } else if (EltTy->isFloatTy()) {
1087 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1088 union { float F; uint32_t I; };
1089 F = CDS->getElementAsFloat(i);
1090 Record.push_back(I);
1093 assert(EltTy->isDoubleTy() && "Unknown ConstantData element type");
1094 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1095 union { double F; uint64_t I; };
1096 F = CDS->getElementAsDouble(i);
1097 Record.push_back(I);
1100 } else if (isa<ConstantArray>(C) || isa<ConstantStruct>(C) ||
1101 isa<ConstantVector>(C)) {
1102 Code = bitc::CST_CODE_AGGREGATE;
1103 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i)
1104 Record.push_back(VE.getValueID(C->getOperand(i)));
1105 AbbrevToUse = AggregateAbbrev;
1106 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1107 switch (CE->getOpcode()) {
1109 if (Instruction::isCast(CE->getOpcode())) {
1110 Code = bitc::CST_CODE_CE_CAST;
1111 Record.push_back(GetEncodedCastOpcode(CE->getOpcode()));
1112 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
1113 Record.push_back(VE.getValueID(C->getOperand(0)));
1114 AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;
1116 assert(CE->getNumOperands() == 2 && "Unknown constant expr!");
1117 Code = bitc::CST_CODE_CE_BINOP;
1118 Record.push_back(GetEncodedBinaryOpcode(CE->getOpcode()));
1119 Record.push_back(VE.getValueID(C->getOperand(0)));
1120 Record.push_back(VE.getValueID(C->getOperand(1)));
1121 uint64_t Flags = GetOptimizationFlags(CE);
1123 Record.push_back(Flags);
1126 case Instruction::GetElementPtr:
1127 Code = bitc::CST_CODE_CE_GEP;
1128 if (cast<GEPOperator>(C)->isInBounds())
1129 Code = bitc::CST_CODE_CE_INBOUNDS_GEP;
1130 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
1131 Record.push_back(VE.getTypeID(C->getOperand(i)->getType()));
1132 Record.push_back(VE.getValueID(C->getOperand(i)));
1135 case Instruction::Select:
1136 Code = bitc::CST_CODE_CE_SELECT;
1137 Record.push_back(VE.getValueID(C->getOperand(0)));
1138 Record.push_back(VE.getValueID(C->getOperand(1)));
1139 Record.push_back(VE.getValueID(C->getOperand(2)));
1141 case Instruction::ExtractElement:
1142 Code = bitc::CST_CODE_CE_EXTRACTELT;
1143 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
1144 Record.push_back(VE.getValueID(C->getOperand(0)));
1145 Record.push_back(VE.getTypeID(C->getOperand(1)->getType()));
1146 Record.push_back(VE.getValueID(C->getOperand(1)));
1148 case Instruction::InsertElement:
1149 Code = bitc::CST_CODE_CE_INSERTELT;
1150 Record.push_back(VE.getValueID(C->getOperand(0)));
1151 Record.push_back(VE.getValueID(C->getOperand(1)));
1152 Record.push_back(VE.getTypeID(C->getOperand(2)->getType()));
1153 Record.push_back(VE.getValueID(C->getOperand(2)));
1155 case Instruction::ShuffleVector:
1156 // If the return type and argument types are the same, this is a
1157 // standard shufflevector instruction. If the types are different,
1158 // then the shuffle is widening or truncating the input vectors, and
1159 // the argument type must also be encoded.
1160 if (C->getType() == C->getOperand(0)->getType()) {
1161 Code = bitc::CST_CODE_CE_SHUFFLEVEC;
1163 Code = bitc::CST_CODE_CE_SHUFVEC_EX;
1164 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
1166 Record.push_back(VE.getValueID(C->getOperand(0)));
1167 Record.push_back(VE.getValueID(C->getOperand(1)));
1168 Record.push_back(VE.getValueID(C->getOperand(2)));
1170 case Instruction::ICmp:
1171 case Instruction::FCmp:
1172 Code = bitc::CST_CODE_CE_CMP;
1173 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
1174 Record.push_back(VE.getValueID(C->getOperand(0)));
1175 Record.push_back(VE.getValueID(C->getOperand(1)));
1176 Record.push_back(CE->getPredicate());
1179 } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) {
1180 Code = bitc::CST_CODE_BLOCKADDRESS;
1181 Record.push_back(VE.getTypeID(BA->getFunction()->getType()));
1182 Record.push_back(VE.getValueID(BA->getFunction()));
1183 Record.push_back(VE.getGlobalBasicBlockID(BA->getBasicBlock()));
1188 llvm_unreachable("Unknown constant!");
1190 Stream.EmitRecord(Code, Record, AbbrevToUse);
1197 static void WriteModuleConstants(const ValueEnumerator &VE,
1198 BitstreamWriter &Stream) {
1199 const ValueEnumerator::ValueList &Vals = VE.getValues();
1201 // Find the first constant to emit, which is the first non-globalvalue value.
1202 // We know globalvalues have been emitted by WriteModuleInfo.
1203 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
1204 if (!isa<GlobalValue>(Vals[i].first)) {
1205 WriteConstants(i, Vals.size(), VE, Stream, true);
1211 /// PushValueAndType - The file has to encode both the value and type id for
1212 /// many values, because we need to know what type to create for forward
1213 /// references. However, most operands are not forward references, so this type
1214 /// field is not needed.
1216 /// This function adds V's value ID to Vals. If the value ID is higher than the
1217 /// instruction ID, then it is a forward reference, and it also includes the
1218 /// type ID. The value ID that is written is encoded relative to the InstID.
1219 static bool PushValueAndType(const Value *V, unsigned InstID,
1220 SmallVectorImpl<unsigned> &Vals,
1221 ValueEnumerator &VE) {
1222 unsigned ValID = VE.getValueID(V);
1223 // Make encoding relative to the InstID.
1224 Vals.push_back(InstID - ValID);
1225 if (ValID >= InstID) {
1226 Vals.push_back(VE.getTypeID(V->getType()));
1232 /// pushValue - Like PushValueAndType, but where the type of the value is
1233 /// omitted (perhaps it was already encoded in an earlier operand).
1234 static void pushValue(const Value *V, unsigned InstID,
1235 SmallVectorImpl<unsigned> &Vals,
1236 ValueEnumerator &VE) {
1237 unsigned ValID = VE.getValueID(V);
1238 Vals.push_back(InstID - ValID);
1241 static void pushValueSigned(const Value *V, unsigned InstID,
1242 SmallVectorImpl<uint64_t> &Vals,
1243 ValueEnumerator &VE) {
1244 unsigned ValID = VE.getValueID(V);
1245 int64_t diff = ((int32_t)InstID - (int32_t)ValID);
1246 emitSignedInt64(Vals, diff);
1249 /// WriteInstruction - Emit an instruction to the specified stream.
1250 static void WriteInstruction(const Instruction &I, unsigned InstID,
1251 ValueEnumerator &VE, BitstreamWriter &Stream,
1252 SmallVectorImpl<unsigned> &Vals) {
1254 unsigned AbbrevToUse = 0;
1255 VE.setInstructionID(&I);
1256 switch (I.getOpcode()) {
1258 if (Instruction::isCast(I.getOpcode())) {
1259 Code = bitc::FUNC_CODE_INST_CAST;
1260 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
1261 AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
1262 Vals.push_back(VE.getTypeID(I.getType()));
1263 Vals.push_back(GetEncodedCastOpcode(I.getOpcode()));
1265 assert(isa<BinaryOperator>(I) && "Unknown instruction!");
1266 Code = bitc::FUNC_CODE_INST_BINOP;
1267 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
1268 AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
1269 pushValue(I.getOperand(1), InstID, Vals, VE);
1270 Vals.push_back(GetEncodedBinaryOpcode(I.getOpcode()));
1271 uint64_t Flags = GetOptimizationFlags(&I);
1273 if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV)
1274 AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV;
1275 Vals.push_back(Flags);
1280 case Instruction::GetElementPtr:
1281 Code = bitc::FUNC_CODE_INST_GEP;
1282 if (cast<GEPOperator>(&I)->isInBounds())
1283 Code = bitc::FUNC_CODE_INST_INBOUNDS_GEP;
1284 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
1285 PushValueAndType(I.getOperand(i), InstID, Vals, VE);
1287 case Instruction::ExtractValue: {
1288 Code = bitc::FUNC_CODE_INST_EXTRACTVAL;
1289 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1290 const ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
1291 for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
1295 case Instruction::InsertValue: {
1296 Code = bitc::FUNC_CODE_INST_INSERTVAL;
1297 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1298 PushValueAndType(I.getOperand(1), InstID, Vals, VE);
1299 const InsertValueInst *IVI = cast<InsertValueInst>(&I);
1300 for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
1304 case Instruction::Select:
1305 Code = bitc::FUNC_CODE_INST_VSELECT;
1306 PushValueAndType(I.getOperand(1), InstID, Vals, VE);
1307 pushValue(I.getOperand(2), InstID, Vals, VE);
1308 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1310 case Instruction::ExtractElement:
1311 Code = bitc::FUNC_CODE_INST_EXTRACTELT;
1312 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1313 PushValueAndType(I.getOperand(1), InstID, Vals, VE);
1315 case Instruction::InsertElement:
1316 Code = bitc::FUNC_CODE_INST_INSERTELT;
1317 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1318 pushValue(I.getOperand(1), InstID, Vals, VE);
1319 PushValueAndType(I.getOperand(2), InstID, Vals, VE);
1321 case Instruction::ShuffleVector:
1322 Code = bitc::FUNC_CODE_INST_SHUFFLEVEC;
1323 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1324 pushValue(I.getOperand(1), InstID, Vals, VE);
1325 pushValue(I.getOperand(2), InstID, Vals, VE);
1327 case Instruction::ICmp:
1328 case Instruction::FCmp:
1329 // compare returning Int1Ty or vector of Int1Ty
1330 Code = bitc::FUNC_CODE_INST_CMP2;
1331 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1332 pushValue(I.getOperand(1), InstID, Vals, VE);
1333 Vals.push_back(cast<CmpInst>(I).getPredicate());
1336 case Instruction::Ret:
1338 Code = bitc::FUNC_CODE_INST_RET;
1339 unsigned NumOperands = I.getNumOperands();
1340 if (NumOperands == 0)
1341 AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
1342 else if (NumOperands == 1) {
1343 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
1344 AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
1346 for (unsigned i = 0, e = NumOperands; i != e; ++i)
1347 PushValueAndType(I.getOperand(i), InstID, Vals, VE);
1351 case Instruction::Br:
1353 Code = bitc::FUNC_CODE_INST_BR;
1354 const BranchInst &II = cast<BranchInst>(I);
1355 Vals.push_back(VE.getValueID(II.getSuccessor(0)));
1356 if (II.isConditional()) {
1357 Vals.push_back(VE.getValueID(II.getSuccessor(1)));
1358 pushValue(II.getCondition(), InstID, Vals, VE);
1362 case Instruction::Switch:
1364 Code = bitc::FUNC_CODE_INST_SWITCH;
1365 const SwitchInst &SI = cast<SwitchInst>(I);
1366 Vals.push_back(VE.getTypeID(SI.getCondition()->getType()));
1367 pushValue(SI.getCondition(), InstID, Vals, VE);
1368 Vals.push_back(VE.getValueID(SI.getDefaultDest()));
1369 for (SwitchInst::ConstCaseIt i = SI.case_begin(), e = SI.case_end();
1371 Vals.push_back(VE.getValueID(i.getCaseValue()));
1372 Vals.push_back(VE.getValueID(i.getCaseSuccessor()));
1376 case Instruction::IndirectBr:
1377 Code = bitc::FUNC_CODE_INST_INDIRECTBR;
1378 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
1379 // Encode the address operand as relative, but not the basic blocks.
1380 pushValue(I.getOperand(0), InstID, Vals, VE);
1381 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i)
1382 Vals.push_back(VE.getValueID(I.getOperand(i)));
1385 case Instruction::Invoke: {
1386 const InvokeInst *II = cast<InvokeInst>(&I);
1387 const Value *Callee(II->getCalledValue());
1388 PointerType *PTy = cast<PointerType>(Callee->getType());
1389 FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1390 Code = bitc::FUNC_CODE_INST_INVOKE;
1392 Vals.push_back(VE.getAttributeID(II->getAttributes()));
1393 Vals.push_back(II->getCallingConv());
1394 Vals.push_back(VE.getValueID(II->getNormalDest()));
1395 Vals.push_back(VE.getValueID(II->getUnwindDest()));
1396 PushValueAndType(Callee, InstID, Vals, VE);
1398 // Emit value #'s for the fixed parameters.
1399 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
1400 pushValue(I.getOperand(i), InstID, Vals, VE); // fixed param.
1402 // Emit type/value pairs for varargs params.
1403 if (FTy->isVarArg()) {
1404 for (unsigned i = FTy->getNumParams(), e = I.getNumOperands()-3;
1406 PushValueAndType(I.getOperand(i), InstID, Vals, VE); // vararg
1410 case Instruction::Resume:
1411 Code = bitc::FUNC_CODE_INST_RESUME;
1412 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1414 case Instruction::Unreachable:
1415 Code = bitc::FUNC_CODE_INST_UNREACHABLE;
1416 AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
1419 case Instruction::PHI: {
1420 const PHINode &PN = cast<PHINode>(I);
1421 Code = bitc::FUNC_CODE_INST_PHI;
1422 // With the newer instruction encoding, forward references could give
1423 // negative valued IDs. This is most common for PHIs, so we use
1425 SmallVector<uint64_t, 128> Vals64;
1426 Vals64.push_back(VE.getTypeID(PN.getType()));
1427 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
1428 pushValueSigned(PN.getIncomingValue(i), InstID, Vals64, VE);
1429 Vals64.push_back(VE.getValueID(PN.getIncomingBlock(i)));
1431 // Emit a Vals64 vector and exit.
1432 Stream.EmitRecord(Code, Vals64, AbbrevToUse);
1437 case Instruction::LandingPad: {
1438 const LandingPadInst &LP = cast<LandingPadInst>(I);
1439 Code = bitc::FUNC_CODE_INST_LANDINGPAD;
1440 Vals.push_back(VE.getTypeID(LP.getType()));
1441 PushValueAndType(LP.getPersonalityFn(), InstID, Vals, VE);
1442 Vals.push_back(LP.isCleanup());
1443 Vals.push_back(LP.getNumClauses());
1444 for (unsigned I = 0, E = LP.getNumClauses(); I != E; ++I) {
1446 Vals.push_back(LandingPadInst::Catch);
1448 Vals.push_back(LandingPadInst::Filter);
1449 PushValueAndType(LP.getClause(I), InstID, Vals, VE);
1454 case Instruction::Alloca: {
1455 Code = bitc::FUNC_CODE_INST_ALLOCA;
1456 Vals.push_back(VE.getTypeID(I.getType()));
1457 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
1458 Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
1459 const AllocaInst &AI = cast<AllocaInst>(I);
1460 unsigned AlignRecord = Log2_32(AI.getAlignment()) + 1;
1461 assert(Log2_32(Value::MaximumAlignment) + 1 < 1 << 5 &&
1462 "not enough bits for maximum alignment");
1463 assert(AlignRecord < 1 << 5 && "alignment greater than 1 << 64");
1464 AlignRecord |= AI.isUsedWithInAlloca() << 5;
1465 Vals.push_back(AlignRecord);
1469 case Instruction::Load:
1470 if (cast<LoadInst>(I).isAtomic()) {
1471 Code = bitc::FUNC_CODE_INST_LOADATOMIC;
1472 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1474 Code = bitc::FUNC_CODE_INST_LOAD;
1475 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE)) // ptr
1476 AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
1478 Vals.push_back(Log2_32(cast<LoadInst>(I).getAlignment())+1);
1479 Vals.push_back(cast<LoadInst>(I).isVolatile());
1480 if (cast<LoadInst>(I).isAtomic()) {
1481 Vals.push_back(GetEncodedOrdering(cast<LoadInst>(I).getOrdering()));
1482 Vals.push_back(GetEncodedSynchScope(cast<LoadInst>(I).getSynchScope()));
1485 case Instruction::Store:
1486 if (cast<StoreInst>(I).isAtomic())
1487 Code = bitc::FUNC_CODE_INST_STOREATOMIC;
1489 Code = bitc::FUNC_CODE_INST_STORE;
1490 PushValueAndType(I.getOperand(1), InstID, Vals, VE); // ptrty + ptr
1491 pushValue(I.getOperand(0), InstID, Vals, VE); // val.
1492 Vals.push_back(Log2_32(cast<StoreInst>(I).getAlignment())+1);
1493 Vals.push_back(cast<StoreInst>(I).isVolatile());
1494 if (cast<StoreInst>(I).isAtomic()) {
1495 Vals.push_back(GetEncodedOrdering(cast<StoreInst>(I).getOrdering()));
1496 Vals.push_back(GetEncodedSynchScope(cast<StoreInst>(I).getSynchScope()));
1499 case Instruction::AtomicCmpXchg:
1500 Code = bitc::FUNC_CODE_INST_CMPXCHG;
1501 PushValueAndType(I.getOperand(0), InstID, Vals, VE); // ptrty + ptr
1502 pushValue(I.getOperand(1), InstID, Vals, VE); // cmp.
1503 pushValue(I.getOperand(2), InstID, Vals, VE); // newval.
1504 Vals.push_back(cast<AtomicCmpXchgInst>(I).isVolatile());
1505 Vals.push_back(GetEncodedOrdering(
1506 cast<AtomicCmpXchgInst>(I).getSuccessOrdering()));
1507 Vals.push_back(GetEncodedSynchScope(
1508 cast<AtomicCmpXchgInst>(I).getSynchScope()));
1509 Vals.push_back(GetEncodedOrdering(
1510 cast<AtomicCmpXchgInst>(I).getFailureOrdering()));
1511 Vals.push_back(cast<AtomicCmpXchgInst>(I).isWeak());
1513 case Instruction::AtomicRMW:
1514 Code = bitc::FUNC_CODE_INST_ATOMICRMW;
1515 PushValueAndType(I.getOperand(0), InstID, Vals, VE); // ptrty + ptr
1516 pushValue(I.getOperand(1), InstID, Vals, VE); // val.
1517 Vals.push_back(GetEncodedRMWOperation(
1518 cast<AtomicRMWInst>(I).getOperation()));
1519 Vals.push_back(cast<AtomicRMWInst>(I).isVolatile());
1520 Vals.push_back(GetEncodedOrdering(cast<AtomicRMWInst>(I).getOrdering()));
1521 Vals.push_back(GetEncodedSynchScope(
1522 cast<AtomicRMWInst>(I).getSynchScope()));
1524 case Instruction::Fence:
1525 Code = bitc::FUNC_CODE_INST_FENCE;
1526 Vals.push_back(GetEncodedOrdering(cast<FenceInst>(I).getOrdering()));
1527 Vals.push_back(GetEncodedSynchScope(cast<FenceInst>(I).getSynchScope()));
1529 case Instruction::Call: {
1530 const CallInst &CI = cast<CallInst>(I);
1531 PointerType *PTy = cast<PointerType>(CI.getCalledValue()->getType());
1532 FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1534 Code = bitc::FUNC_CODE_INST_CALL;
1536 Vals.push_back(VE.getAttributeID(CI.getAttributes()));
1537 Vals.push_back((CI.getCallingConv() << 1) | unsigned(CI.isTailCall()) |
1538 unsigned(CI.isMustTailCall()) << 14);
1539 PushValueAndType(CI.getCalledValue(), InstID, Vals, VE); // Callee
1541 // Emit value #'s for the fixed parameters.
1542 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
1543 // Check for labels (can happen with asm labels).
1544 if (FTy->getParamType(i)->isLabelTy())
1545 Vals.push_back(VE.getValueID(CI.getArgOperand(i)));
1547 pushValue(CI.getArgOperand(i), InstID, Vals, VE); // fixed param.
1550 // Emit type/value pairs for varargs params.
1551 if (FTy->isVarArg()) {
1552 for (unsigned i = FTy->getNumParams(), e = CI.getNumArgOperands();
1554 PushValueAndType(CI.getArgOperand(i), InstID, Vals, VE); // varargs
1558 case Instruction::VAArg:
1559 Code = bitc::FUNC_CODE_INST_VAARG;
1560 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); // valistty
1561 pushValue(I.getOperand(0), InstID, Vals, VE); // valist.
1562 Vals.push_back(VE.getTypeID(I.getType())); // restype.
1566 Stream.EmitRecord(Code, Vals, AbbrevToUse);
1570 // Emit names for globals/functions etc.
1571 static void WriteValueSymbolTable(const ValueSymbolTable &VST,
1572 const ValueEnumerator &VE,
1573 BitstreamWriter &Stream) {
1574 if (VST.empty()) return;
1575 Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
1577 // FIXME: Set up the abbrev, we know how many values there are!
1578 // FIXME: We know if the type names can use 7-bit ascii.
1579 SmallVector<unsigned, 64> NameVals;
1581 for (ValueSymbolTable::const_iterator SI = VST.begin(), SE = VST.end();
1584 const ValueName &Name = *SI;
1586 // Figure out the encoding to use for the name.
1588 bool isChar6 = true;
1589 for (const char *C = Name.getKeyData(), *E = C+Name.getKeyLength();
1592 isChar6 = BitCodeAbbrevOp::isChar6(*C);
1593 if ((unsigned char)*C & 128) {
1595 break; // don't bother scanning the rest.
1599 unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
1601 // VST_ENTRY: [valueid, namechar x N]
1602 // VST_BBENTRY: [bbid, namechar x N]
1604 if (isa<BasicBlock>(SI->getValue())) {
1605 Code = bitc::VST_CODE_BBENTRY;
1607 AbbrevToUse = VST_BBENTRY_6_ABBREV;
1609 Code = bitc::VST_CODE_ENTRY;
1611 AbbrevToUse = VST_ENTRY_6_ABBREV;
1613 AbbrevToUse = VST_ENTRY_7_ABBREV;
1616 NameVals.push_back(VE.getValueID(SI->getValue()));
1617 for (const char *P = Name.getKeyData(),
1618 *E = Name.getKeyData()+Name.getKeyLength(); P != E; ++P)
1619 NameVals.push_back((unsigned char)*P);
1621 // Emit the finished record.
1622 Stream.EmitRecord(Code, NameVals, AbbrevToUse);
1628 static void WriteUseList(ValueEnumerator &VE, UseListOrder &&Order,
1629 BitstreamWriter &Stream) {
1630 assert(Order.Shuffle.size() >= 2 && "Shuffle too small");
1632 if (isa<BasicBlock>(Order.V))
1633 Code = bitc::USELIST_CODE_BB;
1635 Code = bitc::USELIST_CODE_DEFAULT;
1637 SmallVector<uint64_t, 64> Record;
1638 for (unsigned I : Order.Shuffle)
1639 Record.push_back(I);
1640 Record.push_back(VE.getValueID(Order.V));
1641 Stream.EmitRecord(Code, Record);
1644 static void WriteUseListBlock(const Function *F, ValueEnumerator &VE,
1645 BitstreamWriter &Stream) {
1646 auto hasMore = [&]() {
1647 return !VE.UseListOrders.empty() && VE.UseListOrders.back().F == F;
1653 Stream.EnterSubblock(bitc::USELIST_BLOCK_ID, 3);
1655 WriteUseList(VE, std::move(VE.UseListOrders.back()), Stream);
1656 VE.UseListOrders.pop_back();
1661 /// WriteFunction - Emit a function body to the module stream.
1662 static void WriteFunction(const Function &F, ValueEnumerator &VE,
1663 BitstreamWriter &Stream) {
1664 Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 4);
1665 VE.incorporateFunction(F);
1667 SmallVector<unsigned, 64> Vals;
1669 // Emit the number of basic blocks, so the reader can create them ahead of
1671 Vals.push_back(VE.getBasicBlocks().size());
1672 Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals);
1675 // If there are function-local constants, emit them now.
1676 unsigned CstStart, CstEnd;
1677 VE.getFunctionConstantRange(CstStart, CstEnd);
1678 WriteConstants(CstStart, CstEnd, VE, Stream, false);
1680 // If there is function-local metadata, emit it now.
1681 WriteFunctionLocalMetadata(F, VE, Stream);
1683 // Keep a running idea of what the instruction ID is.
1684 unsigned InstID = CstEnd;
1686 bool NeedsMetadataAttachment = false;
1690 // Finally, emit all the instructions, in order.
1691 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1692 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
1694 WriteInstruction(*I, InstID, VE, Stream, Vals);
1696 if (!I->getType()->isVoidTy())
1699 // If the instruction has metadata, write a metadata attachment later.
1700 NeedsMetadataAttachment |= I->hasMetadataOtherThanDebugLoc();
1702 // If the instruction has a debug location, emit it.
1703 DebugLoc DL = I->getDebugLoc();
1704 if (DL.isUnknown()) {
1706 } else if (DL == LastDL) {
1707 // Just repeat the same debug loc as last time.
1708 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC_AGAIN, Vals);
1711 DL.getScopeAndInlinedAt(Scope, IA, I->getContext());
1712 assert(Scope && "Expected valid scope");
1714 Vals.push_back(DL.getLine());
1715 Vals.push_back(DL.getCol());
1716 Vals.push_back(Scope ? VE.getMetadataID(Scope) + 1 : 0);
1717 Vals.push_back(IA ? VE.getMetadataID(IA) + 1 : 0);
1718 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC, Vals);
1725 // Emit names for all the instructions etc.
1726 WriteValueSymbolTable(F.getValueSymbolTable(), VE, Stream);
1728 if (NeedsMetadataAttachment)
1729 WriteMetadataAttachment(F, VE, Stream);
1730 if (shouldPreserveBitcodeUseListOrder())
1731 WriteUseListBlock(&F, VE, Stream);
1736 // Emit blockinfo, which defines the standard abbreviations etc.
1737 static void WriteBlockInfo(const ValueEnumerator &VE, BitstreamWriter &Stream) {
1738 // We only want to emit block info records for blocks that have multiple
1739 // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK.
1740 // Other blocks can define their abbrevs inline.
1741 Stream.EnterBlockInfoBlock(2);
1743 { // 8-bit fixed-width VST_ENTRY/VST_BBENTRY strings.
1744 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1745 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3));
1746 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1747 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1748 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
1749 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1750 Abbv) != VST_ENTRY_8_ABBREV)
1751 llvm_unreachable("Unexpected abbrev ordering!");
1754 { // 7-bit fixed width VST_ENTRY strings.
1755 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1756 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
1757 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1758 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1759 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
1760 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1761 Abbv) != VST_ENTRY_7_ABBREV)
1762 llvm_unreachable("Unexpected abbrev ordering!");
1764 { // 6-bit char6 VST_ENTRY strings.
1765 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1766 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
1767 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1768 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1769 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
1770 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1771 Abbv) != VST_ENTRY_6_ABBREV)
1772 llvm_unreachable("Unexpected abbrev ordering!");
1774 { // 6-bit char6 VST_BBENTRY strings.
1775 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1776 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY));
1777 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1778 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1779 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
1780 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1781 Abbv) != VST_BBENTRY_6_ABBREV)
1782 llvm_unreachable("Unexpected abbrev ordering!");
1787 { // SETTYPE abbrev for CONSTANTS_BLOCK.
1788 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1789 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_SETTYPE));
1790 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
1791 Log2_32_Ceil(VE.getTypes().size()+1)));
1792 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1793 Abbv) != CONSTANTS_SETTYPE_ABBREV)
1794 llvm_unreachable("Unexpected abbrev ordering!");
1797 { // INTEGER abbrev for CONSTANTS_BLOCK.
1798 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1799 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_INTEGER));
1800 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1801 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1802 Abbv) != CONSTANTS_INTEGER_ABBREV)
1803 llvm_unreachable("Unexpected abbrev ordering!");
1806 { // CE_CAST abbrev for CONSTANTS_BLOCK.
1807 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1808 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CE_CAST));
1809 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // cast opc
1810 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // typeid
1811 Log2_32_Ceil(VE.getTypes().size()+1)));
1812 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
1814 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1815 Abbv) != CONSTANTS_CE_CAST_Abbrev)
1816 llvm_unreachable("Unexpected abbrev ordering!");
1818 { // NULL abbrev for CONSTANTS_BLOCK.
1819 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1820 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_NULL));
1821 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1822 Abbv) != CONSTANTS_NULL_Abbrev)
1823 llvm_unreachable("Unexpected abbrev ordering!");
1826 // FIXME: This should only use space for first class types!
1828 { // INST_LOAD abbrev for FUNCTION_BLOCK.
1829 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1830 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_LOAD));
1831 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Ptr
1832 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align
1833 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile
1834 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1835 Abbv) != FUNCTION_INST_LOAD_ABBREV)
1836 llvm_unreachable("Unexpected abbrev ordering!");
1838 { // INST_BINOP abbrev for FUNCTION_BLOCK.
1839 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1840 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
1841 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
1842 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
1843 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
1844 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1845 Abbv) != FUNCTION_INST_BINOP_ABBREV)
1846 llvm_unreachable("Unexpected abbrev ordering!");
1848 { // INST_BINOP_FLAGS abbrev for FUNCTION_BLOCK.
1849 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1850 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
1851 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
1852 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
1853 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
1854 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7)); // flags
1855 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1856 Abbv) != FUNCTION_INST_BINOP_FLAGS_ABBREV)
1857 llvm_unreachable("Unexpected abbrev ordering!");
1859 { // INST_CAST abbrev for FUNCTION_BLOCK.
1860 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1861 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST));
1862 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // OpVal
1863 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
1864 Log2_32_Ceil(VE.getTypes().size()+1)));
1865 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
1866 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1867 Abbv) != FUNCTION_INST_CAST_ABBREV)
1868 llvm_unreachable("Unexpected abbrev ordering!");
1871 { // INST_RET abbrev for FUNCTION_BLOCK.
1872 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1873 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
1874 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1875 Abbv) != FUNCTION_INST_RET_VOID_ABBREV)
1876 llvm_unreachable("Unexpected abbrev ordering!");
1878 { // INST_RET abbrev for FUNCTION_BLOCK.
1879 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1880 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
1881 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ValID
1882 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1883 Abbv) != FUNCTION_INST_RET_VAL_ABBREV)
1884 llvm_unreachable("Unexpected abbrev ordering!");
1886 { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK.
1887 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1888 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNREACHABLE));
1889 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1890 Abbv) != FUNCTION_INST_UNREACHABLE_ABBREV)
1891 llvm_unreachable("Unexpected abbrev ordering!");
1897 /// WriteModule - Emit the specified module to the bitstream.
1898 static void WriteModule(const Module *M, BitstreamWriter &Stream) {
1899 Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
1901 SmallVector<unsigned, 1> Vals;
1902 unsigned CurVersion = 1;
1903 Vals.push_back(CurVersion);
1904 Stream.EmitRecord(bitc::MODULE_CODE_VERSION, Vals);
1906 // Analyze the module, enumerating globals, functions, etc.
1907 ValueEnumerator VE(*M);
1909 // Emit blockinfo, which defines the standard abbreviations etc.
1910 WriteBlockInfo(VE, Stream);
1912 // Emit information about attribute groups.
1913 WriteAttributeGroupTable(VE, Stream);
1915 // Emit information about parameter attributes.
1916 WriteAttributeTable(VE, Stream);
1918 // Emit information describing all of the types in the module.
1919 WriteTypeTable(VE, Stream);
1921 writeComdats(VE, Stream);
1923 // Emit top-level description of module, including target triple, inline asm,
1924 // descriptors for global variables, and function prototype info.
1925 WriteModuleInfo(M, VE, Stream);
1928 WriteModuleConstants(VE, Stream);
1931 WriteModuleMetadata(M, VE, Stream);
1934 WriteModuleMetadataStore(M, Stream);
1936 // Emit names for globals/functions etc.
1937 WriteValueSymbolTable(M->getValueSymbolTable(), VE, Stream);
1939 // Emit module-level use-lists.
1940 if (shouldPreserveBitcodeUseListOrder())
1941 WriteUseListBlock(nullptr, VE, Stream);
1943 // Emit function bodies.
1944 for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F)
1945 if (!F->isDeclaration())
1946 WriteFunction(*F, VE, Stream);
1951 /// EmitDarwinBCHeader - If generating a bc file on darwin, we have to emit a
1952 /// header and trailer to make it compatible with the system archiver. To do
1953 /// this we emit the following header, and then emit a trailer that pads the
1954 /// file out to be a multiple of 16 bytes.
1956 /// struct bc_header {
1957 /// uint32_t Magic; // 0x0B17C0DE
1958 /// uint32_t Version; // Version, currently always 0.
1959 /// uint32_t BitcodeOffset; // Offset to traditional bitcode file.
1960 /// uint32_t BitcodeSize; // Size of traditional bitcode file.
1961 /// uint32_t CPUType; // CPU specifier.
1962 /// ... potentially more later ...
1965 DarwinBCSizeFieldOffset = 3*4, // Offset to bitcode_size.
1966 DarwinBCHeaderSize = 5*4
1969 static void WriteInt32ToBuffer(uint32_t Value, SmallVectorImpl<char> &Buffer,
1970 uint32_t &Position) {
1971 Buffer[Position + 0] = (unsigned char) (Value >> 0);
1972 Buffer[Position + 1] = (unsigned char) (Value >> 8);
1973 Buffer[Position + 2] = (unsigned char) (Value >> 16);
1974 Buffer[Position + 3] = (unsigned char) (Value >> 24);
1978 static void EmitDarwinBCHeaderAndTrailer(SmallVectorImpl<char> &Buffer,
1980 unsigned CPUType = ~0U;
1982 // Match x86_64-*, i[3-9]86-*, powerpc-*, powerpc64-*, arm-*, thumb-*,
1983 // armv[0-9]-*, thumbv[0-9]-*, armv5te-*, or armv6t2-*. The CPUType is a magic
1984 // number from /usr/include/mach/machine.h. It is ok to reproduce the
1985 // specific constants here because they are implicitly part of the Darwin ABI.
1987 DARWIN_CPU_ARCH_ABI64 = 0x01000000,
1988 DARWIN_CPU_TYPE_X86 = 7,
1989 DARWIN_CPU_TYPE_ARM = 12,
1990 DARWIN_CPU_TYPE_POWERPC = 18
1993 Triple::ArchType Arch = TT.getArch();
1994 if (Arch == Triple::x86_64)
1995 CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64;
1996 else if (Arch == Triple::x86)
1997 CPUType = DARWIN_CPU_TYPE_X86;
1998 else if (Arch == Triple::ppc)
1999 CPUType = DARWIN_CPU_TYPE_POWERPC;
2000 else if (Arch == Triple::ppc64)
2001 CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64;
2002 else if (Arch == Triple::arm || Arch == Triple::thumb)
2003 CPUType = DARWIN_CPU_TYPE_ARM;
2005 // Traditional Bitcode starts after header.
2006 assert(Buffer.size() >= DarwinBCHeaderSize &&
2007 "Expected header size to be reserved");
2008 unsigned BCOffset = DarwinBCHeaderSize;
2009 unsigned BCSize = Buffer.size()-DarwinBCHeaderSize;
2011 // Write the magic and version.
2012 unsigned Position = 0;
2013 WriteInt32ToBuffer(0x0B17C0DE , Buffer, Position);
2014 WriteInt32ToBuffer(0 , Buffer, Position); // Version.
2015 WriteInt32ToBuffer(BCOffset , Buffer, Position);
2016 WriteInt32ToBuffer(BCSize , Buffer, Position);
2017 WriteInt32ToBuffer(CPUType , Buffer, Position);
2019 // If the file is not a multiple of 16 bytes, insert dummy padding.
2020 while (Buffer.size() & 15)
2021 Buffer.push_back(0);
2024 /// WriteBitcodeToFile - Write the specified module to the specified output
2026 void llvm::WriteBitcodeToFile(const Module *M, raw_ostream &Out) {
2027 SmallVector<char, 0> Buffer;
2028 Buffer.reserve(256*1024);
2030 // If this is darwin or another generic macho target, reserve space for the
2032 Triple TT(M->getTargetTriple());
2033 if (TT.isOSDarwin())
2034 Buffer.insert(Buffer.begin(), DarwinBCHeaderSize, 0);
2036 // Emit the module into the buffer.
2038 BitstreamWriter Stream(Buffer);
2040 // Emit the file header.
2041 Stream.Emit((unsigned)'B', 8);
2042 Stream.Emit((unsigned)'C', 8);
2043 Stream.Emit(0x0, 4);
2044 Stream.Emit(0xC, 4);
2045 Stream.Emit(0xE, 4);
2046 Stream.Emit(0xD, 4);
2049 WriteModule(M, Stream);
2052 if (TT.isOSDarwin())
2053 EmitDarwinBCHeaderAndTrailer(Buffer, TT);
2055 // Write the generated bitstream to "Out".
2056 Out.write((char*)&Buffer.front(), Buffer.size());