xref: /llvm-project/llvm/lib/Bitcode/Writer/BitcodeWriter.cpp (revision cffd8cb9dc74b4899342fd89c26d803ef33a0410)
1 //===--- Bitcode/Writer/BitcodeWriter.cpp - Bitcode Writer ----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // Bitcode writer implementation.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "ValueEnumerator.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/ADT/Triple.h"
17 #include "llvm/Analysis/BlockFrequencyInfo.h"
18 #include "llvm/Analysis/BlockFrequencyInfoImpl.h"
19 #include "llvm/Analysis/BranchProbabilityInfo.h"
20 #include "llvm/Analysis/LoopInfo.h"
21 #include "llvm/Bitcode/BitstreamWriter.h"
22 #include "llvm/Bitcode/LLVMBitCodes.h"
23 #include "llvm/Bitcode/ReaderWriter.h"
24 #include "llvm/IR/CallSite.h"
25 #include "llvm/IR/Constants.h"
26 #include "llvm/IR/DebugInfoMetadata.h"
27 #include "llvm/IR/DerivedTypes.h"
28 #include "llvm/IR/Dominators.h"
29 #include "llvm/IR/InlineAsm.h"
30 #include "llvm/IR/Instructions.h"
31 #include "llvm/IR/IntrinsicInst.h"
32 #include "llvm/IR/LLVMContext.h"
33 #include "llvm/IR/Module.h"
34 #include "llvm/IR/Operator.h"
35 #include "llvm/IR/UseListOrder.h"
36 #include "llvm/IR/ValueSymbolTable.h"
37 #include "llvm/Support/CommandLine.h"
38 #include "llvm/Support/ErrorHandling.h"
39 #include "llvm/Support/MathExtras.h"
40 #include "llvm/Support/Program.h"
41 #include "llvm/Support/raw_ostream.h"
42 #include <cctype>
43 #include <map>
44 using namespace llvm;
45 
46 /// These are manifest constants used by the bitcode writer. They do not need to
47 /// be kept in sync with the reader, but need to be consistent within this file.
48 enum {
49   // VALUE_SYMTAB_BLOCK abbrev id's.
50   VST_ENTRY_8_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
51   VST_ENTRY_7_ABBREV,
52   VST_ENTRY_6_ABBREV,
53   VST_BBENTRY_6_ABBREV,
54 
55   // CONSTANTS_BLOCK abbrev id's.
56   CONSTANTS_SETTYPE_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
57   CONSTANTS_INTEGER_ABBREV,
58   CONSTANTS_CE_CAST_Abbrev,
59   CONSTANTS_NULL_Abbrev,
60 
61   // FUNCTION_BLOCK abbrev id's.
62   FUNCTION_INST_LOAD_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
63   FUNCTION_INST_BINOP_ABBREV,
64   FUNCTION_INST_BINOP_FLAGS_ABBREV,
65   FUNCTION_INST_CAST_ABBREV,
66   FUNCTION_INST_RET_VOID_ABBREV,
67   FUNCTION_INST_RET_VAL_ABBREV,
68   FUNCTION_INST_UNREACHABLE_ABBREV,
69   FUNCTION_INST_GEP_ABBREV,
70 };
71 
72 static unsigned GetEncodedCastOpcode(unsigned Opcode) {
73   switch (Opcode) {
74   default: llvm_unreachable("Unknown cast instruction!");
75   case Instruction::Trunc   : return bitc::CAST_TRUNC;
76   case Instruction::ZExt    : return bitc::CAST_ZEXT;
77   case Instruction::SExt    : return bitc::CAST_SEXT;
78   case Instruction::FPToUI  : return bitc::CAST_FPTOUI;
79   case Instruction::FPToSI  : return bitc::CAST_FPTOSI;
80   case Instruction::UIToFP  : return bitc::CAST_UITOFP;
81   case Instruction::SIToFP  : return bitc::CAST_SITOFP;
82   case Instruction::FPTrunc : return bitc::CAST_FPTRUNC;
83   case Instruction::FPExt   : return bitc::CAST_FPEXT;
84   case Instruction::PtrToInt: return bitc::CAST_PTRTOINT;
85   case Instruction::IntToPtr: return bitc::CAST_INTTOPTR;
86   case Instruction::BitCast : return bitc::CAST_BITCAST;
87   case Instruction::AddrSpaceCast: return bitc::CAST_ADDRSPACECAST;
88   }
89 }
90 
91 static unsigned GetEncodedBinaryOpcode(unsigned Opcode) {
92   switch (Opcode) {
93   default: llvm_unreachable("Unknown binary instruction!");
94   case Instruction::Add:
95   case Instruction::FAdd: return bitc::BINOP_ADD;
96   case Instruction::Sub:
97   case Instruction::FSub: return bitc::BINOP_SUB;
98   case Instruction::Mul:
99   case Instruction::FMul: return bitc::BINOP_MUL;
100   case Instruction::UDiv: return bitc::BINOP_UDIV;
101   case Instruction::FDiv:
102   case Instruction::SDiv: return bitc::BINOP_SDIV;
103   case Instruction::URem: return bitc::BINOP_UREM;
104   case Instruction::FRem:
105   case Instruction::SRem: return bitc::BINOP_SREM;
106   case Instruction::Shl:  return bitc::BINOP_SHL;
107   case Instruction::LShr: return bitc::BINOP_LSHR;
108   case Instruction::AShr: return bitc::BINOP_ASHR;
109   case Instruction::And:  return bitc::BINOP_AND;
110   case Instruction::Or:   return bitc::BINOP_OR;
111   case Instruction::Xor:  return bitc::BINOP_XOR;
112   }
113 }
114 
115 static unsigned GetEncodedRMWOperation(AtomicRMWInst::BinOp Op) {
116   switch (Op) {
117   default: llvm_unreachable("Unknown RMW operation!");
118   case AtomicRMWInst::Xchg: return bitc::RMW_XCHG;
119   case AtomicRMWInst::Add: return bitc::RMW_ADD;
120   case AtomicRMWInst::Sub: return bitc::RMW_SUB;
121   case AtomicRMWInst::And: return bitc::RMW_AND;
122   case AtomicRMWInst::Nand: return bitc::RMW_NAND;
123   case AtomicRMWInst::Or: return bitc::RMW_OR;
124   case AtomicRMWInst::Xor: return bitc::RMW_XOR;
125   case AtomicRMWInst::Max: return bitc::RMW_MAX;
126   case AtomicRMWInst::Min: return bitc::RMW_MIN;
127   case AtomicRMWInst::UMax: return bitc::RMW_UMAX;
128   case AtomicRMWInst::UMin: return bitc::RMW_UMIN;
129   }
130 }
131 
132 static unsigned GetEncodedOrdering(AtomicOrdering Ordering) {
133   switch (Ordering) {
134   case NotAtomic: return bitc::ORDERING_NOTATOMIC;
135   case Unordered: return bitc::ORDERING_UNORDERED;
136   case Monotonic: return bitc::ORDERING_MONOTONIC;
137   case Acquire: return bitc::ORDERING_ACQUIRE;
138   case Release: return bitc::ORDERING_RELEASE;
139   case AcquireRelease: return bitc::ORDERING_ACQREL;
140   case SequentiallyConsistent: return bitc::ORDERING_SEQCST;
141   }
142   llvm_unreachable("Invalid ordering");
143 }
144 
145 static unsigned GetEncodedSynchScope(SynchronizationScope SynchScope) {
146   switch (SynchScope) {
147   case SingleThread: return bitc::SYNCHSCOPE_SINGLETHREAD;
148   case CrossThread: return bitc::SYNCHSCOPE_CROSSTHREAD;
149   }
150   llvm_unreachable("Invalid synch scope");
151 }
152 
153 static void WriteStringRecord(unsigned Code, StringRef Str,
154                               unsigned AbbrevToUse, BitstreamWriter &Stream) {
155   SmallVector<unsigned, 64> Vals;
156 
157   // Code: [strchar x N]
158   for (unsigned i = 0, e = Str.size(); i != e; ++i) {
159     if (AbbrevToUse && !BitCodeAbbrevOp::isChar6(Str[i]))
160       AbbrevToUse = 0;
161     Vals.push_back(Str[i]);
162   }
163 
164   // Emit the finished record.
165   Stream.EmitRecord(Code, Vals, AbbrevToUse);
166 }
167 
168 static uint64_t getAttrKindEncoding(Attribute::AttrKind Kind) {
169   switch (Kind) {
170   case Attribute::Alignment:
171     return bitc::ATTR_KIND_ALIGNMENT;
172   case Attribute::AlwaysInline:
173     return bitc::ATTR_KIND_ALWAYS_INLINE;
174   case Attribute::ArgMemOnly:
175     return bitc::ATTR_KIND_ARGMEMONLY;
176   case Attribute::Builtin:
177     return bitc::ATTR_KIND_BUILTIN;
178   case Attribute::ByVal:
179     return bitc::ATTR_KIND_BY_VAL;
180   case Attribute::Convergent:
181     return bitc::ATTR_KIND_CONVERGENT;
182   case Attribute::InAlloca:
183     return bitc::ATTR_KIND_IN_ALLOCA;
184   case Attribute::Cold:
185     return bitc::ATTR_KIND_COLD;
186   case Attribute::InaccessibleMemOnly:
187     return bitc::ATTR_KIND_INACCESSIBLEMEM_ONLY;
188   case Attribute::InaccessibleMemOrArgMemOnly:
189     return bitc::ATTR_KIND_INACCESSIBLEMEM_OR_ARGMEMONLY;
190   case Attribute::InlineHint:
191     return bitc::ATTR_KIND_INLINE_HINT;
192   case Attribute::InReg:
193     return bitc::ATTR_KIND_IN_REG;
194   case Attribute::JumpTable:
195     return bitc::ATTR_KIND_JUMP_TABLE;
196   case Attribute::MinSize:
197     return bitc::ATTR_KIND_MIN_SIZE;
198   case Attribute::Naked:
199     return bitc::ATTR_KIND_NAKED;
200   case Attribute::Nest:
201     return bitc::ATTR_KIND_NEST;
202   case Attribute::NoAlias:
203     return bitc::ATTR_KIND_NO_ALIAS;
204   case Attribute::NoBuiltin:
205     return bitc::ATTR_KIND_NO_BUILTIN;
206   case Attribute::NoCapture:
207     return bitc::ATTR_KIND_NO_CAPTURE;
208   case Attribute::NoDuplicate:
209     return bitc::ATTR_KIND_NO_DUPLICATE;
210   case Attribute::NoImplicitFloat:
211     return bitc::ATTR_KIND_NO_IMPLICIT_FLOAT;
212   case Attribute::NoInline:
213     return bitc::ATTR_KIND_NO_INLINE;
214   case Attribute::NoRecurse:
215     return bitc::ATTR_KIND_NO_RECURSE;
216   case Attribute::NonLazyBind:
217     return bitc::ATTR_KIND_NON_LAZY_BIND;
218   case Attribute::NonNull:
219     return bitc::ATTR_KIND_NON_NULL;
220   case Attribute::Dereferenceable:
221     return bitc::ATTR_KIND_DEREFERENCEABLE;
222   case Attribute::DereferenceableOrNull:
223     return bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL;
224   case Attribute::NoRedZone:
225     return bitc::ATTR_KIND_NO_RED_ZONE;
226   case Attribute::NoReturn:
227     return bitc::ATTR_KIND_NO_RETURN;
228   case Attribute::NoUnwind:
229     return bitc::ATTR_KIND_NO_UNWIND;
230   case Attribute::OptimizeForSize:
231     return bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE;
232   case Attribute::OptimizeNone:
233     return bitc::ATTR_KIND_OPTIMIZE_NONE;
234   case Attribute::ReadNone:
235     return bitc::ATTR_KIND_READ_NONE;
236   case Attribute::ReadOnly:
237     return bitc::ATTR_KIND_READ_ONLY;
238   case Attribute::Returned:
239     return bitc::ATTR_KIND_RETURNED;
240   case Attribute::ReturnsTwice:
241     return bitc::ATTR_KIND_RETURNS_TWICE;
242   case Attribute::SExt:
243     return bitc::ATTR_KIND_S_EXT;
244   case Attribute::StackAlignment:
245     return bitc::ATTR_KIND_STACK_ALIGNMENT;
246   case Attribute::StackProtect:
247     return bitc::ATTR_KIND_STACK_PROTECT;
248   case Attribute::StackProtectReq:
249     return bitc::ATTR_KIND_STACK_PROTECT_REQ;
250   case Attribute::StackProtectStrong:
251     return bitc::ATTR_KIND_STACK_PROTECT_STRONG;
252   case Attribute::SafeStack:
253     return bitc::ATTR_KIND_SAFESTACK;
254   case Attribute::StructRet:
255     return bitc::ATTR_KIND_STRUCT_RET;
256   case Attribute::SanitizeAddress:
257     return bitc::ATTR_KIND_SANITIZE_ADDRESS;
258   case Attribute::SanitizeThread:
259     return bitc::ATTR_KIND_SANITIZE_THREAD;
260   case Attribute::SanitizeMemory:
261     return bitc::ATTR_KIND_SANITIZE_MEMORY;
262   case Attribute::UWTable:
263     return bitc::ATTR_KIND_UW_TABLE;
264   case Attribute::ZExt:
265     return bitc::ATTR_KIND_Z_EXT;
266   case Attribute::EndAttrKinds:
267     llvm_unreachable("Can not encode end-attribute kinds marker.");
268   case Attribute::None:
269     llvm_unreachable("Can not encode none-attribute.");
270   }
271 
272   llvm_unreachable("Trying to encode unknown attribute");
273 }
274 
275 static void WriteAttributeGroupTable(const ValueEnumerator &VE,
276                                      BitstreamWriter &Stream) {
277   const std::vector<AttributeSet> &AttrGrps = VE.getAttributeGroups();
278   if (AttrGrps.empty()) return;
279 
280   Stream.EnterSubblock(bitc::PARAMATTR_GROUP_BLOCK_ID, 3);
281 
282   SmallVector<uint64_t, 64> Record;
283   for (unsigned i = 0, e = AttrGrps.size(); i != e; ++i) {
284     AttributeSet AS = AttrGrps[i];
285     for (unsigned i = 0, e = AS.getNumSlots(); i != e; ++i) {
286       AttributeSet A = AS.getSlotAttributes(i);
287 
288       Record.push_back(VE.getAttributeGroupID(A));
289       Record.push_back(AS.getSlotIndex(i));
290 
291       for (AttributeSet::iterator I = AS.begin(0), E = AS.end(0);
292            I != E; ++I) {
293         Attribute Attr = *I;
294         if (Attr.isEnumAttribute()) {
295           Record.push_back(0);
296           Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
297         } else if (Attr.isIntAttribute()) {
298           Record.push_back(1);
299           Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
300           Record.push_back(Attr.getValueAsInt());
301         } else {
302           StringRef Kind = Attr.getKindAsString();
303           StringRef Val = Attr.getValueAsString();
304 
305           Record.push_back(Val.empty() ? 3 : 4);
306           Record.append(Kind.begin(), Kind.end());
307           Record.push_back(0);
308           if (!Val.empty()) {
309             Record.append(Val.begin(), Val.end());
310             Record.push_back(0);
311           }
312         }
313       }
314 
315       Stream.EmitRecord(bitc::PARAMATTR_GRP_CODE_ENTRY, Record);
316       Record.clear();
317     }
318   }
319 
320   Stream.ExitBlock();
321 }
322 
323 static void WriteAttributeTable(const ValueEnumerator &VE,
324                                 BitstreamWriter &Stream) {
325   const std::vector<AttributeSet> &Attrs = VE.getAttributes();
326   if (Attrs.empty()) return;
327 
328   Stream.EnterSubblock(bitc::PARAMATTR_BLOCK_ID, 3);
329 
330   SmallVector<uint64_t, 64> Record;
331   for (unsigned i = 0, e = Attrs.size(); i != e; ++i) {
332     const AttributeSet &A = Attrs[i];
333     for (unsigned i = 0, e = A.getNumSlots(); i != e; ++i)
334       Record.push_back(VE.getAttributeGroupID(A.getSlotAttributes(i)));
335 
336     Stream.EmitRecord(bitc::PARAMATTR_CODE_ENTRY, Record);
337     Record.clear();
338   }
339 
340   Stream.ExitBlock();
341 }
342 
343 /// WriteTypeTable - Write out the type table for a module.
344 static void WriteTypeTable(const ValueEnumerator &VE, BitstreamWriter &Stream) {
345   const ValueEnumerator::TypeList &TypeList = VE.getTypes();
346 
347   Stream.EnterSubblock(bitc::TYPE_BLOCK_ID_NEW, 4 /*count from # abbrevs */);
348   SmallVector<uint64_t, 64> TypeVals;
349 
350   uint64_t NumBits = VE.computeBitsRequiredForTypeIndicies();
351 
352   // Abbrev for TYPE_CODE_POINTER.
353   BitCodeAbbrev *Abbv = new BitCodeAbbrev();
354   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_POINTER));
355   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
356   Abbv->Add(BitCodeAbbrevOp(0));  // Addrspace = 0
357   unsigned PtrAbbrev = Stream.EmitAbbrev(Abbv);
358 
359   // Abbrev for TYPE_CODE_FUNCTION.
360   Abbv = new BitCodeAbbrev();
361   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_FUNCTION));
362   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));  // isvararg
363   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
364   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
365 
366   unsigned FunctionAbbrev = Stream.EmitAbbrev(Abbv);
367 
368   // Abbrev for TYPE_CODE_STRUCT_ANON.
369   Abbv = new BitCodeAbbrev();
370   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_ANON));
371   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));  // ispacked
372   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
373   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
374 
375   unsigned StructAnonAbbrev = Stream.EmitAbbrev(Abbv);
376 
377   // Abbrev for TYPE_CODE_STRUCT_NAME.
378   Abbv = new BitCodeAbbrev();
379   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAME));
380   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
381   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
382   unsigned StructNameAbbrev = Stream.EmitAbbrev(Abbv);
383 
384   // Abbrev for TYPE_CODE_STRUCT_NAMED.
385   Abbv = new BitCodeAbbrev();
386   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAMED));
387   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));  // ispacked
388   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
389   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
390 
391   unsigned StructNamedAbbrev = Stream.EmitAbbrev(Abbv);
392 
393   // Abbrev for TYPE_CODE_ARRAY.
394   Abbv = new BitCodeAbbrev();
395   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_ARRAY));
396   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // size
397   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
398 
399   unsigned ArrayAbbrev = Stream.EmitAbbrev(Abbv);
400 
401   // Emit an entry count so the reader can reserve space.
402   TypeVals.push_back(TypeList.size());
403   Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals);
404   TypeVals.clear();
405 
406   // Loop over all of the types, emitting each in turn.
407   for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
408     Type *T = TypeList[i];
409     int AbbrevToUse = 0;
410     unsigned Code = 0;
411 
412     switch (T->getTypeID()) {
413     case Type::VoidTyID:      Code = bitc::TYPE_CODE_VOID;      break;
414     case Type::HalfTyID:      Code = bitc::TYPE_CODE_HALF;      break;
415     case Type::FloatTyID:     Code = bitc::TYPE_CODE_FLOAT;     break;
416     case Type::DoubleTyID:    Code = bitc::TYPE_CODE_DOUBLE;    break;
417     case Type::X86_FP80TyID:  Code = bitc::TYPE_CODE_X86_FP80;  break;
418     case Type::FP128TyID:     Code = bitc::TYPE_CODE_FP128;     break;
419     case Type::PPC_FP128TyID: Code = bitc::TYPE_CODE_PPC_FP128; break;
420     case Type::LabelTyID:     Code = bitc::TYPE_CODE_LABEL;     break;
421     case Type::MetadataTyID:  Code = bitc::TYPE_CODE_METADATA;  break;
422     case Type::X86_MMXTyID:   Code = bitc::TYPE_CODE_X86_MMX;   break;
423     case Type::TokenTyID:     Code = bitc::TYPE_CODE_TOKEN;     break;
424     case Type::IntegerTyID:
425       // INTEGER: [width]
426       Code = bitc::TYPE_CODE_INTEGER;
427       TypeVals.push_back(cast<IntegerType>(T)->getBitWidth());
428       break;
429     case Type::PointerTyID: {
430       PointerType *PTy = cast<PointerType>(T);
431       // POINTER: [pointee type, address space]
432       Code = bitc::TYPE_CODE_POINTER;
433       TypeVals.push_back(VE.getTypeID(PTy->getElementType()));
434       unsigned AddressSpace = PTy->getAddressSpace();
435       TypeVals.push_back(AddressSpace);
436       if (AddressSpace == 0) AbbrevToUse = PtrAbbrev;
437       break;
438     }
439     case Type::FunctionTyID: {
440       FunctionType *FT = cast<FunctionType>(T);
441       // FUNCTION: [isvararg, retty, paramty x N]
442       Code = bitc::TYPE_CODE_FUNCTION;
443       TypeVals.push_back(FT->isVarArg());
444       TypeVals.push_back(VE.getTypeID(FT->getReturnType()));
445       for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
446         TypeVals.push_back(VE.getTypeID(FT->getParamType(i)));
447       AbbrevToUse = FunctionAbbrev;
448       break;
449     }
450     case Type::StructTyID: {
451       StructType *ST = cast<StructType>(T);
452       // STRUCT: [ispacked, eltty x N]
453       TypeVals.push_back(ST->isPacked());
454       // Output all of the element types.
455       for (StructType::element_iterator I = ST->element_begin(),
456            E = ST->element_end(); I != E; ++I)
457         TypeVals.push_back(VE.getTypeID(*I));
458 
459       if (ST->isLiteral()) {
460         Code = bitc::TYPE_CODE_STRUCT_ANON;
461         AbbrevToUse = StructAnonAbbrev;
462       } else {
463         if (ST->isOpaque()) {
464           Code = bitc::TYPE_CODE_OPAQUE;
465         } else {
466           Code = bitc::TYPE_CODE_STRUCT_NAMED;
467           AbbrevToUse = StructNamedAbbrev;
468         }
469 
470         // Emit the name if it is present.
471         if (!ST->getName().empty())
472           WriteStringRecord(bitc::TYPE_CODE_STRUCT_NAME, ST->getName(),
473                             StructNameAbbrev, Stream);
474       }
475       break;
476     }
477     case Type::ArrayTyID: {
478       ArrayType *AT = cast<ArrayType>(T);
479       // ARRAY: [numelts, eltty]
480       Code = bitc::TYPE_CODE_ARRAY;
481       TypeVals.push_back(AT->getNumElements());
482       TypeVals.push_back(VE.getTypeID(AT->getElementType()));
483       AbbrevToUse = ArrayAbbrev;
484       break;
485     }
486     case Type::VectorTyID: {
487       VectorType *VT = cast<VectorType>(T);
488       // VECTOR [numelts, eltty]
489       Code = bitc::TYPE_CODE_VECTOR;
490       TypeVals.push_back(VT->getNumElements());
491       TypeVals.push_back(VE.getTypeID(VT->getElementType()));
492       break;
493     }
494     }
495 
496     // Emit the finished record.
497     Stream.EmitRecord(Code, TypeVals, AbbrevToUse);
498     TypeVals.clear();
499   }
500 
501   Stream.ExitBlock();
502 }
503 
504 static unsigned getEncodedLinkage(const GlobalValue::LinkageTypes Linkage) {
505   switch (Linkage) {
506   case GlobalValue::ExternalLinkage:
507     return 0;
508   case GlobalValue::WeakAnyLinkage:
509     return 16;
510   case GlobalValue::AppendingLinkage:
511     return 2;
512   case GlobalValue::InternalLinkage:
513     return 3;
514   case GlobalValue::LinkOnceAnyLinkage:
515     return 18;
516   case GlobalValue::ExternalWeakLinkage:
517     return 7;
518   case GlobalValue::CommonLinkage:
519     return 8;
520   case GlobalValue::PrivateLinkage:
521     return 9;
522   case GlobalValue::WeakODRLinkage:
523     return 17;
524   case GlobalValue::LinkOnceODRLinkage:
525     return 19;
526   case GlobalValue::AvailableExternallyLinkage:
527     return 12;
528   }
529   llvm_unreachable("Invalid linkage");
530 }
531 
532 static unsigned getEncodedLinkage(const GlobalValue &GV) {
533   return getEncodedLinkage(GV.getLinkage());
534 }
535 
536 static unsigned getEncodedVisibility(const GlobalValue &GV) {
537   switch (GV.getVisibility()) {
538   case GlobalValue::DefaultVisibility:   return 0;
539   case GlobalValue::HiddenVisibility:    return 1;
540   case GlobalValue::ProtectedVisibility: return 2;
541   }
542   llvm_unreachable("Invalid visibility");
543 }
544 
545 static unsigned getEncodedDLLStorageClass(const GlobalValue &GV) {
546   switch (GV.getDLLStorageClass()) {
547   case GlobalValue::DefaultStorageClass:   return 0;
548   case GlobalValue::DLLImportStorageClass: return 1;
549   case GlobalValue::DLLExportStorageClass: return 2;
550   }
551   llvm_unreachable("Invalid DLL storage class");
552 }
553 
554 static unsigned getEncodedThreadLocalMode(const GlobalValue &GV) {
555   switch (GV.getThreadLocalMode()) {
556     case GlobalVariable::NotThreadLocal:         return 0;
557     case GlobalVariable::GeneralDynamicTLSModel: return 1;
558     case GlobalVariable::LocalDynamicTLSModel:   return 2;
559     case GlobalVariable::InitialExecTLSModel:    return 3;
560     case GlobalVariable::LocalExecTLSModel:      return 4;
561   }
562   llvm_unreachable("Invalid TLS model");
563 }
564 
565 static unsigned getEncodedComdatSelectionKind(const Comdat &C) {
566   switch (C.getSelectionKind()) {
567   case Comdat::Any:
568     return bitc::COMDAT_SELECTION_KIND_ANY;
569   case Comdat::ExactMatch:
570     return bitc::COMDAT_SELECTION_KIND_EXACT_MATCH;
571   case Comdat::Largest:
572     return bitc::COMDAT_SELECTION_KIND_LARGEST;
573   case Comdat::NoDuplicates:
574     return bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES;
575   case Comdat::SameSize:
576     return bitc::COMDAT_SELECTION_KIND_SAME_SIZE;
577   }
578   llvm_unreachable("Invalid selection kind");
579 }
580 
581 static void writeComdats(const ValueEnumerator &VE, BitstreamWriter &Stream) {
582   SmallVector<unsigned, 64> Vals;
583   for (const Comdat *C : VE.getComdats()) {
584     // COMDAT: [selection_kind, name]
585     Vals.push_back(getEncodedComdatSelectionKind(*C));
586     size_t Size = C->getName().size();
587     assert(isUInt<32>(Size));
588     Vals.push_back(Size);
589     for (char Chr : C->getName())
590       Vals.push_back((unsigned char)Chr);
591     Stream.EmitRecord(bitc::MODULE_CODE_COMDAT, Vals, /*AbbrevToUse=*/0);
592     Vals.clear();
593   }
594 }
595 
596 /// Write a record that will eventually hold the word offset of the
597 /// module-level VST. For now the offset is 0, which will be backpatched
598 /// after the real VST is written. Returns the bit offset to backpatch.
599 static uint64_t WriteValueSymbolTableForwardDecl(BitstreamWriter &Stream) {
600   // Write a placeholder value in for the offset of the real VST,
601   // which is written after the function blocks so that it can include
602   // the offset of each function. The placeholder offset will be
603   // updated when the real VST is written.
604   BitCodeAbbrev *Abbv = new BitCodeAbbrev();
605   Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_VSTOFFSET));
606   // Blocks are 32-bit aligned, so we can use a 32-bit word offset to
607   // hold the real VST offset. Must use fixed instead of VBR as we don't
608   // know how many VBR chunks to reserve ahead of time.
609   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
610   unsigned VSTOffsetAbbrev = Stream.EmitAbbrev(Abbv);
611 
612   // Emit the placeholder
613   uint64_t Vals[] = {bitc::MODULE_CODE_VSTOFFSET, 0};
614   Stream.EmitRecordWithAbbrev(VSTOffsetAbbrev, Vals);
615 
616   // Compute and return the bit offset to the placeholder, which will be
617   // patched when the real VST is written. We can simply subtract the 32-bit
618   // fixed size from the current bit number to get the location to backpatch.
619   return Stream.GetCurrentBitNo() - 32;
620 }
621 
622 enum StringEncoding { SE_Char6, SE_Fixed7, SE_Fixed8 };
623 
624 /// Determine the encoding to use for the given string name and length.
625 static StringEncoding getStringEncoding(const char *Str, unsigned StrLen) {
626   bool isChar6 = true;
627   for (const char *C = Str, *E = C + StrLen; C != E; ++C) {
628     if (isChar6)
629       isChar6 = BitCodeAbbrevOp::isChar6(*C);
630     if ((unsigned char)*C & 128)
631       // don't bother scanning the rest.
632       return SE_Fixed8;
633   }
634   if (isChar6)
635     return SE_Char6;
636   else
637     return SE_Fixed7;
638 }
639 
640 /// Emit top-level description of module, including target triple, inline asm,
641 /// descriptors for global variables, and function prototype info.
642 /// Returns the bit offset to backpatch with the location of the real VST.
643 static uint64_t WriteModuleInfo(const Module *M, const ValueEnumerator &VE,
644                                 BitstreamWriter &Stream) {
645   // Emit various pieces of data attached to a module.
646   if (!M->getTargetTriple().empty())
647     WriteStringRecord(bitc::MODULE_CODE_TRIPLE, M->getTargetTriple(),
648                       0/*TODO*/, Stream);
649   const std::string &DL = M->getDataLayoutStr();
650   if (!DL.empty())
651     WriteStringRecord(bitc::MODULE_CODE_DATALAYOUT, DL, 0 /*TODO*/, Stream);
652   if (!M->getModuleInlineAsm().empty())
653     WriteStringRecord(bitc::MODULE_CODE_ASM, M->getModuleInlineAsm(),
654                       0/*TODO*/, Stream);
655 
656   // Emit information about sections and GC, computing how many there are. Also
657   // compute the maximum alignment value.
658   std::map<std::string, unsigned> SectionMap;
659   std::map<std::string, unsigned> GCMap;
660   unsigned MaxAlignment = 0;
661   unsigned MaxGlobalType = 0;
662   for (const GlobalValue &GV : M->globals()) {
663     MaxAlignment = std::max(MaxAlignment, GV.getAlignment());
664     MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV.getValueType()));
665     if (GV.hasSection()) {
666       // Give section names unique ID's.
667       unsigned &Entry = SectionMap[GV.getSection()];
668       if (!Entry) {
669         WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, GV.getSection(),
670                           0/*TODO*/, Stream);
671         Entry = SectionMap.size();
672       }
673     }
674   }
675   for (const Function &F : *M) {
676     MaxAlignment = std::max(MaxAlignment, F.getAlignment());
677     if (F.hasSection()) {
678       // Give section names unique ID's.
679       unsigned &Entry = SectionMap[F.getSection()];
680       if (!Entry) {
681         WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, F.getSection(),
682                           0/*TODO*/, Stream);
683         Entry = SectionMap.size();
684       }
685     }
686     if (F.hasGC()) {
687       // Same for GC names.
688       unsigned &Entry = GCMap[F.getGC()];
689       if (!Entry) {
690         WriteStringRecord(bitc::MODULE_CODE_GCNAME, F.getGC(),
691                           0/*TODO*/, Stream);
692         Entry = GCMap.size();
693       }
694     }
695   }
696 
697   // Emit abbrev for globals, now that we know # sections and max alignment.
698   unsigned SimpleGVarAbbrev = 0;
699   if (!M->global_empty()) {
700     // Add an abbrev for common globals with no visibility or thread localness.
701     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
702     Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GLOBALVAR));
703     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
704                               Log2_32_Ceil(MaxGlobalType+1)));
705     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // AddrSpace << 2
706                                                            //| explicitType << 1
707                                                            //| constant
708     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // Initializer.
709     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5)); // Linkage.
710     if (MaxAlignment == 0)                                 // Alignment.
711       Abbv->Add(BitCodeAbbrevOp(0));
712     else {
713       unsigned MaxEncAlignment = Log2_32(MaxAlignment)+1;
714       Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
715                                Log2_32_Ceil(MaxEncAlignment+1)));
716     }
717     if (SectionMap.empty())                                    // Section.
718       Abbv->Add(BitCodeAbbrevOp(0));
719     else
720       Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
721                                Log2_32_Ceil(SectionMap.size()+1)));
722     // Don't bother emitting vis + thread local.
723     SimpleGVarAbbrev = Stream.EmitAbbrev(Abbv);
724   }
725 
726   // Emit the global variable information.
727   SmallVector<unsigned, 64> Vals;
728   for (const GlobalVariable &GV : M->globals()) {
729     unsigned AbbrevToUse = 0;
730 
731     // GLOBALVAR: [type, isconst, initid,
732     //             linkage, alignment, section, visibility, threadlocal,
733     //             unnamed_addr, externally_initialized, dllstorageclass,
734     //             comdat]
735     Vals.push_back(VE.getTypeID(GV.getValueType()));
736     Vals.push_back(GV.getType()->getAddressSpace() << 2 | 2 | GV.isConstant());
737     Vals.push_back(GV.isDeclaration() ? 0 :
738                    (VE.getValueID(GV.getInitializer()) + 1));
739     Vals.push_back(getEncodedLinkage(GV));
740     Vals.push_back(Log2_32(GV.getAlignment())+1);
741     Vals.push_back(GV.hasSection() ? SectionMap[GV.getSection()] : 0);
742     if (GV.isThreadLocal() ||
743         GV.getVisibility() != GlobalValue::DefaultVisibility ||
744         GV.hasUnnamedAddr() || GV.isExternallyInitialized() ||
745         GV.getDLLStorageClass() != GlobalValue::DefaultStorageClass ||
746         GV.hasComdat()) {
747       Vals.push_back(getEncodedVisibility(GV));
748       Vals.push_back(getEncodedThreadLocalMode(GV));
749       Vals.push_back(GV.hasUnnamedAddr());
750       Vals.push_back(GV.isExternallyInitialized());
751       Vals.push_back(getEncodedDLLStorageClass(GV));
752       Vals.push_back(GV.hasComdat() ? VE.getComdatID(GV.getComdat()) : 0);
753     } else {
754       AbbrevToUse = SimpleGVarAbbrev;
755     }
756 
757     Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse);
758     Vals.clear();
759   }
760 
761   // Emit the function proto information.
762   for (const Function &F : *M) {
763     // FUNCTION:  [type, callingconv, isproto, linkage, paramattrs, alignment,
764     //             section, visibility, gc, unnamed_addr, prologuedata,
765     //             dllstorageclass, comdat, prefixdata, personalityfn]
766     Vals.push_back(VE.getTypeID(F.getFunctionType()));
767     Vals.push_back(F.getCallingConv());
768     Vals.push_back(F.isDeclaration());
769     Vals.push_back(getEncodedLinkage(F));
770     Vals.push_back(VE.getAttributeID(F.getAttributes()));
771     Vals.push_back(Log2_32(F.getAlignment())+1);
772     Vals.push_back(F.hasSection() ? SectionMap[F.getSection()] : 0);
773     Vals.push_back(getEncodedVisibility(F));
774     Vals.push_back(F.hasGC() ? GCMap[F.getGC()] : 0);
775     Vals.push_back(F.hasUnnamedAddr());
776     Vals.push_back(F.hasPrologueData() ? (VE.getValueID(F.getPrologueData()) + 1)
777                                        : 0);
778     Vals.push_back(getEncodedDLLStorageClass(F));
779     Vals.push_back(F.hasComdat() ? VE.getComdatID(F.getComdat()) : 0);
780     Vals.push_back(F.hasPrefixData() ? (VE.getValueID(F.getPrefixData()) + 1)
781                                      : 0);
782     Vals.push_back(
783         F.hasPersonalityFn() ? (VE.getValueID(F.getPersonalityFn()) + 1) : 0);
784 
785     unsigned AbbrevToUse = 0;
786     Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse);
787     Vals.clear();
788   }
789 
790   // Emit the alias information.
791   for (const GlobalAlias &A : M->aliases()) {
792     // ALIAS: [alias type, aliasee val#, linkage, visibility]
793     Vals.push_back(VE.getTypeID(A.getValueType()));
794     Vals.push_back(A.getType()->getAddressSpace());
795     Vals.push_back(VE.getValueID(A.getAliasee()));
796     Vals.push_back(getEncodedLinkage(A));
797     Vals.push_back(getEncodedVisibility(A));
798     Vals.push_back(getEncodedDLLStorageClass(A));
799     Vals.push_back(getEncodedThreadLocalMode(A));
800     Vals.push_back(A.hasUnnamedAddr());
801     unsigned AbbrevToUse = 0;
802     Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse);
803     Vals.clear();
804   }
805 
806   // Emit the module's source file name.
807   {
808     StringEncoding Bits = getStringEncoding(M->getSourceFileName().data(),
809                                             M->getSourceFileName().size());
810     BitCodeAbbrevOp AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8);
811     if (Bits == SE_Char6)
812       AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Char6);
813     else if (Bits == SE_Fixed7)
814       AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7);
815 
816     // MODULE_CODE_SOURCE_FILENAME: [namechar x N]
817     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
818     Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_SOURCE_FILENAME));
819     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
820     Abbv->Add(AbbrevOpToUse);
821     unsigned FilenameAbbrev = Stream.EmitAbbrev(Abbv);
822 
823     for (const auto P : M->getSourceFileName())
824       Vals.push_back((unsigned char)P);
825 
826     // Emit the finished record.
827     Stream.EmitRecord(bitc::MODULE_CODE_SOURCE_FILENAME, Vals, FilenameAbbrev);
828     Vals.clear();
829   }
830 
831   // If we have a VST, write the VSTOFFSET record placeholder and return
832   // its offset.
833   if (M->getValueSymbolTable().empty())
834     return 0;
835   return WriteValueSymbolTableForwardDecl(Stream);
836 }
837 
838 static uint64_t GetOptimizationFlags(const Value *V) {
839   uint64_t Flags = 0;
840 
841   if (const auto *OBO = dyn_cast<OverflowingBinaryOperator>(V)) {
842     if (OBO->hasNoSignedWrap())
843       Flags |= 1 << bitc::OBO_NO_SIGNED_WRAP;
844     if (OBO->hasNoUnsignedWrap())
845       Flags |= 1 << bitc::OBO_NO_UNSIGNED_WRAP;
846   } else if (const auto *PEO = dyn_cast<PossiblyExactOperator>(V)) {
847     if (PEO->isExact())
848       Flags |= 1 << bitc::PEO_EXACT;
849   } else if (const auto *FPMO = dyn_cast<FPMathOperator>(V)) {
850     if (FPMO->hasUnsafeAlgebra())
851       Flags |= FastMathFlags::UnsafeAlgebra;
852     if (FPMO->hasNoNaNs())
853       Flags |= FastMathFlags::NoNaNs;
854     if (FPMO->hasNoInfs())
855       Flags |= FastMathFlags::NoInfs;
856     if (FPMO->hasNoSignedZeros())
857       Flags |= FastMathFlags::NoSignedZeros;
858     if (FPMO->hasAllowReciprocal())
859       Flags |= FastMathFlags::AllowReciprocal;
860   }
861 
862   return Flags;
863 }
864 
865 static void writeValueAsMetadata(const ValueAsMetadata *MD,
866                                  const ValueEnumerator &VE,
867                                  BitstreamWriter &Stream,
868                                  SmallVectorImpl<uint64_t> &Record) {
869   // Mimic an MDNode with a value as one operand.
870   Value *V = MD->getValue();
871   Record.push_back(VE.getTypeID(V->getType()));
872   Record.push_back(VE.getValueID(V));
873   Stream.EmitRecord(bitc::METADATA_VALUE, Record, 0);
874   Record.clear();
875 }
876 
877 static void writeMDTuple(const MDTuple *N, const ValueEnumerator &VE,
878                          BitstreamWriter &Stream,
879                          SmallVectorImpl<uint64_t> &Record, unsigned Abbrev) {
880   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
881     Metadata *MD = N->getOperand(i);
882     assert(!(MD && isa<LocalAsMetadata>(MD)) &&
883            "Unexpected function-local metadata");
884     Record.push_back(VE.getMetadataOrNullID(MD));
885   }
886   Stream.EmitRecord(N->isDistinct() ? bitc::METADATA_DISTINCT_NODE
887                                     : bitc::METADATA_NODE,
888                     Record, Abbrev);
889   Record.clear();
890 }
891 
892 static unsigned createDILocationAbbrev(BitstreamWriter &Stream) {
893   // Assume the column is usually under 128, and always output the inlined-at
894   // location (it's never more expensive than building an array size 1).
895   BitCodeAbbrev *Abbv = new BitCodeAbbrev();
896   Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_LOCATION));
897   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
898   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
899   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
900   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
901   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
902   return Stream.EmitAbbrev(Abbv);
903 }
904 
905 static void writeDILocation(const DILocation *N, const ValueEnumerator &VE,
906                             BitstreamWriter &Stream,
907                             SmallVectorImpl<uint64_t> &Record,
908                             unsigned &Abbrev) {
909   if (!Abbrev)
910     Abbrev = createDILocationAbbrev(Stream);
911 
912   Record.push_back(N->isDistinct());
913   Record.push_back(N->getLine());
914   Record.push_back(N->getColumn());
915   Record.push_back(VE.getMetadataID(N->getScope()));
916   Record.push_back(VE.getMetadataOrNullID(N->getInlinedAt()));
917 
918   Stream.EmitRecord(bitc::METADATA_LOCATION, Record, Abbrev);
919   Record.clear();
920 }
921 
922 static unsigned createGenericDINodeAbbrev(BitstreamWriter &Stream) {
923   // Assume the column is usually under 128, and always output the inlined-at
924   // location (it's never more expensive than building an array size 1).
925   BitCodeAbbrev *Abbv = new BitCodeAbbrev();
926   Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_GENERIC_DEBUG));
927   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
928   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
929   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
930   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
931   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
932   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
933   return Stream.EmitAbbrev(Abbv);
934 }
935 
936 static void writeGenericDINode(const GenericDINode *N,
937                                const ValueEnumerator &VE,
938                                BitstreamWriter &Stream,
939                                SmallVectorImpl<uint64_t> &Record,
940                                unsigned &Abbrev) {
941   if (!Abbrev)
942     Abbrev = createGenericDINodeAbbrev(Stream);
943 
944   Record.push_back(N->isDistinct());
945   Record.push_back(N->getTag());
946   Record.push_back(0); // Per-tag version field; unused for now.
947 
948   for (auto &I : N->operands())
949     Record.push_back(VE.getMetadataOrNullID(I));
950 
951   Stream.EmitRecord(bitc::METADATA_GENERIC_DEBUG, Record, Abbrev);
952   Record.clear();
953 }
954 
955 static uint64_t rotateSign(int64_t I) {
956   uint64_t U = I;
957   return I < 0 ? ~(U << 1) : U << 1;
958 }
959 
960 static void writeDISubrange(const DISubrange *N, const ValueEnumerator &,
961                             BitstreamWriter &Stream,
962                             SmallVectorImpl<uint64_t> &Record,
963                             unsigned Abbrev) {
964   Record.push_back(N->isDistinct());
965   Record.push_back(N->getCount());
966   Record.push_back(rotateSign(N->getLowerBound()));
967 
968   Stream.EmitRecord(bitc::METADATA_SUBRANGE, Record, Abbrev);
969   Record.clear();
970 }
971 
972 static void writeDIEnumerator(const DIEnumerator *N, const ValueEnumerator &VE,
973                               BitstreamWriter &Stream,
974                               SmallVectorImpl<uint64_t> &Record,
975                               unsigned Abbrev) {
976   Record.push_back(N->isDistinct());
977   Record.push_back(rotateSign(N->getValue()));
978   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
979 
980   Stream.EmitRecord(bitc::METADATA_ENUMERATOR, Record, Abbrev);
981   Record.clear();
982 }
983 
984 static void writeDIBasicType(const DIBasicType *N, const ValueEnumerator &VE,
985                              BitstreamWriter &Stream,
986                              SmallVectorImpl<uint64_t> &Record,
987                              unsigned Abbrev) {
988   Record.push_back(N->isDistinct());
989   Record.push_back(N->getTag());
990   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
991   Record.push_back(N->getSizeInBits());
992   Record.push_back(N->getAlignInBits());
993   Record.push_back(N->getEncoding());
994 
995   Stream.EmitRecord(bitc::METADATA_BASIC_TYPE, Record, Abbrev);
996   Record.clear();
997 }
998 
999 static void writeDIDerivedType(const DIDerivedType *N,
1000                                const ValueEnumerator &VE,
1001                                BitstreamWriter &Stream,
1002                                SmallVectorImpl<uint64_t> &Record,
1003                                unsigned Abbrev) {
1004   Record.push_back(N->isDistinct());
1005   Record.push_back(N->getTag());
1006   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1007   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1008   Record.push_back(N->getLine());
1009   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1010   Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
1011   Record.push_back(N->getSizeInBits());
1012   Record.push_back(N->getAlignInBits());
1013   Record.push_back(N->getOffsetInBits());
1014   Record.push_back(N->getFlags());
1015   Record.push_back(VE.getMetadataOrNullID(N->getExtraData()));
1016 
1017   Stream.EmitRecord(bitc::METADATA_DERIVED_TYPE, Record, Abbrev);
1018   Record.clear();
1019 }
1020 
1021 static void writeDICompositeType(const DICompositeType *N,
1022                                  const ValueEnumerator &VE,
1023                                  BitstreamWriter &Stream,
1024                                  SmallVectorImpl<uint64_t> &Record,
1025                                  unsigned Abbrev) {
1026   Record.push_back(N->isDistinct());
1027   Record.push_back(N->getTag());
1028   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1029   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1030   Record.push_back(N->getLine());
1031   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1032   Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
1033   Record.push_back(N->getSizeInBits());
1034   Record.push_back(N->getAlignInBits());
1035   Record.push_back(N->getOffsetInBits());
1036   Record.push_back(N->getFlags());
1037   Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
1038   Record.push_back(N->getRuntimeLang());
1039   Record.push_back(VE.getMetadataOrNullID(N->getVTableHolder()));
1040   Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
1041   Record.push_back(VE.getMetadataOrNullID(N->getRawIdentifier()));
1042 
1043   Stream.EmitRecord(bitc::METADATA_COMPOSITE_TYPE, Record, Abbrev);
1044   Record.clear();
1045 }
1046 
1047 static void writeDISubroutineType(const DISubroutineType *N,
1048                                   const ValueEnumerator &VE,
1049                                   BitstreamWriter &Stream,
1050                                   SmallVectorImpl<uint64_t> &Record,
1051                                   unsigned Abbrev) {
1052   Record.push_back(N->isDistinct());
1053   Record.push_back(N->getFlags());
1054   Record.push_back(VE.getMetadataOrNullID(N->getTypeArray().get()));
1055 
1056   Stream.EmitRecord(bitc::METADATA_SUBROUTINE_TYPE, Record, Abbrev);
1057   Record.clear();
1058 }
1059 
1060 static void writeDIFile(const DIFile *N, const ValueEnumerator &VE,
1061                         BitstreamWriter &Stream,
1062                         SmallVectorImpl<uint64_t> &Record, unsigned Abbrev) {
1063   Record.push_back(N->isDistinct());
1064   Record.push_back(VE.getMetadataOrNullID(N->getRawFilename()));
1065   Record.push_back(VE.getMetadataOrNullID(N->getRawDirectory()));
1066 
1067   Stream.EmitRecord(bitc::METADATA_FILE, Record, Abbrev);
1068   Record.clear();
1069 }
1070 
1071 static void writeDICompileUnit(const DICompileUnit *N,
1072                                const ValueEnumerator &VE,
1073                                BitstreamWriter &Stream,
1074                                SmallVectorImpl<uint64_t> &Record,
1075                                unsigned Abbrev) {
1076   assert(N->isDistinct() && "Expected distinct compile units");
1077   Record.push_back(/* IsDistinct */ true);
1078   Record.push_back(N->getSourceLanguage());
1079   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1080   Record.push_back(VE.getMetadataOrNullID(N->getRawProducer()));
1081   Record.push_back(N->isOptimized());
1082   Record.push_back(VE.getMetadataOrNullID(N->getRawFlags()));
1083   Record.push_back(N->getRuntimeVersion());
1084   Record.push_back(VE.getMetadataOrNullID(N->getRawSplitDebugFilename()));
1085   Record.push_back(N->getEmissionKind());
1086   Record.push_back(VE.getMetadataOrNullID(N->getEnumTypes().get()));
1087   Record.push_back(VE.getMetadataOrNullID(N->getRetainedTypes().get()));
1088   Record.push_back(VE.getMetadataOrNullID(N->getSubprograms().get()));
1089   Record.push_back(VE.getMetadataOrNullID(N->getGlobalVariables().get()));
1090   Record.push_back(VE.getMetadataOrNullID(N->getImportedEntities().get()));
1091   Record.push_back(N->getDWOId());
1092   Record.push_back(VE.getMetadataOrNullID(N->getMacros().get()));
1093 
1094   Stream.EmitRecord(bitc::METADATA_COMPILE_UNIT, Record, Abbrev);
1095   Record.clear();
1096 }
1097 
1098 static void writeDISubprogram(const DISubprogram *N, const ValueEnumerator &VE,
1099                               BitstreamWriter &Stream,
1100                               SmallVectorImpl<uint64_t> &Record,
1101                               unsigned Abbrev) {
1102   Record.push_back(N->isDistinct());
1103   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1104   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1105   Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
1106   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1107   Record.push_back(N->getLine());
1108   Record.push_back(VE.getMetadataOrNullID(N->getType()));
1109   Record.push_back(N->isLocalToUnit());
1110   Record.push_back(N->isDefinition());
1111   Record.push_back(N->getScopeLine());
1112   Record.push_back(VE.getMetadataOrNullID(N->getContainingType()));
1113   Record.push_back(N->getVirtuality());
1114   Record.push_back(N->getVirtualIndex());
1115   Record.push_back(N->getFlags());
1116   Record.push_back(N->isOptimized());
1117   Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
1118   Record.push_back(VE.getMetadataOrNullID(N->getDeclaration()));
1119   Record.push_back(VE.getMetadataOrNullID(N->getVariables().get()));
1120 
1121   Stream.EmitRecord(bitc::METADATA_SUBPROGRAM, Record, Abbrev);
1122   Record.clear();
1123 }
1124 
1125 static void writeDILexicalBlock(const DILexicalBlock *N,
1126                                 const ValueEnumerator &VE,
1127                                 BitstreamWriter &Stream,
1128                                 SmallVectorImpl<uint64_t> &Record,
1129                                 unsigned Abbrev) {
1130   Record.push_back(N->isDistinct());
1131   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1132   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1133   Record.push_back(N->getLine());
1134   Record.push_back(N->getColumn());
1135 
1136   Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK, Record, Abbrev);
1137   Record.clear();
1138 }
1139 
1140 static void writeDILexicalBlockFile(const DILexicalBlockFile *N,
1141                                     const ValueEnumerator &VE,
1142                                     BitstreamWriter &Stream,
1143                                     SmallVectorImpl<uint64_t> &Record,
1144                                     unsigned Abbrev) {
1145   Record.push_back(N->isDistinct());
1146   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1147   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1148   Record.push_back(N->getDiscriminator());
1149 
1150   Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK_FILE, Record, Abbrev);
1151   Record.clear();
1152 }
1153 
1154 static void writeDINamespace(const DINamespace *N, const ValueEnumerator &VE,
1155                              BitstreamWriter &Stream,
1156                              SmallVectorImpl<uint64_t> &Record,
1157                              unsigned Abbrev) {
1158   Record.push_back(N->isDistinct());
1159   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1160   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1161   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1162   Record.push_back(N->getLine());
1163 
1164   Stream.EmitRecord(bitc::METADATA_NAMESPACE, Record, Abbrev);
1165   Record.clear();
1166 }
1167 
1168 static void writeDIMacro(const DIMacro *N, const ValueEnumerator &VE,
1169                          BitstreamWriter &Stream,
1170                          SmallVectorImpl<uint64_t> &Record, unsigned Abbrev) {
1171   Record.push_back(N->isDistinct());
1172   Record.push_back(N->getMacinfoType());
1173   Record.push_back(N->getLine());
1174   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1175   Record.push_back(VE.getMetadataOrNullID(N->getRawValue()));
1176 
1177   Stream.EmitRecord(bitc::METADATA_MACRO, Record, Abbrev);
1178   Record.clear();
1179 }
1180 
1181 static void writeDIMacroFile(const DIMacroFile *N, const ValueEnumerator &VE,
1182                              BitstreamWriter &Stream,
1183                              SmallVectorImpl<uint64_t> &Record,
1184                              unsigned Abbrev) {
1185   Record.push_back(N->isDistinct());
1186   Record.push_back(N->getMacinfoType());
1187   Record.push_back(N->getLine());
1188   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1189   Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
1190 
1191   Stream.EmitRecord(bitc::METADATA_MACRO_FILE, Record, Abbrev);
1192   Record.clear();
1193 }
1194 
1195 static void writeDIModule(const DIModule *N, const ValueEnumerator &VE,
1196                           BitstreamWriter &Stream,
1197                           SmallVectorImpl<uint64_t> &Record, unsigned Abbrev) {
1198   Record.push_back(N->isDistinct());
1199   for (auto &I : N->operands())
1200     Record.push_back(VE.getMetadataOrNullID(I));
1201 
1202   Stream.EmitRecord(bitc::METADATA_MODULE, Record, Abbrev);
1203   Record.clear();
1204 }
1205 
1206 static void writeDITemplateTypeParameter(const DITemplateTypeParameter *N,
1207                                          const ValueEnumerator &VE,
1208                                          BitstreamWriter &Stream,
1209                                          SmallVectorImpl<uint64_t> &Record,
1210                                          unsigned Abbrev) {
1211   Record.push_back(N->isDistinct());
1212   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1213   Record.push_back(VE.getMetadataOrNullID(N->getType()));
1214 
1215   Stream.EmitRecord(bitc::METADATA_TEMPLATE_TYPE, Record, Abbrev);
1216   Record.clear();
1217 }
1218 
1219 static void writeDITemplateValueParameter(const DITemplateValueParameter *N,
1220                                           const ValueEnumerator &VE,
1221                                           BitstreamWriter &Stream,
1222                                           SmallVectorImpl<uint64_t> &Record,
1223                                           unsigned Abbrev) {
1224   Record.push_back(N->isDistinct());
1225   Record.push_back(N->getTag());
1226   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1227   Record.push_back(VE.getMetadataOrNullID(N->getType()));
1228   Record.push_back(VE.getMetadataOrNullID(N->getValue()));
1229 
1230   Stream.EmitRecord(bitc::METADATA_TEMPLATE_VALUE, Record, Abbrev);
1231   Record.clear();
1232 }
1233 
1234 static void writeDIGlobalVariable(const DIGlobalVariable *N,
1235                                   const ValueEnumerator &VE,
1236                                   BitstreamWriter &Stream,
1237                                   SmallVectorImpl<uint64_t> &Record,
1238                                   unsigned Abbrev) {
1239   Record.push_back(N->isDistinct());
1240   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1241   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1242   Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
1243   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1244   Record.push_back(N->getLine());
1245   Record.push_back(VE.getMetadataOrNullID(N->getType()));
1246   Record.push_back(N->isLocalToUnit());
1247   Record.push_back(N->isDefinition());
1248   Record.push_back(VE.getMetadataOrNullID(N->getRawVariable()));
1249   Record.push_back(VE.getMetadataOrNullID(N->getStaticDataMemberDeclaration()));
1250 
1251   Stream.EmitRecord(bitc::METADATA_GLOBAL_VAR, Record, Abbrev);
1252   Record.clear();
1253 }
1254 
1255 static void writeDILocalVariable(const DILocalVariable *N,
1256                                  const ValueEnumerator &VE,
1257                                  BitstreamWriter &Stream,
1258                                  SmallVectorImpl<uint64_t> &Record,
1259                                  unsigned Abbrev) {
1260   Record.push_back(N->isDistinct());
1261   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1262   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1263   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1264   Record.push_back(N->getLine());
1265   Record.push_back(VE.getMetadataOrNullID(N->getType()));
1266   Record.push_back(N->getArg());
1267   Record.push_back(N->getFlags());
1268 
1269   Stream.EmitRecord(bitc::METADATA_LOCAL_VAR, Record, Abbrev);
1270   Record.clear();
1271 }
1272 
1273 static void writeDIExpression(const DIExpression *N, const ValueEnumerator &,
1274                               BitstreamWriter &Stream,
1275                               SmallVectorImpl<uint64_t> &Record,
1276                               unsigned Abbrev) {
1277   Record.reserve(N->getElements().size() + 1);
1278 
1279   Record.push_back(N->isDistinct());
1280   Record.append(N->elements_begin(), N->elements_end());
1281 
1282   Stream.EmitRecord(bitc::METADATA_EXPRESSION, Record, Abbrev);
1283   Record.clear();
1284 }
1285 
1286 static void writeDIObjCProperty(const DIObjCProperty *N,
1287                                 const ValueEnumerator &VE,
1288                                 BitstreamWriter &Stream,
1289                                 SmallVectorImpl<uint64_t> &Record,
1290                                 unsigned Abbrev) {
1291   Record.push_back(N->isDistinct());
1292   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1293   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1294   Record.push_back(N->getLine());
1295   Record.push_back(VE.getMetadataOrNullID(N->getRawSetterName()));
1296   Record.push_back(VE.getMetadataOrNullID(N->getRawGetterName()));
1297   Record.push_back(N->getAttributes());
1298   Record.push_back(VE.getMetadataOrNullID(N->getType()));
1299 
1300   Stream.EmitRecord(bitc::METADATA_OBJC_PROPERTY, Record, Abbrev);
1301   Record.clear();
1302 }
1303 
1304 static void writeDIImportedEntity(const DIImportedEntity *N,
1305                                   const ValueEnumerator &VE,
1306                                   BitstreamWriter &Stream,
1307                                   SmallVectorImpl<uint64_t> &Record,
1308                                   unsigned Abbrev) {
1309   Record.push_back(N->isDistinct());
1310   Record.push_back(N->getTag());
1311   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1312   Record.push_back(VE.getMetadataOrNullID(N->getEntity()));
1313   Record.push_back(N->getLine());
1314   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1315 
1316   Stream.EmitRecord(bitc::METADATA_IMPORTED_ENTITY, Record, Abbrev);
1317   Record.clear();
1318 }
1319 
1320 static unsigned createNamedMetadataAbbrev(BitstreamWriter &Stream) {
1321   BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1322   Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_NAME));
1323   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1324   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
1325   return Stream.EmitAbbrev(Abbv);
1326 }
1327 
1328 static void writeNamedMetadata(const Module &M, const ValueEnumerator &VE,
1329                                BitstreamWriter &Stream,
1330                                SmallVectorImpl<uint64_t> &Record) {
1331   if (M.named_metadata_empty())
1332     return;
1333 
1334   unsigned Abbrev = createNamedMetadataAbbrev(Stream);
1335   for (const NamedMDNode &NMD : M.named_metadata()) {
1336     // Write name.
1337     StringRef Str = NMD.getName();
1338     Record.append(Str.bytes_begin(), Str.bytes_end());
1339     Stream.EmitRecord(bitc::METADATA_NAME, Record, Abbrev);
1340     Record.clear();
1341 
1342     // Write named metadata operands.
1343     for (const MDNode *N : NMD.operands())
1344       Record.push_back(VE.getMetadataID(N));
1345     Stream.EmitRecord(bitc::METADATA_NAMED_NODE, Record, 0);
1346     Record.clear();
1347   }
1348 }
1349 
1350 static unsigned createMetadataStringsAbbrev(BitstreamWriter &Stream) {
1351   BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1352   Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_STRINGS));
1353   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of strings
1354   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // offset to chars
1355   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1356   return Stream.EmitAbbrev(Abbv);
1357 }
1358 
1359 /// Write out a record for MDString.
1360 ///
1361 /// All the metadata strings in a metadata block are emitted in a single
1362 /// record.  The sizes and strings themselves are shoved into a blob.
1363 static void writeMetadataStrings(ArrayRef<const Metadata *> Strings,
1364                                  BitstreamWriter &Stream,
1365                                  SmallVectorImpl<uint64_t> &Record) {
1366   if (Strings.empty())
1367     return;
1368 
1369   // Start the record with the number of strings.
1370   Record.push_back(bitc::METADATA_STRINGS);
1371   Record.push_back(Strings.size());
1372 
1373   // Emit the sizes of the strings in the blob.
1374   SmallString<256> Blob;
1375   {
1376     BitstreamWriter W(Blob);
1377     for (const Metadata *MD : Strings)
1378       W.EmitVBR(cast<MDString>(MD)->getLength(), 6);
1379     W.FlushToWord();
1380   }
1381 
1382   // Add the offset to the strings to the record.
1383   Record.push_back(Blob.size());
1384 
1385   // Add the strings to the blob.
1386   for (const Metadata *MD : Strings)
1387     Blob.append(cast<MDString>(MD)->getString());
1388 
1389   // Emit the final record.
1390   Stream.EmitRecordWithBlob(createMetadataStringsAbbrev(Stream), Record, Blob);
1391   Record.clear();
1392 }
1393 
1394 static void writeMetadataRecords(ArrayRef<const Metadata *> MDs,
1395                                  const ValueEnumerator &VE,
1396                                  BitstreamWriter &Stream,
1397                                  SmallVectorImpl<uint64_t> &Record) {
1398   if (MDs.empty())
1399     return;
1400 
1401   // Initialize MDNode abbreviations.
1402 #define HANDLE_MDNODE_LEAF(CLASS) unsigned CLASS##Abbrev = 0;
1403 #include "llvm/IR/Metadata.def"
1404 
1405   for (const Metadata *MD : MDs) {
1406     if (const MDNode *N = dyn_cast<MDNode>(MD)) {
1407       assert(N->isResolved() && "Expected forward references to be resolved");
1408 
1409       switch (N->getMetadataID()) {
1410       default:
1411         llvm_unreachable("Invalid MDNode subclass");
1412 #define HANDLE_MDNODE_LEAF(CLASS)                                              \
1413   case Metadata::CLASS##Kind:                                                  \
1414     write##CLASS(cast<CLASS>(N), VE, Stream, Record, CLASS##Abbrev);           \
1415     continue;
1416 #include "llvm/IR/Metadata.def"
1417       }
1418     }
1419     writeValueAsMetadata(cast<ConstantAsMetadata>(MD), VE, Stream, Record);
1420   }
1421 }
1422 
1423 static void writeModuleMetadata(const Module &M,
1424                                 const ValueEnumerator &VE,
1425                                 BitstreamWriter &Stream) {
1426   if (VE.getMDs().empty() && M.named_metadata_empty())
1427     return;
1428 
1429   Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
1430   SmallVector<uint64_t, 64> Record;
1431   writeMetadataStrings(VE.getMDStrings(), Stream, Record);
1432   writeMetadataRecords(VE.getNonMDStrings(), VE, Stream, Record);
1433   writeNamedMetadata(M, VE, Stream, Record);
1434   Stream.ExitBlock();
1435 }
1436 
1437 static void writeFunctionMetadata(const Function &F, const ValueEnumerator &VE,
1438                                   BitstreamWriter &Stream) {
1439   ArrayRef<const Metadata *> MDs = VE.getFunctionMDs();
1440   if (MDs.empty())
1441     return;
1442 
1443   Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
1444 
1445   SmallVector<uint64_t, 64> Record;
1446   for (const Metadata *MD : VE.getFunctionMDs())
1447     writeValueAsMetadata(cast<LocalAsMetadata>(MD), VE, Stream, Record);
1448 
1449   Stream.ExitBlock();
1450 }
1451 
1452 static void WriteMetadataAttachment(const Function &F,
1453                                     const ValueEnumerator &VE,
1454                                     BitstreamWriter &Stream) {
1455   Stream.EnterSubblock(bitc::METADATA_ATTACHMENT_ID, 3);
1456 
1457   SmallVector<uint64_t, 64> Record;
1458 
1459   // Write metadata attachments
1460   // METADATA_ATTACHMENT - [m x [value, [n x [id, mdnode]]]
1461   SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
1462   F.getAllMetadata(MDs);
1463   if (!MDs.empty()) {
1464     for (const auto &I : MDs) {
1465       Record.push_back(I.first);
1466       Record.push_back(VE.getMetadataID(I.second));
1467     }
1468     Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
1469     Record.clear();
1470   }
1471 
1472   for (const BasicBlock &BB : F)
1473     for (const Instruction &I : BB) {
1474       MDs.clear();
1475       I.getAllMetadataOtherThanDebugLoc(MDs);
1476 
1477       // If no metadata, ignore instruction.
1478       if (MDs.empty()) continue;
1479 
1480       Record.push_back(VE.getInstructionID(&I));
1481 
1482       for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
1483         Record.push_back(MDs[i].first);
1484         Record.push_back(VE.getMetadataID(MDs[i].second));
1485       }
1486       Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
1487       Record.clear();
1488     }
1489 
1490   Stream.ExitBlock();
1491 }
1492 
1493 static void WriteModuleMetadataStore(const Module *M, BitstreamWriter &Stream) {
1494   SmallVector<uint64_t, 64> Record;
1495 
1496   // Write metadata kinds
1497   // METADATA_KIND - [n x [id, name]]
1498   SmallVector<StringRef, 8> Names;
1499   M->getMDKindNames(Names);
1500 
1501   if (Names.empty()) return;
1502 
1503   Stream.EnterSubblock(bitc::METADATA_KIND_BLOCK_ID, 3);
1504 
1505   for (unsigned MDKindID = 0, e = Names.size(); MDKindID != e; ++MDKindID) {
1506     Record.push_back(MDKindID);
1507     StringRef KName = Names[MDKindID];
1508     Record.append(KName.begin(), KName.end());
1509 
1510     Stream.EmitRecord(bitc::METADATA_KIND, Record, 0);
1511     Record.clear();
1512   }
1513 
1514   Stream.ExitBlock();
1515 }
1516 
1517 static void WriteOperandBundleTags(const Module *M, BitstreamWriter &Stream) {
1518   // Write metadata kinds
1519   //
1520   // OPERAND_BUNDLE_TAGS_BLOCK_ID : N x OPERAND_BUNDLE_TAG
1521   //
1522   // OPERAND_BUNDLE_TAG - [strchr x N]
1523 
1524   SmallVector<StringRef, 8> Tags;
1525   M->getOperandBundleTags(Tags);
1526 
1527   if (Tags.empty())
1528     return;
1529 
1530   Stream.EnterSubblock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID, 3);
1531 
1532   SmallVector<uint64_t, 64> Record;
1533 
1534   for (auto Tag : Tags) {
1535     Record.append(Tag.begin(), Tag.end());
1536 
1537     Stream.EmitRecord(bitc::OPERAND_BUNDLE_TAG, Record, 0);
1538     Record.clear();
1539   }
1540 
1541   Stream.ExitBlock();
1542 }
1543 
1544 static void emitSignedInt64(SmallVectorImpl<uint64_t> &Vals, uint64_t V) {
1545   if ((int64_t)V >= 0)
1546     Vals.push_back(V << 1);
1547   else
1548     Vals.push_back((-V << 1) | 1);
1549 }
1550 
1551 static void WriteConstants(unsigned FirstVal, unsigned LastVal,
1552                            const ValueEnumerator &VE,
1553                            BitstreamWriter &Stream, bool isGlobal) {
1554   if (FirstVal == LastVal) return;
1555 
1556   Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 4);
1557 
1558   unsigned AggregateAbbrev = 0;
1559   unsigned String8Abbrev = 0;
1560   unsigned CString7Abbrev = 0;
1561   unsigned CString6Abbrev = 0;
1562   // If this is a constant pool for the module, emit module-specific abbrevs.
1563   if (isGlobal) {
1564     // Abbrev for CST_CODE_AGGREGATE.
1565     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1566     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_AGGREGATE));
1567     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1568     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal+1)));
1569     AggregateAbbrev = Stream.EmitAbbrev(Abbv);
1570 
1571     // Abbrev for CST_CODE_STRING.
1572     Abbv = new BitCodeAbbrev();
1573     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_STRING));
1574     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1575     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
1576     String8Abbrev = Stream.EmitAbbrev(Abbv);
1577     // Abbrev for CST_CODE_CSTRING.
1578     Abbv = new BitCodeAbbrev();
1579     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
1580     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1581     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
1582     CString7Abbrev = Stream.EmitAbbrev(Abbv);
1583     // Abbrev for CST_CODE_CSTRING.
1584     Abbv = new BitCodeAbbrev();
1585     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
1586     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1587     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
1588     CString6Abbrev = Stream.EmitAbbrev(Abbv);
1589   }
1590 
1591   SmallVector<uint64_t, 64> Record;
1592 
1593   const ValueEnumerator::ValueList &Vals = VE.getValues();
1594   Type *LastTy = nullptr;
1595   for (unsigned i = FirstVal; i != LastVal; ++i) {
1596     const Value *V = Vals[i].first;
1597     // If we need to switch types, do so now.
1598     if (V->getType() != LastTy) {
1599       LastTy = V->getType();
1600       Record.push_back(VE.getTypeID(LastTy));
1601       Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record,
1602                         CONSTANTS_SETTYPE_ABBREV);
1603       Record.clear();
1604     }
1605 
1606     if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
1607       Record.push_back(unsigned(IA->hasSideEffects()) |
1608                        unsigned(IA->isAlignStack()) << 1 |
1609                        unsigned(IA->getDialect()&1) << 2);
1610 
1611       // Add the asm string.
1612       const std::string &AsmStr = IA->getAsmString();
1613       Record.push_back(AsmStr.size());
1614       Record.append(AsmStr.begin(), AsmStr.end());
1615 
1616       // Add the constraint string.
1617       const std::string &ConstraintStr = IA->getConstraintString();
1618       Record.push_back(ConstraintStr.size());
1619       Record.append(ConstraintStr.begin(), ConstraintStr.end());
1620       Stream.EmitRecord(bitc::CST_CODE_INLINEASM, Record);
1621       Record.clear();
1622       continue;
1623     }
1624     const Constant *C = cast<Constant>(V);
1625     unsigned Code = -1U;
1626     unsigned AbbrevToUse = 0;
1627     if (C->isNullValue()) {
1628       Code = bitc::CST_CODE_NULL;
1629     } else if (isa<UndefValue>(C)) {
1630       Code = bitc::CST_CODE_UNDEF;
1631     } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {
1632       if (IV->getBitWidth() <= 64) {
1633         uint64_t V = IV->getSExtValue();
1634         emitSignedInt64(Record, V);
1635         Code = bitc::CST_CODE_INTEGER;
1636         AbbrevToUse = CONSTANTS_INTEGER_ABBREV;
1637       } else {                             // Wide integers, > 64 bits in size.
1638         // We have an arbitrary precision integer value to write whose
1639         // bit width is > 64. However, in canonical unsigned integer
1640         // format it is likely that the high bits are going to be zero.
1641         // So, we only write the number of active words.
1642         unsigned NWords = IV->getValue().getActiveWords();
1643         const uint64_t *RawWords = IV->getValue().getRawData();
1644         for (unsigned i = 0; i != NWords; ++i) {
1645           emitSignedInt64(Record, RawWords[i]);
1646         }
1647         Code = bitc::CST_CODE_WIDE_INTEGER;
1648       }
1649     } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
1650       Code = bitc::CST_CODE_FLOAT;
1651       Type *Ty = CFP->getType();
1652       if (Ty->isHalfTy() || Ty->isFloatTy() || Ty->isDoubleTy()) {
1653         Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
1654       } else if (Ty->isX86_FP80Ty()) {
1655         // api needed to prevent premature destruction
1656         // bits are not in the same order as a normal i80 APInt, compensate.
1657         APInt api = CFP->getValueAPF().bitcastToAPInt();
1658         const uint64_t *p = api.getRawData();
1659         Record.push_back((p[1] << 48) | (p[0] >> 16));
1660         Record.push_back(p[0] & 0xffffLL);
1661       } else if (Ty->isFP128Ty() || Ty->isPPC_FP128Ty()) {
1662         APInt api = CFP->getValueAPF().bitcastToAPInt();
1663         const uint64_t *p = api.getRawData();
1664         Record.push_back(p[0]);
1665         Record.push_back(p[1]);
1666       } else {
1667         assert (0 && "Unknown FP type!");
1668       }
1669     } else if (isa<ConstantDataSequential>(C) &&
1670                cast<ConstantDataSequential>(C)->isString()) {
1671       const ConstantDataSequential *Str = cast<ConstantDataSequential>(C);
1672       // Emit constant strings specially.
1673       unsigned NumElts = Str->getNumElements();
1674       // If this is a null-terminated string, use the denser CSTRING encoding.
1675       if (Str->isCString()) {
1676         Code = bitc::CST_CODE_CSTRING;
1677         --NumElts;  // Don't encode the null, which isn't allowed by char6.
1678       } else {
1679         Code = bitc::CST_CODE_STRING;
1680         AbbrevToUse = String8Abbrev;
1681       }
1682       bool isCStr7 = Code == bitc::CST_CODE_CSTRING;
1683       bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING;
1684       for (unsigned i = 0; i != NumElts; ++i) {
1685         unsigned char V = Str->getElementAsInteger(i);
1686         Record.push_back(V);
1687         isCStr7 &= (V & 128) == 0;
1688         if (isCStrChar6)
1689           isCStrChar6 = BitCodeAbbrevOp::isChar6(V);
1690       }
1691 
1692       if (isCStrChar6)
1693         AbbrevToUse = CString6Abbrev;
1694       else if (isCStr7)
1695         AbbrevToUse = CString7Abbrev;
1696     } else if (const ConstantDataSequential *CDS =
1697                   dyn_cast<ConstantDataSequential>(C)) {
1698       Code = bitc::CST_CODE_DATA;
1699       Type *EltTy = CDS->getType()->getElementType();
1700       if (isa<IntegerType>(EltTy)) {
1701         for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
1702           Record.push_back(CDS->getElementAsInteger(i));
1703       } else {
1704         for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
1705           Record.push_back(
1706               CDS->getElementAsAPFloat(i).bitcastToAPInt().getLimitedValue());
1707       }
1708     } else if (isa<ConstantArray>(C) || isa<ConstantStruct>(C) ||
1709                isa<ConstantVector>(C)) {
1710       Code = bitc::CST_CODE_AGGREGATE;
1711       for (const Value *Op : C->operands())
1712         Record.push_back(VE.getValueID(Op));
1713       AbbrevToUse = AggregateAbbrev;
1714     } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1715       switch (CE->getOpcode()) {
1716       default:
1717         if (Instruction::isCast(CE->getOpcode())) {
1718           Code = bitc::CST_CODE_CE_CAST;
1719           Record.push_back(GetEncodedCastOpcode(CE->getOpcode()));
1720           Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
1721           Record.push_back(VE.getValueID(C->getOperand(0)));
1722           AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;
1723         } else {
1724           assert(CE->getNumOperands() == 2 && "Unknown constant expr!");
1725           Code = bitc::CST_CODE_CE_BINOP;
1726           Record.push_back(GetEncodedBinaryOpcode(CE->getOpcode()));
1727           Record.push_back(VE.getValueID(C->getOperand(0)));
1728           Record.push_back(VE.getValueID(C->getOperand(1)));
1729           uint64_t Flags = GetOptimizationFlags(CE);
1730           if (Flags != 0)
1731             Record.push_back(Flags);
1732         }
1733         break;
1734       case Instruction::GetElementPtr: {
1735         Code = bitc::CST_CODE_CE_GEP;
1736         const auto *GO = cast<GEPOperator>(C);
1737         if (GO->isInBounds())
1738           Code = bitc::CST_CODE_CE_INBOUNDS_GEP;
1739         Record.push_back(VE.getTypeID(GO->getSourceElementType()));
1740         for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
1741           Record.push_back(VE.getTypeID(C->getOperand(i)->getType()));
1742           Record.push_back(VE.getValueID(C->getOperand(i)));
1743         }
1744         break;
1745       }
1746       case Instruction::Select:
1747         Code = bitc::CST_CODE_CE_SELECT;
1748         Record.push_back(VE.getValueID(C->getOperand(0)));
1749         Record.push_back(VE.getValueID(C->getOperand(1)));
1750         Record.push_back(VE.getValueID(C->getOperand(2)));
1751         break;
1752       case Instruction::ExtractElement:
1753         Code = bitc::CST_CODE_CE_EXTRACTELT;
1754         Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
1755         Record.push_back(VE.getValueID(C->getOperand(0)));
1756         Record.push_back(VE.getTypeID(C->getOperand(1)->getType()));
1757         Record.push_back(VE.getValueID(C->getOperand(1)));
1758         break;
1759       case Instruction::InsertElement:
1760         Code = bitc::CST_CODE_CE_INSERTELT;
1761         Record.push_back(VE.getValueID(C->getOperand(0)));
1762         Record.push_back(VE.getValueID(C->getOperand(1)));
1763         Record.push_back(VE.getTypeID(C->getOperand(2)->getType()));
1764         Record.push_back(VE.getValueID(C->getOperand(2)));
1765         break;
1766       case Instruction::ShuffleVector:
1767         // If the return type and argument types are the same, this is a
1768         // standard shufflevector instruction.  If the types are different,
1769         // then the shuffle is widening or truncating the input vectors, and
1770         // the argument type must also be encoded.
1771         if (C->getType() == C->getOperand(0)->getType()) {
1772           Code = bitc::CST_CODE_CE_SHUFFLEVEC;
1773         } else {
1774           Code = bitc::CST_CODE_CE_SHUFVEC_EX;
1775           Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
1776         }
1777         Record.push_back(VE.getValueID(C->getOperand(0)));
1778         Record.push_back(VE.getValueID(C->getOperand(1)));
1779         Record.push_back(VE.getValueID(C->getOperand(2)));
1780         break;
1781       case Instruction::ICmp:
1782       case Instruction::FCmp:
1783         Code = bitc::CST_CODE_CE_CMP;
1784         Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
1785         Record.push_back(VE.getValueID(C->getOperand(0)));
1786         Record.push_back(VE.getValueID(C->getOperand(1)));
1787         Record.push_back(CE->getPredicate());
1788         break;
1789       }
1790     } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) {
1791       Code = bitc::CST_CODE_BLOCKADDRESS;
1792       Record.push_back(VE.getTypeID(BA->getFunction()->getType()));
1793       Record.push_back(VE.getValueID(BA->getFunction()));
1794       Record.push_back(VE.getGlobalBasicBlockID(BA->getBasicBlock()));
1795     } else {
1796 #ifndef NDEBUG
1797       C->dump();
1798 #endif
1799       llvm_unreachable("Unknown constant!");
1800     }
1801     Stream.EmitRecord(Code, Record, AbbrevToUse);
1802     Record.clear();
1803   }
1804 
1805   Stream.ExitBlock();
1806 }
1807 
1808 static void WriteModuleConstants(const ValueEnumerator &VE,
1809                                  BitstreamWriter &Stream) {
1810   const ValueEnumerator::ValueList &Vals = VE.getValues();
1811 
1812   // Find the first constant to emit, which is the first non-globalvalue value.
1813   // We know globalvalues have been emitted by WriteModuleInfo.
1814   for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
1815     if (!isa<GlobalValue>(Vals[i].first)) {
1816       WriteConstants(i, Vals.size(), VE, Stream, true);
1817       return;
1818     }
1819   }
1820 }
1821 
1822 /// PushValueAndType - The file has to encode both the value and type id for
1823 /// many values, because we need to know what type to create for forward
1824 /// references.  However, most operands are not forward references, so this type
1825 /// field is not needed.
1826 ///
1827 /// This function adds V's value ID to Vals.  If the value ID is higher than the
1828 /// instruction ID, then it is a forward reference, and it also includes the
1829 /// type ID.  The value ID that is written is encoded relative to the InstID.
1830 static bool PushValueAndType(const Value *V, unsigned InstID,
1831                              SmallVectorImpl<unsigned> &Vals,
1832                              ValueEnumerator &VE) {
1833   unsigned ValID = VE.getValueID(V);
1834   // Make encoding relative to the InstID.
1835   Vals.push_back(InstID - ValID);
1836   if (ValID >= InstID) {
1837     Vals.push_back(VE.getTypeID(V->getType()));
1838     return true;
1839   }
1840   return false;
1841 }
1842 
1843 static void WriteOperandBundles(BitstreamWriter &Stream, ImmutableCallSite CS,
1844                                 unsigned InstID, ValueEnumerator &VE) {
1845   SmallVector<unsigned, 64> Record;
1846   LLVMContext &C = CS.getInstruction()->getContext();
1847 
1848   for (unsigned i = 0, e = CS.getNumOperandBundles(); i != e; ++i) {
1849     const auto &Bundle = CS.getOperandBundleAt(i);
1850     Record.push_back(C.getOperandBundleTagID(Bundle.getTagName()));
1851 
1852     for (auto &Input : Bundle.Inputs)
1853       PushValueAndType(Input, InstID, Record, VE);
1854 
1855     Stream.EmitRecord(bitc::FUNC_CODE_OPERAND_BUNDLE, Record);
1856     Record.clear();
1857   }
1858 }
1859 
1860 /// pushValue - Like PushValueAndType, but where the type of the value is
1861 /// omitted (perhaps it was already encoded in an earlier operand).
1862 static void pushValue(const Value *V, unsigned InstID,
1863                       SmallVectorImpl<unsigned> &Vals,
1864                       ValueEnumerator &VE) {
1865   unsigned ValID = VE.getValueID(V);
1866   Vals.push_back(InstID - ValID);
1867 }
1868 
1869 static void pushValueSigned(const Value *V, unsigned InstID,
1870                             SmallVectorImpl<uint64_t> &Vals,
1871                             ValueEnumerator &VE) {
1872   unsigned ValID = VE.getValueID(V);
1873   int64_t diff = ((int32_t)InstID - (int32_t)ValID);
1874   emitSignedInt64(Vals, diff);
1875 }
1876 
1877 /// WriteInstruction - Emit an instruction to the specified stream.
1878 static void WriteInstruction(const Instruction &I, unsigned InstID,
1879                              ValueEnumerator &VE, BitstreamWriter &Stream,
1880                              SmallVectorImpl<unsigned> &Vals) {
1881   unsigned Code = 0;
1882   unsigned AbbrevToUse = 0;
1883   VE.setInstructionID(&I);
1884   switch (I.getOpcode()) {
1885   default:
1886     if (Instruction::isCast(I.getOpcode())) {
1887       Code = bitc::FUNC_CODE_INST_CAST;
1888       if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
1889         AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
1890       Vals.push_back(VE.getTypeID(I.getType()));
1891       Vals.push_back(GetEncodedCastOpcode(I.getOpcode()));
1892     } else {
1893       assert(isa<BinaryOperator>(I) && "Unknown instruction!");
1894       Code = bitc::FUNC_CODE_INST_BINOP;
1895       if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
1896         AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
1897       pushValue(I.getOperand(1), InstID, Vals, VE);
1898       Vals.push_back(GetEncodedBinaryOpcode(I.getOpcode()));
1899       uint64_t Flags = GetOptimizationFlags(&I);
1900       if (Flags != 0) {
1901         if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV)
1902           AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV;
1903         Vals.push_back(Flags);
1904       }
1905     }
1906     break;
1907 
1908   case Instruction::GetElementPtr: {
1909     Code = bitc::FUNC_CODE_INST_GEP;
1910     AbbrevToUse = FUNCTION_INST_GEP_ABBREV;
1911     auto &GEPInst = cast<GetElementPtrInst>(I);
1912     Vals.push_back(GEPInst.isInBounds());
1913     Vals.push_back(VE.getTypeID(GEPInst.getSourceElementType()));
1914     for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
1915       PushValueAndType(I.getOperand(i), InstID, Vals, VE);
1916     break;
1917   }
1918   case Instruction::ExtractValue: {
1919     Code = bitc::FUNC_CODE_INST_EXTRACTVAL;
1920     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1921     const ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
1922     Vals.append(EVI->idx_begin(), EVI->idx_end());
1923     break;
1924   }
1925   case Instruction::InsertValue: {
1926     Code = bitc::FUNC_CODE_INST_INSERTVAL;
1927     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1928     PushValueAndType(I.getOperand(1), InstID, Vals, VE);
1929     const InsertValueInst *IVI = cast<InsertValueInst>(&I);
1930     Vals.append(IVI->idx_begin(), IVI->idx_end());
1931     break;
1932   }
1933   case Instruction::Select:
1934     Code = bitc::FUNC_CODE_INST_VSELECT;
1935     PushValueAndType(I.getOperand(1), InstID, Vals, VE);
1936     pushValue(I.getOperand(2), InstID, Vals, VE);
1937     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1938     break;
1939   case Instruction::ExtractElement:
1940     Code = bitc::FUNC_CODE_INST_EXTRACTELT;
1941     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1942     PushValueAndType(I.getOperand(1), InstID, Vals, VE);
1943     break;
1944   case Instruction::InsertElement:
1945     Code = bitc::FUNC_CODE_INST_INSERTELT;
1946     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1947     pushValue(I.getOperand(1), InstID, Vals, VE);
1948     PushValueAndType(I.getOperand(2), InstID, Vals, VE);
1949     break;
1950   case Instruction::ShuffleVector:
1951     Code = bitc::FUNC_CODE_INST_SHUFFLEVEC;
1952     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1953     pushValue(I.getOperand(1), InstID, Vals, VE);
1954     pushValue(I.getOperand(2), InstID, Vals, VE);
1955     break;
1956   case Instruction::ICmp:
1957   case Instruction::FCmp: {
1958     // compare returning Int1Ty or vector of Int1Ty
1959     Code = bitc::FUNC_CODE_INST_CMP2;
1960     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1961     pushValue(I.getOperand(1), InstID, Vals, VE);
1962     Vals.push_back(cast<CmpInst>(I).getPredicate());
1963     uint64_t Flags = GetOptimizationFlags(&I);
1964     if (Flags != 0)
1965       Vals.push_back(Flags);
1966     break;
1967   }
1968 
1969   case Instruction::Ret:
1970     {
1971       Code = bitc::FUNC_CODE_INST_RET;
1972       unsigned NumOperands = I.getNumOperands();
1973       if (NumOperands == 0)
1974         AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
1975       else if (NumOperands == 1) {
1976         if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
1977           AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
1978       } else {
1979         for (unsigned i = 0, e = NumOperands; i != e; ++i)
1980           PushValueAndType(I.getOperand(i), InstID, Vals, VE);
1981       }
1982     }
1983     break;
1984   case Instruction::Br:
1985     {
1986       Code = bitc::FUNC_CODE_INST_BR;
1987       const BranchInst &II = cast<BranchInst>(I);
1988       Vals.push_back(VE.getValueID(II.getSuccessor(0)));
1989       if (II.isConditional()) {
1990         Vals.push_back(VE.getValueID(II.getSuccessor(1)));
1991         pushValue(II.getCondition(), InstID, Vals, VE);
1992       }
1993     }
1994     break;
1995   case Instruction::Switch:
1996     {
1997       Code = bitc::FUNC_CODE_INST_SWITCH;
1998       const SwitchInst &SI = cast<SwitchInst>(I);
1999       Vals.push_back(VE.getTypeID(SI.getCondition()->getType()));
2000       pushValue(SI.getCondition(), InstID, Vals, VE);
2001       Vals.push_back(VE.getValueID(SI.getDefaultDest()));
2002       for (SwitchInst::ConstCaseIt Case : SI.cases()) {
2003         Vals.push_back(VE.getValueID(Case.getCaseValue()));
2004         Vals.push_back(VE.getValueID(Case.getCaseSuccessor()));
2005       }
2006     }
2007     break;
2008   case Instruction::IndirectBr:
2009     Code = bitc::FUNC_CODE_INST_INDIRECTBR;
2010     Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
2011     // Encode the address operand as relative, but not the basic blocks.
2012     pushValue(I.getOperand(0), InstID, Vals, VE);
2013     for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i)
2014       Vals.push_back(VE.getValueID(I.getOperand(i)));
2015     break;
2016 
2017   case Instruction::Invoke: {
2018     const InvokeInst *II = cast<InvokeInst>(&I);
2019     const Value *Callee = II->getCalledValue();
2020     FunctionType *FTy = II->getFunctionType();
2021 
2022     if (II->hasOperandBundles())
2023       WriteOperandBundles(Stream, II, InstID, VE);
2024 
2025     Code = bitc::FUNC_CODE_INST_INVOKE;
2026 
2027     Vals.push_back(VE.getAttributeID(II->getAttributes()));
2028     Vals.push_back(II->getCallingConv() | 1 << 13);
2029     Vals.push_back(VE.getValueID(II->getNormalDest()));
2030     Vals.push_back(VE.getValueID(II->getUnwindDest()));
2031     Vals.push_back(VE.getTypeID(FTy));
2032     PushValueAndType(Callee, InstID, Vals, VE);
2033 
2034     // Emit value #'s for the fixed parameters.
2035     for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
2036       pushValue(I.getOperand(i), InstID, Vals, VE);  // fixed param.
2037 
2038     // Emit type/value pairs for varargs params.
2039     if (FTy->isVarArg()) {
2040       for (unsigned i = FTy->getNumParams(), e = I.getNumOperands()-3;
2041            i != e; ++i)
2042         PushValueAndType(I.getOperand(i), InstID, Vals, VE); // vararg
2043     }
2044     break;
2045   }
2046   case Instruction::Resume:
2047     Code = bitc::FUNC_CODE_INST_RESUME;
2048     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
2049     break;
2050   case Instruction::CleanupRet: {
2051     Code = bitc::FUNC_CODE_INST_CLEANUPRET;
2052     const auto &CRI = cast<CleanupReturnInst>(I);
2053     pushValue(CRI.getCleanupPad(), InstID, Vals, VE);
2054     if (CRI.hasUnwindDest())
2055       Vals.push_back(VE.getValueID(CRI.getUnwindDest()));
2056     break;
2057   }
2058   case Instruction::CatchRet: {
2059     Code = bitc::FUNC_CODE_INST_CATCHRET;
2060     const auto &CRI = cast<CatchReturnInst>(I);
2061     pushValue(CRI.getCatchPad(), InstID, Vals, VE);
2062     Vals.push_back(VE.getValueID(CRI.getSuccessor()));
2063     break;
2064   }
2065   case Instruction::CleanupPad:
2066   case Instruction::CatchPad: {
2067     const auto &FuncletPad = cast<FuncletPadInst>(I);
2068     Code = isa<CatchPadInst>(FuncletPad) ? bitc::FUNC_CODE_INST_CATCHPAD
2069                                          : bitc::FUNC_CODE_INST_CLEANUPPAD;
2070     pushValue(FuncletPad.getParentPad(), InstID, Vals, VE);
2071 
2072     unsigned NumArgOperands = FuncletPad.getNumArgOperands();
2073     Vals.push_back(NumArgOperands);
2074     for (unsigned Op = 0; Op != NumArgOperands; ++Op)
2075       PushValueAndType(FuncletPad.getArgOperand(Op), InstID, Vals, VE);
2076     break;
2077   }
2078   case Instruction::CatchSwitch: {
2079     Code = bitc::FUNC_CODE_INST_CATCHSWITCH;
2080     const auto &CatchSwitch = cast<CatchSwitchInst>(I);
2081 
2082     pushValue(CatchSwitch.getParentPad(), InstID, Vals, VE);
2083 
2084     unsigned NumHandlers = CatchSwitch.getNumHandlers();
2085     Vals.push_back(NumHandlers);
2086     for (const BasicBlock *CatchPadBB : CatchSwitch.handlers())
2087       Vals.push_back(VE.getValueID(CatchPadBB));
2088 
2089     if (CatchSwitch.hasUnwindDest())
2090       Vals.push_back(VE.getValueID(CatchSwitch.getUnwindDest()));
2091     break;
2092   }
2093   case Instruction::Unreachable:
2094     Code = bitc::FUNC_CODE_INST_UNREACHABLE;
2095     AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
2096     break;
2097 
2098   case Instruction::PHI: {
2099     const PHINode &PN = cast<PHINode>(I);
2100     Code = bitc::FUNC_CODE_INST_PHI;
2101     // With the newer instruction encoding, forward references could give
2102     // negative valued IDs.  This is most common for PHIs, so we use
2103     // signed VBRs.
2104     SmallVector<uint64_t, 128> Vals64;
2105     Vals64.push_back(VE.getTypeID(PN.getType()));
2106     for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
2107       pushValueSigned(PN.getIncomingValue(i), InstID, Vals64, VE);
2108       Vals64.push_back(VE.getValueID(PN.getIncomingBlock(i)));
2109     }
2110     // Emit a Vals64 vector and exit.
2111     Stream.EmitRecord(Code, Vals64, AbbrevToUse);
2112     Vals64.clear();
2113     return;
2114   }
2115 
2116   case Instruction::LandingPad: {
2117     const LandingPadInst &LP = cast<LandingPadInst>(I);
2118     Code = bitc::FUNC_CODE_INST_LANDINGPAD;
2119     Vals.push_back(VE.getTypeID(LP.getType()));
2120     Vals.push_back(LP.isCleanup());
2121     Vals.push_back(LP.getNumClauses());
2122     for (unsigned I = 0, E = LP.getNumClauses(); I != E; ++I) {
2123       if (LP.isCatch(I))
2124         Vals.push_back(LandingPadInst::Catch);
2125       else
2126         Vals.push_back(LandingPadInst::Filter);
2127       PushValueAndType(LP.getClause(I), InstID, Vals, VE);
2128     }
2129     break;
2130   }
2131 
2132   case Instruction::Alloca: {
2133     Code = bitc::FUNC_CODE_INST_ALLOCA;
2134     const AllocaInst &AI = cast<AllocaInst>(I);
2135     Vals.push_back(VE.getTypeID(AI.getAllocatedType()));
2136     Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
2137     Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
2138     unsigned AlignRecord = Log2_32(AI.getAlignment()) + 1;
2139     assert(Log2_32(Value::MaximumAlignment) + 1 < 1 << 5 &&
2140            "not enough bits for maximum alignment");
2141     assert(AlignRecord < 1 << 5 && "alignment greater than 1 << 64");
2142     AlignRecord |= AI.isUsedWithInAlloca() << 5;
2143     AlignRecord |= 1 << 6;
2144     // Reserve bit 7 for SwiftError flag.
2145     // AlignRecord |= AI.isSwiftError() << 7;
2146     Vals.push_back(AlignRecord);
2147     break;
2148   }
2149 
2150   case Instruction::Load:
2151     if (cast<LoadInst>(I).isAtomic()) {
2152       Code = bitc::FUNC_CODE_INST_LOADATOMIC;
2153       PushValueAndType(I.getOperand(0), InstID, Vals, VE);
2154     } else {
2155       Code = bitc::FUNC_CODE_INST_LOAD;
2156       if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))  // ptr
2157         AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
2158     }
2159     Vals.push_back(VE.getTypeID(I.getType()));
2160     Vals.push_back(Log2_32(cast<LoadInst>(I).getAlignment())+1);
2161     Vals.push_back(cast<LoadInst>(I).isVolatile());
2162     if (cast<LoadInst>(I).isAtomic()) {
2163       Vals.push_back(GetEncodedOrdering(cast<LoadInst>(I).getOrdering()));
2164       Vals.push_back(GetEncodedSynchScope(cast<LoadInst>(I).getSynchScope()));
2165     }
2166     break;
2167   case Instruction::Store:
2168     if (cast<StoreInst>(I).isAtomic())
2169       Code = bitc::FUNC_CODE_INST_STOREATOMIC;
2170     else
2171       Code = bitc::FUNC_CODE_INST_STORE;
2172     PushValueAndType(I.getOperand(1), InstID, Vals, VE);  // ptrty + ptr
2173     PushValueAndType(I.getOperand(0), InstID, Vals, VE);  // valty + val
2174     Vals.push_back(Log2_32(cast<StoreInst>(I).getAlignment())+1);
2175     Vals.push_back(cast<StoreInst>(I).isVolatile());
2176     if (cast<StoreInst>(I).isAtomic()) {
2177       Vals.push_back(GetEncodedOrdering(cast<StoreInst>(I).getOrdering()));
2178       Vals.push_back(GetEncodedSynchScope(cast<StoreInst>(I).getSynchScope()));
2179     }
2180     break;
2181   case Instruction::AtomicCmpXchg:
2182     Code = bitc::FUNC_CODE_INST_CMPXCHG;
2183     PushValueAndType(I.getOperand(0), InstID, Vals, VE);  // ptrty + ptr
2184     PushValueAndType(I.getOperand(1), InstID, Vals, VE);  // cmp.
2185     pushValue(I.getOperand(2), InstID, Vals, VE);         // newval.
2186     Vals.push_back(cast<AtomicCmpXchgInst>(I).isVolatile());
2187     Vals.push_back(GetEncodedOrdering(
2188                      cast<AtomicCmpXchgInst>(I).getSuccessOrdering()));
2189     Vals.push_back(GetEncodedSynchScope(
2190                      cast<AtomicCmpXchgInst>(I).getSynchScope()));
2191     Vals.push_back(GetEncodedOrdering(
2192                      cast<AtomicCmpXchgInst>(I).getFailureOrdering()));
2193     Vals.push_back(cast<AtomicCmpXchgInst>(I).isWeak());
2194     break;
2195   case Instruction::AtomicRMW:
2196     Code = bitc::FUNC_CODE_INST_ATOMICRMW;
2197     PushValueAndType(I.getOperand(0), InstID, Vals, VE);  // ptrty + ptr
2198     pushValue(I.getOperand(1), InstID, Vals, VE);         // val.
2199     Vals.push_back(GetEncodedRMWOperation(
2200                      cast<AtomicRMWInst>(I).getOperation()));
2201     Vals.push_back(cast<AtomicRMWInst>(I).isVolatile());
2202     Vals.push_back(GetEncodedOrdering(cast<AtomicRMWInst>(I).getOrdering()));
2203     Vals.push_back(GetEncodedSynchScope(
2204                      cast<AtomicRMWInst>(I).getSynchScope()));
2205     break;
2206   case Instruction::Fence:
2207     Code = bitc::FUNC_CODE_INST_FENCE;
2208     Vals.push_back(GetEncodedOrdering(cast<FenceInst>(I).getOrdering()));
2209     Vals.push_back(GetEncodedSynchScope(cast<FenceInst>(I).getSynchScope()));
2210     break;
2211   case Instruction::Call: {
2212     const CallInst &CI = cast<CallInst>(I);
2213     FunctionType *FTy = CI.getFunctionType();
2214 
2215     if (CI.hasOperandBundles())
2216       WriteOperandBundles(Stream, &CI, InstID, VE);
2217 
2218     Code = bitc::FUNC_CODE_INST_CALL;
2219 
2220     Vals.push_back(VE.getAttributeID(CI.getAttributes()));
2221 
2222     unsigned Flags = GetOptimizationFlags(&I);
2223     Vals.push_back(CI.getCallingConv() << bitc::CALL_CCONV |
2224                    unsigned(CI.isTailCall()) << bitc::CALL_TAIL |
2225                    unsigned(CI.isMustTailCall()) << bitc::CALL_MUSTTAIL |
2226                    1 << bitc::CALL_EXPLICIT_TYPE |
2227                    unsigned(CI.isNoTailCall()) << bitc::CALL_NOTAIL |
2228                    unsigned(Flags != 0) << bitc::CALL_FMF);
2229     if (Flags != 0)
2230       Vals.push_back(Flags);
2231 
2232     Vals.push_back(VE.getTypeID(FTy));
2233     PushValueAndType(CI.getCalledValue(), InstID, Vals, VE);  // Callee
2234 
2235     // Emit value #'s for the fixed parameters.
2236     for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
2237       // Check for labels (can happen with asm labels).
2238       if (FTy->getParamType(i)->isLabelTy())
2239         Vals.push_back(VE.getValueID(CI.getArgOperand(i)));
2240       else
2241         pushValue(CI.getArgOperand(i), InstID, Vals, VE);  // fixed param.
2242     }
2243 
2244     // Emit type/value pairs for varargs params.
2245     if (FTy->isVarArg()) {
2246       for (unsigned i = FTy->getNumParams(), e = CI.getNumArgOperands();
2247            i != e; ++i)
2248         PushValueAndType(CI.getArgOperand(i), InstID, Vals, VE);  // varargs
2249     }
2250     break;
2251   }
2252   case Instruction::VAArg:
2253     Code = bitc::FUNC_CODE_INST_VAARG;
2254     Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));   // valistty
2255     pushValue(I.getOperand(0), InstID, Vals, VE); // valist.
2256     Vals.push_back(VE.getTypeID(I.getType())); // restype.
2257     break;
2258   }
2259 
2260   Stream.EmitRecord(Code, Vals, AbbrevToUse);
2261   Vals.clear();
2262 }
2263 
2264 /// Emit names for globals/functions etc. The VSTOffsetPlaceholder,
2265 /// BitcodeStartBit and ModuleSummaryIndex are only passed for the module-level
2266 /// VST, where we are including a function bitcode index and need to
2267 /// backpatch the VST forward declaration record.
2268 static void WriteValueSymbolTable(
2269     const ValueSymbolTable &VST, const ValueEnumerator &VE,
2270     BitstreamWriter &Stream, uint64_t VSTOffsetPlaceholder = 0,
2271     uint64_t BitcodeStartBit = 0,
2272     DenseMap<const Function *, std::unique_ptr<GlobalValueInfo>>
2273         *FunctionIndex = nullptr) {
2274   if (VST.empty()) {
2275     // WriteValueSymbolTableForwardDecl should have returned early as
2276     // well. Ensure this handling remains in sync by asserting that
2277     // the placeholder offset is not set.
2278     assert(VSTOffsetPlaceholder == 0);
2279     return;
2280   }
2281 
2282   if (VSTOffsetPlaceholder > 0) {
2283     // Get the offset of the VST we are writing, and backpatch it into
2284     // the VST forward declaration record.
2285     uint64_t VSTOffset = Stream.GetCurrentBitNo();
2286     // The BitcodeStartBit was the stream offset of the actual bitcode
2287     // (e.g. excluding any initial darwin header).
2288     VSTOffset -= BitcodeStartBit;
2289     assert((VSTOffset & 31) == 0 && "VST block not 32-bit aligned");
2290     Stream.BackpatchWord(VSTOffsetPlaceholder, VSTOffset / 32);
2291   }
2292 
2293   Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
2294 
2295   // For the module-level VST, add abbrev Ids for the VST_CODE_FNENTRY
2296   // records, which are not used in the per-function VSTs.
2297   unsigned FnEntry8BitAbbrev;
2298   unsigned FnEntry7BitAbbrev;
2299   unsigned FnEntry6BitAbbrev;
2300   if (VSTOffsetPlaceholder > 0) {
2301     // 8-bit fixed-width VST_CODE_FNENTRY function strings.
2302     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2303     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_FNENTRY));
2304     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
2305     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // funcoffset
2306     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2307     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
2308     FnEntry8BitAbbrev = Stream.EmitAbbrev(Abbv);
2309 
2310     // 7-bit fixed width VST_CODE_FNENTRY function strings.
2311     Abbv = new BitCodeAbbrev();
2312     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_FNENTRY));
2313     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
2314     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // funcoffset
2315     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2316     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
2317     FnEntry7BitAbbrev = Stream.EmitAbbrev(Abbv);
2318 
2319     // 6-bit char6 VST_CODE_FNENTRY function strings.
2320     Abbv = new BitCodeAbbrev();
2321     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_FNENTRY));
2322     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
2323     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // funcoffset
2324     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2325     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
2326     FnEntry6BitAbbrev = Stream.EmitAbbrev(Abbv);
2327   }
2328 
2329   // FIXME: Set up the abbrev, we know how many values there are!
2330   // FIXME: We know if the type names can use 7-bit ascii.
2331   SmallVector<unsigned, 64> NameVals;
2332 
2333   for (const ValueName &Name : VST) {
2334     // Figure out the encoding to use for the name.
2335     StringEncoding Bits =
2336         getStringEncoding(Name.getKeyData(), Name.getKeyLength());
2337 
2338     unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
2339     NameVals.push_back(VE.getValueID(Name.getValue()));
2340 
2341     Function *F = dyn_cast<Function>(Name.getValue());
2342     if (!F) {
2343       // If value is an alias, need to get the aliased base object to
2344       // see if it is a function.
2345       auto *GA = dyn_cast<GlobalAlias>(Name.getValue());
2346       if (GA && GA->getBaseObject())
2347         F = dyn_cast<Function>(GA->getBaseObject());
2348     }
2349 
2350     // VST_CODE_ENTRY:   [valueid, namechar x N]
2351     // VST_CODE_FNENTRY: [valueid, funcoffset, namechar x N]
2352     // VST_CODE_BBENTRY: [bbid, namechar x N]
2353     unsigned Code;
2354     if (isa<BasicBlock>(Name.getValue())) {
2355       Code = bitc::VST_CODE_BBENTRY;
2356       if (Bits == SE_Char6)
2357         AbbrevToUse = VST_BBENTRY_6_ABBREV;
2358     } else if (F && !F->isDeclaration()) {
2359       // Must be the module-level VST, where we pass in the Index and
2360       // have a VSTOffsetPlaceholder. The function-level VST should not
2361       // contain any Function symbols.
2362       assert(FunctionIndex);
2363       assert(VSTOffsetPlaceholder > 0);
2364 
2365       // Save the word offset of the function (from the start of the
2366       // actual bitcode written to the stream).
2367       uint64_t BitcodeIndex =
2368           (*FunctionIndex)[F]->bitcodeIndex() - BitcodeStartBit;
2369       assert((BitcodeIndex & 31) == 0 && "function block not 32-bit aligned");
2370       NameVals.push_back(BitcodeIndex / 32);
2371 
2372       Code = bitc::VST_CODE_FNENTRY;
2373       AbbrevToUse = FnEntry8BitAbbrev;
2374       if (Bits == SE_Char6)
2375         AbbrevToUse = FnEntry6BitAbbrev;
2376       else if (Bits == SE_Fixed7)
2377         AbbrevToUse = FnEntry7BitAbbrev;
2378     } else {
2379       Code = bitc::VST_CODE_ENTRY;
2380       if (Bits == SE_Char6)
2381         AbbrevToUse = VST_ENTRY_6_ABBREV;
2382       else if (Bits == SE_Fixed7)
2383         AbbrevToUse = VST_ENTRY_7_ABBREV;
2384     }
2385 
2386     for (const auto P : Name.getKey())
2387       NameVals.push_back((unsigned char)P);
2388 
2389     // Emit the finished record.
2390     Stream.EmitRecord(Code, NameVals, AbbrevToUse);
2391     NameVals.clear();
2392   }
2393   Stream.ExitBlock();
2394 }
2395 
2396 /// Emit function names and summary offsets for the combined index
2397 /// used by ThinLTO.
2398 static void
2399 WriteCombinedValueSymbolTable(const ModuleSummaryIndex &Index,
2400                               BitstreamWriter &Stream,
2401                               std::map<uint64_t, unsigned> &GUIDToValueIdMap,
2402                               uint64_t VSTOffsetPlaceholder) {
2403   assert(VSTOffsetPlaceholder > 0 && "Expected non-zero VSTOffsetPlaceholder");
2404   // Get the offset of the VST we are writing, and backpatch it into
2405   // the VST forward declaration record.
2406   uint64_t VSTOffset = Stream.GetCurrentBitNo();
2407   assert((VSTOffset & 31) == 0 && "VST block not 32-bit aligned");
2408   Stream.BackpatchWord(VSTOffsetPlaceholder, VSTOffset / 32);
2409 
2410   Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
2411 
2412   BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2413   Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_COMBINED_GVDEFENTRY));
2414   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
2415   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // sumoffset
2416   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // guid
2417   unsigned DefEntryAbbrev = Stream.EmitAbbrev(Abbv);
2418 
2419   Abbv = new BitCodeAbbrev();
2420   Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_COMBINED_ENTRY));
2421   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
2422   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // refguid
2423   unsigned EntryAbbrev = Stream.EmitAbbrev(Abbv);
2424 
2425   SmallVector<uint64_t, 64> NameVals;
2426 
2427   for (const auto &FII : Index) {
2428     uint64_t FuncGUID = FII.first;
2429     const auto &VMI = GUIDToValueIdMap.find(FuncGUID);
2430     assert(VMI != GUIDToValueIdMap.end());
2431 
2432     for (const auto &FI : FII.second) {
2433       // VST_CODE_COMBINED_GVDEFENTRY: [valueid, sumoffset, guid]
2434       NameVals.push_back(VMI->second);
2435       NameVals.push_back(FI->bitcodeIndex());
2436       NameVals.push_back(FuncGUID);
2437 
2438       // Emit the finished record.
2439       Stream.EmitRecord(bitc::VST_CODE_COMBINED_GVDEFENTRY, NameVals,
2440                         DefEntryAbbrev);
2441       NameVals.clear();
2442     }
2443     GUIDToValueIdMap.erase(VMI);
2444   }
2445   for (const auto &GVI : GUIDToValueIdMap) {
2446     // VST_CODE_COMBINED_ENTRY: [valueid, refguid]
2447     NameVals.push_back(GVI.second);
2448     NameVals.push_back(GVI.first);
2449 
2450     // Emit the finished record.
2451     Stream.EmitRecord(bitc::VST_CODE_COMBINED_ENTRY, NameVals, EntryAbbrev);
2452     NameVals.clear();
2453   }
2454   Stream.ExitBlock();
2455 }
2456 
2457 static void WriteUseList(ValueEnumerator &VE, UseListOrder &&Order,
2458                          BitstreamWriter &Stream) {
2459   assert(Order.Shuffle.size() >= 2 && "Shuffle too small");
2460   unsigned Code;
2461   if (isa<BasicBlock>(Order.V))
2462     Code = bitc::USELIST_CODE_BB;
2463   else
2464     Code = bitc::USELIST_CODE_DEFAULT;
2465 
2466   SmallVector<uint64_t, 64> Record(Order.Shuffle.begin(), Order.Shuffle.end());
2467   Record.push_back(VE.getValueID(Order.V));
2468   Stream.EmitRecord(Code, Record);
2469 }
2470 
2471 static void WriteUseListBlock(const Function *F, ValueEnumerator &VE,
2472                               BitstreamWriter &Stream) {
2473   assert(VE.shouldPreserveUseListOrder() &&
2474          "Expected to be preserving use-list order");
2475 
2476   auto hasMore = [&]() {
2477     return !VE.UseListOrders.empty() && VE.UseListOrders.back().F == F;
2478   };
2479   if (!hasMore())
2480     // Nothing to do.
2481     return;
2482 
2483   Stream.EnterSubblock(bitc::USELIST_BLOCK_ID, 3);
2484   while (hasMore()) {
2485     WriteUseList(VE, std::move(VE.UseListOrders.back()), Stream);
2486     VE.UseListOrders.pop_back();
2487   }
2488   Stream.ExitBlock();
2489 }
2490 
2491 // Walk through the operands of a given User via worklist iteration and populate
2492 // the set of GlobalValue references encountered. Invoked either on an
2493 // Instruction or a GlobalVariable (which walks its initializer).
2494 static void findRefEdges(const User *CurUser, const ValueEnumerator &VE,
2495                          DenseSet<unsigned> &RefEdges,
2496                          SmallPtrSet<const User *, 8> &Visited) {
2497   SmallVector<const User *, 32> Worklist;
2498   Worklist.push_back(CurUser);
2499 
2500   while (!Worklist.empty()) {
2501     const User *U = Worklist.pop_back_val();
2502 
2503     if (!Visited.insert(U).second)
2504       continue;
2505 
2506     ImmutableCallSite CS(U);
2507 
2508     for (const auto &OI : U->operands()) {
2509       const User *Operand = dyn_cast<User>(OI);
2510       if (!Operand)
2511         continue;
2512       if (isa<BlockAddress>(Operand))
2513         continue;
2514       if (isa<GlobalValue>(Operand)) {
2515         // We have a reference to a global value. This should be added to
2516         // the reference set unless it is a callee. Callees are handled
2517         // specially by WriteFunction and are added to a separate list.
2518         if (!(CS && CS.isCallee(&OI)))
2519           RefEdges.insert(VE.getValueID(Operand));
2520         continue;
2521       }
2522       Worklist.push_back(Operand);
2523     }
2524   }
2525 }
2526 
2527 /// Emit a function body to the module stream.
2528 static void WriteFunction(
2529     const Function &F, const Module *M, ValueEnumerator &VE,
2530     BitstreamWriter &Stream,
2531     DenseMap<const Function *, std::unique_ptr<GlobalValueInfo>> &FunctionIndex,
2532     bool EmitSummaryIndex) {
2533   // Save the bitcode index of the start of this function block for recording
2534   // in the VST.
2535   uint64_t BitcodeIndex = Stream.GetCurrentBitNo();
2536 
2537   bool HasProfileData = F.getEntryCount().hasValue();
2538   std::unique_ptr<BlockFrequencyInfo> BFI;
2539   if (EmitSummaryIndex && HasProfileData) {
2540     Function &Func = const_cast<Function &>(F);
2541     LoopInfo LI{DominatorTree(Func)};
2542     BranchProbabilityInfo BPI{Func, LI};
2543     BFI = llvm::make_unique<BlockFrequencyInfo>(Func, BPI, LI);
2544   }
2545 
2546   Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 4);
2547   VE.incorporateFunction(F);
2548 
2549   SmallVector<unsigned, 64> Vals;
2550 
2551   // Emit the number of basic blocks, so the reader can create them ahead of
2552   // time.
2553   Vals.push_back(VE.getBasicBlocks().size());
2554   Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals);
2555   Vals.clear();
2556 
2557   // If there are function-local constants, emit them now.
2558   unsigned CstStart, CstEnd;
2559   VE.getFunctionConstantRange(CstStart, CstEnd);
2560   WriteConstants(CstStart, CstEnd, VE, Stream, false);
2561 
2562   // If there is function-local metadata, emit it now.
2563   writeFunctionMetadata(F, VE, Stream);
2564 
2565   // Keep a running idea of what the instruction ID is.
2566   unsigned InstID = CstEnd;
2567 
2568   bool NeedsMetadataAttachment = F.hasMetadata();
2569 
2570   DILocation *LastDL = nullptr;
2571   unsigned NumInsts = 0;
2572   // Map from callee ValueId to profile count. Used to accumulate profile
2573   // counts for all static calls to a given callee.
2574   DenseMap<unsigned, CalleeInfo> CallGraphEdges;
2575   DenseSet<unsigned> RefEdges;
2576 
2577   SmallPtrSet<const User *, 8> Visited;
2578   // Finally, emit all the instructions, in order.
2579   for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
2580     for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
2581          I != E; ++I) {
2582       WriteInstruction(*I, InstID, VE, Stream, Vals);
2583 
2584       if (!isa<DbgInfoIntrinsic>(I))
2585         ++NumInsts;
2586 
2587       if (!I->getType()->isVoidTy())
2588         ++InstID;
2589 
2590       if (EmitSummaryIndex) {
2591         if (auto CS = ImmutableCallSite(&*I)) {
2592           auto *CalledFunction = CS.getCalledFunction();
2593           if (CalledFunction && CalledFunction->hasName() &&
2594               !CalledFunction->isIntrinsic()) {
2595             auto ScaledCount = BFI ? BFI->getBlockProfileCount(&*BB) : None;
2596             unsigned CalleeId = VE.getValueID(
2597                 M->getValueSymbolTable().lookup(CalledFunction->getName()));
2598             CallGraphEdges[CalleeId] +=
2599                 (ScaledCount ? ScaledCount.getValue() : 0);
2600           }
2601         }
2602         findRefEdges(&*I, VE, RefEdges, Visited);
2603       }
2604 
2605       // If the instruction has metadata, write a metadata attachment later.
2606       NeedsMetadataAttachment |= I->hasMetadataOtherThanDebugLoc();
2607 
2608       // If the instruction has a debug location, emit it.
2609       DILocation *DL = I->getDebugLoc();
2610       if (!DL)
2611         continue;
2612 
2613       if (DL == LastDL) {
2614         // Just repeat the same debug loc as last time.
2615         Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC_AGAIN, Vals);
2616         continue;
2617       }
2618 
2619       Vals.push_back(DL->getLine());
2620       Vals.push_back(DL->getColumn());
2621       Vals.push_back(VE.getMetadataOrNullID(DL->getScope()));
2622       Vals.push_back(VE.getMetadataOrNullID(DL->getInlinedAt()));
2623       Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC, Vals);
2624       Vals.clear();
2625 
2626       LastDL = DL;
2627     }
2628 
2629   std::unique_ptr<FunctionSummary> FuncSummary;
2630   if (EmitSummaryIndex) {
2631     FuncSummary = llvm::make_unique<FunctionSummary>(F.getLinkage(), NumInsts);
2632     FuncSummary->addCallGraphEdges(CallGraphEdges);
2633     FuncSummary->addRefEdges(RefEdges);
2634   }
2635   FunctionIndex[&F] =
2636       llvm::make_unique<GlobalValueInfo>(BitcodeIndex, std::move(FuncSummary));
2637 
2638   // Emit names for all the instructions etc.
2639   WriteValueSymbolTable(F.getValueSymbolTable(), VE, Stream);
2640 
2641   if (NeedsMetadataAttachment)
2642     WriteMetadataAttachment(F, VE, Stream);
2643   if (VE.shouldPreserveUseListOrder())
2644     WriteUseListBlock(&F, VE, Stream);
2645   VE.purgeFunction();
2646   Stream.ExitBlock();
2647 }
2648 
2649 // Emit blockinfo, which defines the standard abbreviations etc.
2650 static void WriteBlockInfo(const ValueEnumerator &VE, BitstreamWriter &Stream) {
2651   // We only want to emit block info records for blocks that have multiple
2652   // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK.
2653   // Other blocks can define their abbrevs inline.
2654   Stream.EnterBlockInfoBlock(2);
2655 
2656   { // 8-bit fixed-width VST_CODE_ENTRY/VST_CODE_BBENTRY strings.
2657     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2658     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3));
2659     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2660     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2661     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
2662     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
2663                                    Abbv) != VST_ENTRY_8_ABBREV)
2664       llvm_unreachable("Unexpected abbrev ordering!");
2665   }
2666 
2667   { // 7-bit fixed width VST_CODE_ENTRY strings.
2668     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2669     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
2670     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2671     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2672     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
2673     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
2674                                    Abbv) != VST_ENTRY_7_ABBREV)
2675       llvm_unreachable("Unexpected abbrev ordering!");
2676   }
2677   { // 6-bit char6 VST_CODE_ENTRY strings.
2678     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2679     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
2680     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2681     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2682     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
2683     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
2684                                    Abbv) != VST_ENTRY_6_ABBREV)
2685       llvm_unreachable("Unexpected abbrev ordering!");
2686   }
2687   { // 6-bit char6 VST_CODE_BBENTRY strings.
2688     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2689     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY));
2690     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2691     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2692     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
2693     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
2694                                    Abbv) != VST_BBENTRY_6_ABBREV)
2695       llvm_unreachable("Unexpected abbrev ordering!");
2696   }
2697 
2698 
2699 
2700   { // SETTYPE abbrev for CONSTANTS_BLOCK.
2701     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2702     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_SETTYPE));
2703     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
2704                               VE.computeBitsRequiredForTypeIndicies()));
2705     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
2706                                    Abbv) != CONSTANTS_SETTYPE_ABBREV)
2707       llvm_unreachable("Unexpected abbrev ordering!");
2708   }
2709 
2710   { // INTEGER abbrev for CONSTANTS_BLOCK.
2711     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2712     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_INTEGER));
2713     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2714     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
2715                                    Abbv) != CONSTANTS_INTEGER_ABBREV)
2716       llvm_unreachable("Unexpected abbrev ordering!");
2717   }
2718 
2719   { // CE_CAST abbrev for CONSTANTS_BLOCK.
2720     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2721     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CE_CAST));
2722     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4));  // cast opc
2723     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,       // typeid
2724                               VE.computeBitsRequiredForTypeIndicies()));
2725     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));    // value id
2726 
2727     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
2728                                    Abbv) != CONSTANTS_CE_CAST_Abbrev)
2729       llvm_unreachable("Unexpected abbrev ordering!");
2730   }
2731   { // NULL abbrev for CONSTANTS_BLOCK.
2732     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2733     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_NULL));
2734     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
2735                                    Abbv) != CONSTANTS_NULL_Abbrev)
2736       llvm_unreachable("Unexpected abbrev ordering!");
2737   }
2738 
2739   // FIXME: This should only use space for first class types!
2740 
2741   { // INST_LOAD abbrev for FUNCTION_BLOCK.
2742     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2743     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_LOAD));
2744     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Ptr
2745     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,    // dest ty
2746                               VE.computeBitsRequiredForTypeIndicies()));
2747     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align
2748     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile
2749     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
2750                                    Abbv) != FUNCTION_INST_LOAD_ABBREV)
2751       llvm_unreachable("Unexpected abbrev ordering!");
2752   }
2753   { // INST_BINOP abbrev for FUNCTION_BLOCK.
2754     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2755     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
2756     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
2757     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
2758     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
2759     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
2760                                    Abbv) != FUNCTION_INST_BINOP_ABBREV)
2761       llvm_unreachable("Unexpected abbrev ordering!");
2762   }
2763   { // INST_BINOP_FLAGS abbrev for FUNCTION_BLOCK.
2764     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2765     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
2766     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
2767     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
2768     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
2769     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7)); // flags
2770     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
2771                                    Abbv) != FUNCTION_INST_BINOP_FLAGS_ABBREV)
2772       llvm_unreachable("Unexpected abbrev ordering!");
2773   }
2774   { // INST_CAST abbrev for FUNCTION_BLOCK.
2775     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2776     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST));
2777     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));    // OpVal
2778     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,       // dest ty
2779                               VE.computeBitsRequiredForTypeIndicies()));
2780     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4));  // opc
2781     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
2782                                    Abbv) != FUNCTION_INST_CAST_ABBREV)
2783       llvm_unreachable("Unexpected abbrev ordering!");
2784   }
2785 
2786   { // INST_RET abbrev for FUNCTION_BLOCK.
2787     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2788     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
2789     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
2790                                    Abbv) != FUNCTION_INST_RET_VOID_ABBREV)
2791       llvm_unreachable("Unexpected abbrev ordering!");
2792   }
2793   { // INST_RET abbrev for FUNCTION_BLOCK.
2794     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2795     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
2796     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ValID
2797     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
2798                                    Abbv) != FUNCTION_INST_RET_VAL_ABBREV)
2799       llvm_unreachable("Unexpected abbrev ordering!");
2800   }
2801   { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK.
2802     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2803     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNREACHABLE));
2804     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
2805                                    Abbv) != FUNCTION_INST_UNREACHABLE_ABBREV)
2806       llvm_unreachable("Unexpected abbrev ordering!");
2807   }
2808   {
2809     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2810     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_GEP));
2811     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
2812     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
2813                               Log2_32_Ceil(VE.getTypes().size() + 1)));
2814     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2815     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
2816     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
2817         FUNCTION_INST_GEP_ABBREV)
2818       llvm_unreachable("Unexpected abbrev ordering!");
2819   }
2820 
2821   Stream.ExitBlock();
2822 }
2823 
2824 /// Write the module path strings, currently only used when generating
2825 /// a combined index file.
2826 static void WriteModStrings(const ModuleSummaryIndex &I,
2827                             BitstreamWriter &Stream) {
2828   Stream.EnterSubblock(bitc::MODULE_STRTAB_BLOCK_ID, 3);
2829 
2830   // TODO: See which abbrev sizes we actually need to emit
2831 
2832   // 8-bit fixed-width MST_ENTRY strings.
2833   BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2834   Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
2835   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2836   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2837   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
2838   unsigned Abbrev8Bit = Stream.EmitAbbrev(Abbv);
2839 
2840   // 7-bit fixed width MST_ENTRY strings.
2841   Abbv = new BitCodeAbbrev();
2842   Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
2843   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2844   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2845   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
2846   unsigned Abbrev7Bit = Stream.EmitAbbrev(Abbv);
2847 
2848   // 6-bit char6 MST_ENTRY strings.
2849   Abbv = new BitCodeAbbrev();
2850   Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
2851   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2852   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2853   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
2854   unsigned Abbrev6Bit = Stream.EmitAbbrev(Abbv);
2855 
2856   SmallVector<unsigned, 64> NameVals;
2857   for (const StringMapEntry<uint64_t> &MPSE : I.modulePaths()) {
2858     StringEncoding Bits =
2859         getStringEncoding(MPSE.getKey().data(), MPSE.getKey().size());
2860     unsigned AbbrevToUse = Abbrev8Bit;
2861     if (Bits == SE_Char6)
2862       AbbrevToUse = Abbrev6Bit;
2863     else if (Bits == SE_Fixed7)
2864       AbbrevToUse = Abbrev7Bit;
2865 
2866     NameVals.push_back(MPSE.getValue());
2867 
2868     for (const auto P : MPSE.getKey())
2869       NameVals.push_back((unsigned char)P);
2870 
2871     // Emit the finished record.
2872     Stream.EmitRecord(bitc::MST_CODE_ENTRY, NameVals, AbbrevToUse);
2873     NameVals.clear();
2874   }
2875   Stream.ExitBlock();
2876 }
2877 
2878 // Helper to emit a single function summary record.
2879 static void WritePerModuleFunctionSummaryRecord(
2880     SmallVector<uint64_t, 64> &NameVals, FunctionSummary *FS, unsigned ValueID,
2881     unsigned FSCallsAbbrev, unsigned FSCallsProfileAbbrev,
2882     BitstreamWriter &Stream, const Function &F) {
2883   assert(FS);
2884   NameVals.push_back(ValueID);
2885   NameVals.push_back(getEncodedLinkage(FS->linkage()));
2886   NameVals.push_back(FS->instCount());
2887   NameVals.push_back(FS->refs().size());
2888 
2889   for (auto &RI : FS->refs())
2890     NameVals.push_back(RI);
2891 
2892   bool HasProfileData = F.getEntryCount().hasValue();
2893   for (auto &ECI : FS->calls()) {
2894     NameVals.push_back(ECI.first);
2895     assert(ECI.second.CallsiteCount > 0 && "Expected at least one callsite");
2896     NameVals.push_back(ECI.second.CallsiteCount);
2897     if (HasProfileData)
2898       NameVals.push_back(ECI.second.ProfileCount);
2899   }
2900 
2901   unsigned FSAbbrev = (HasProfileData ? FSCallsProfileAbbrev : FSCallsAbbrev);
2902   unsigned Code =
2903       (HasProfileData ? bitc::FS_PERMODULE_PROFILE : bitc::FS_PERMODULE);
2904 
2905   // Emit the finished record.
2906   Stream.EmitRecord(Code, NameVals, FSAbbrev);
2907   NameVals.clear();
2908 }
2909 
2910 // Collect the global value references in the given variable's initializer,
2911 // and emit them in a summary record.
2912 static void WriteModuleLevelReferences(const GlobalVariable &V,
2913                                        const ValueEnumerator &VE,
2914                                        SmallVector<uint64_t, 64> &NameVals,
2915                                        unsigned FSModRefsAbbrev,
2916                                        BitstreamWriter &Stream) {
2917   // Only interested in recording variable defs in the summary.
2918   if (V.isDeclaration())
2919     return;
2920   DenseSet<unsigned> RefEdges;
2921   SmallPtrSet<const User *, 8> Visited;
2922   findRefEdges(&V, VE, RefEdges, Visited);
2923   NameVals.push_back(VE.getValueID(&V));
2924   NameVals.push_back(getEncodedLinkage(V.getLinkage()));
2925   for (auto RefId : RefEdges) {
2926     NameVals.push_back(RefId);
2927   }
2928   Stream.EmitRecord(bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS, NameVals,
2929                     FSModRefsAbbrev);
2930   NameVals.clear();
2931 }
2932 
2933 /// Emit the per-module summary section alongside the rest of
2934 /// the module's bitcode.
2935 static void WritePerModuleGlobalValueSummary(
2936     DenseMap<const Function *, std::unique_ptr<GlobalValueInfo>> &FunctionIndex,
2937     const Module *M, const ValueEnumerator &VE, BitstreamWriter &Stream) {
2938   if (M->empty())
2939     return;
2940 
2941   Stream.EnterSubblock(bitc::GLOBALVAL_SUMMARY_BLOCK_ID, 3);
2942 
2943   // Abbrev for FS_PERMODULE.
2944   BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2945   Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE));
2946   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // valueid
2947   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5)); // linkage
2948   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // instcount
2949   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // numrefs
2950   // numrefs x valueid, n x (valueid, callsitecount)
2951   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2952   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2953   unsigned FSCallsAbbrev = Stream.EmitAbbrev(Abbv);
2954 
2955   // Abbrev for FS_PERMODULE_PROFILE.
2956   Abbv = new BitCodeAbbrev();
2957   Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_PROFILE));
2958   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // valueid
2959   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5)); // linkage
2960   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // instcount
2961   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // numrefs
2962   // numrefs x valueid, n x (valueid, callsitecount, profilecount)
2963   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2964   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2965   unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(Abbv);
2966 
2967   // Abbrev for FS_PERMODULE_GLOBALVAR_INIT_REFS.
2968   Abbv = new BitCodeAbbrev();
2969   Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS));
2970   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
2971   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5)); // linkage
2972   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));  // valueids
2973   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2974   unsigned FSModRefsAbbrev = Stream.EmitAbbrev(Abbv);
2975 
2976   SmallVector<uint64_t, 64> NameVals;
2977   // Iterate over the list of functions instead of the FunctionIndex map to
2978   // ensure the ordering is stable.
2979   for (const Function &F : *M) {
2980     if (F.isDeclaration())
2981       continue;
2982     // Skip anonymous functions. We will emit a function summary for
2983     // any aliases below.
2984     if (!F.hasName())
2985       continue;
2986 
2987     assert(FunctionIndex.count(&F) == 1);
2988 
2989     WritePerModuleFunctionSummaryRecord(
2990         NameVals, cast<FunctionSummary>(FunctionIndex[&F]->summary()),
2991         VE.getValueID(M->getValueSymbolTable().lookup(F.getName())),
2992         FSCallsAbbrev, FSCallsProfileAbbrev, Stream, F);
2993   }
2994 
2995   for (const GlobalAlias &A : M->aliases()) {
2996     if (!A.getBaseObject())
2997       continue;
2998     const Function *F = dyn_cast<Function>(A.getBaseObject());
2999     if (!F || F->isDeclaration())
3000       continue;
3001 
3002     assert(FunctionIndex.count(F) == 1);
3003     FunctionSummary *FS =
3004         cast<FunctionSummary>(FunctionIndex[F]->summary());
3005     // Add the alias to the reference list of aliasee function.
3006     FS->addRefEdge(
3007         VE.getValueID(M->getValueSymbolTable().lookup(A.getName())));
3008     WritePerModuleFunctionSummaryRecord(
3009         NameVals, FS,
3010         VE.getValueID(M->getValueSymbolTable().lookup(A.getName())),
3011         FSCallsAbbrev, FSCallsProfileAbbrev, Stream, *F);
3012   }
3013 
3014   // Capture references from GlobalVariable initializers, which are outside
3015   // of a function scope.
3016   for (const GlobalVariable &G : M->globals())
3017     WriteModuleLevelReferences(G, VE, NameVals, FSModRefsAbbrev, Stream);
3018   for (const GlobalAlias &A : M->aliases())
3019     if (auto *GV = dyn_cast<GlobalVariable>(A.getBaseObject()))
3020       WriteModuleLevelReferences(*GV, VE, NameVals, FSModRefsAbbrev, Stream);
3021 
3022   Stream.ExitBlock();
3023 }
3024 
3025 /// Emit the combined summary section into the combined index file.
3026 static void WriteCombinedGlobalValueSummary(
3027     const ModuleSummaryIndex &I, BitstreamWriter &Stream,
3028     std::map<uint64_t, unsigned> &GUIDToValueIdMap, unsigned GlobalValueId) {
3029   Stream.EnterSubblock(bitc::GLOBALVAL_SUMMARY_BLOCK_ID, 3);
3030 
3031   // Abbrev for FS_COMBINED.
3032   BitCodeAbbrev *Abbv = new BitCodeAbbrev();
3033   Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED));
3034   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // modid
3035   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5)); // linkage
3036   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // instcount
3037   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // numrefs
3038   // numrefs x valueid, n x (valueid, callsitecount)
3039   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3040   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3041   unsigned FSCallsAbbrev = Stream.EmitAbbrev(Abbv);
3042 
3043   // Abbrev for FS_COMBINED_PROFILE.
3044   Abbv = new BitCodeAbbrev();
3045   Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_PROFILE));
3046   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // modid
3047   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5)); // linkage
3048   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // instcount
3049   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // numrefs
3050   // numrefs x valueid, n x (valueid, callsitecount, profilecount)
3051   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3052   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3053   unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(Abbv);
3054 
3055   // Abbrev for FS_COMBINED_GLOBALVAR_INIT_REFS.
3056   Abbv = new BitCodeAbbrev();
3057   Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_GLOBALVAR_INIT_REFS));
3058   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // modid
3059   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5)); // linkage
3060   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));    // valueids
3061   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3062   unsigned FSModRefsAbbrev = Stream.EmitAbbrev(Abbv);
3063 
3064   SmallVector<uint64_t, 64> NameVals;
3065   for (const auto &FII : I) {
3066     for (auto &FI : FII.second) {
3067       GlobalValueSummary *S = FI->summary();
3068       assert(S);
3069 
3070       if (auto *VS = dyn_cast<GlobalVarSummary>(S)) {
3071         NameVals.push_back(I.getModuleId(VS->modulePath()));
3072         NameVals.push_back(getEncodedLinkage(VS->linkage()));
3073         for (auto &RI : VS->refs()) {
3074           const auto &VMI = GUIDToValueIdMap.find(RI);
3075           unsigned RefId;
3076           // If this GUID doesn't have an entry, assign one.
3077           if (VMI == GUIDToValueIdMap.end()) {
3078             GUIDToValueIdMap[RI] = ++GlobalValueId;
3079             RefId = GlobalValueId;
3080           } else {
3081             RefId = VMI->second;
3082           }
3083           NameVals.push_back(RefId);
3084         }
3085 
3086         // Record the starting offset of this summary entry for use
3087         // in the VST entry. Add the current code size since the
3088         // reader will invoke readRecord after the abbrev id read.
3089         FI->setBitcodeIndex(Stream.GetCurrentBitNo() +
3090                             Stream.GetAbbrevIDWidth());
3091 
3092         // Emit the finished record.
3093         Stream.EmitRecord(bitc::FS_COMBINED_GLOBALVAR_INIT_REFS, NameVals,
3094                           FSModRefsAbbrev);
3095         NameVals.clear();
3096         continue;
3097       }
3098 
3099       auto *FS = cast<FunctionSummary>(S);
3100       NameVals.push_back(I.getModuleId(FS->modulePath()));
3101       NameVals.push_back(getEncodedLinkage(FS->linkage()));
3102       NameVals.push_back(FS->instCount());
3103       NameVals.push_back(FS->refs().size());
3104 
3105       for (auto &RI : FS->refs()) {
3106         const auto &VMI = GUIDToValueIdMap.find(RI);
3107         unsigned RefId;
3108         // If this GUID doesn't have an entry, assign one.
3109         if (VMI == GUIDToValueIdMap.end()) {
3110           GUIDToValueIdMap[RI] = ++GlobalValueId;
3111           RefId = GlobalValueId;
3112         } else {
3113           RefId = VMI->second;
3114         }
3115         NameVals.push_back(RefId);
3116       }
3117 
3118       bool HasProfileData = false;
3119       for (auto &EI : FS->calls()) {
3120         HasProfileData |= EI.second.ProfileCount != 0;
3121         if (HasProfileData)
3122           break;
3123       }
3124 
3125       for (auto &EI : FS->calls()) {
3126         const auto &VMI = GUIDToValueIdMap.find(EI.first);
3127         // If this GUID doesn't have an entry, it doesn't have a function
3128         // summary and we don't need to record any calls to it.
3129         if (VMI == GUIDToValueIdMap.end())
3130           continue;
3131         NameVals.push_back(VMI->second);
3132         assert(EI.second.CallsiteCount > 0 && "Expected at least one callsite");
3133         NameVals.push_back(EI.second.CallsiteCount);
3134         if (HasProfileData)
3135           NameVals.push_back(EI.second.ProfileCount);
3136       }
3137 
3138       // Record the starting offset of this summary entry for use
3139       // in the VST entry. Add the current code size since the
3140       // reader will invoke readRecord after the abbrev id read.
3141       FI->setBitcodeIndex(Stream.GetCurrentBitNo() + Stream.GetAbbrevIDWidth());
3142 
3143       unsigned FSAbbrev =
3144           (HasProfileData ? FSCallsProfileAbbrev : FSCallsAbbrev);
3145       unsigned Code =
3146           (HasProfileData ? bitc::FS_COMBINED_PROFILE : bitc::FS_COMBINED);
3147 
3148       // Emit the finished record.
3149       Stream.EmitRecord(Code, NameVals, FSAbbrev);
3150       NameVals.clear();
3151     }
3152   }
3153 
3154   Stream.ExitBlock();
3155 }
3156 
3157 // Create the "IDENTIFICATION_BLOCK_ID" containing a single string with the
3158 // current llvm version, and a record for the epoch number.
3159 static void WriteIdentificationBlock(const Module *M, BitstreamWriter &Stream) {
3160   Stream.EnterSubblock(bitc::IDENTIFICATION_BLOCK_ID, 5);
3161 
3162   // Write the "user readable" string identifying the bitcode producer
3163   BitCodeAbbrev *Abbv = new BitCodeAbbrev();
3164   Abbv->Add(BitCodeAbbrevOp(bitc::IDENTIFICATION_CODE_STRING));
3165   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3166   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
3167   auto StringAbbrev = Stream.EmitAbbrev(Abbv);
3168   WriteStringRecord(bitc::IDENTIFICATION_CODE_STRING,
3169                     "LLVM" LLVM_VERSION_STRING, StringAbbrev, Stream);
3170 
3171   // Write the epoch version
3172   Abbv = new BitCodeAbbrev();
3173   Abbv->Add(BitCodeAbbrevOp(bitc::IDENTIFICATION_CODE_EPOCH));
3174   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
3175   auto EpochAbbrev = Stream.EmitAbbrev(Abbv);
3176   SmallVector<unsigned, 1> Vals = {bitc::BITCODE_CURRENT_EPOCH};
3177   Stream.EmitRecord(bitc::IDENTIFICATION_CODE_EPOCH, Vals, EpochAbbrev);
3178   Stream.ExitBlock();
3179 }
3180 
3181 /// WriteModule - Emit the specified module to the bitstream.
3182 static void WriteModule(const Module *M, BitstreamWriter &Stream,
3183                         bool ShouldPreserveUseListOrder,
3184                         uint64_t BitcodeStartBit, bool EmitSummaryIndex) {
3185   Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
3186 
3187   SmallVector<unsigned, 1> Vals;
3188   unsigned CurVersion = 1;
3189   Vals.push_back(CurVersion);
3190   Stream.EmitRecord(bitc::MODULE_CODE_VERSION, Vals);
3191 
3192   // Analyze the module, enumerating globals, functions, etc.
3193   ValueEnumerator VE(*M, ShouldPreserveUseListOrder);
3194 
3195   // Emit blockinfo, which defines the standard abbreviations etc.
3196   WriteBlockInfo(VE, Stream);
3197 
3198   // Emit information about attribute groups.
3199   WriteAttributeGroupTable(VE, Stream);
3200 
3201   // Emit information about parameter attributes.
3202   WriteAttributeTable(VE, Stream);
3203 
3204   // Emit information describing all of the types in the module.
3205   WriteTypeTable(VE, Stream);
3206 
3207   writeComdats(VE, Stream);
3208 
3209   // Emit top-level description of module, including target triple, inline asm,
3210   // descriptors for global variables, and function prototype info.
3211   uint64_t VSTOffsetPlaceholder = WriteModuleInfo(M, VE, Stream);
3212 
3213   // Emit constants.
3214   WriteModuleConstants(VE, Stream);
3215 
3216   // Emit metadata.
3217   writeModuleMetadata(*M, VE, Stream);
3218 
3219   // Emit metadata.
3220   WriteModuleMetadataStore(M, Stream);
3221 
3222   // Emit module-level use-lists.
3223   if (VE.shouldPreserveUseListOrder())
3224     WriteUseListBlock(nullptr, VE, Stream);
3225 
3226   WriteOperandBundleTags(M, Stream);
3227 
3228   // Emit function bodies.
3229   DenseMap<const Function *, std::unique_ptr<GlobalValueInfo>> FunctionIndex;
3230   for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F)
3231     if (!F->isDeclaration())
3232       WriteFunction(*F, M, VE, Stream, FunctionIndex, EmitSummaryIndex);
3233 
3234   // Need to write after the above call to WriteFunction which populates
3235   // the summary information in the index.
3236   if (EmitSummaryIndex)
3237     WritePerModuleGlobalValueSummary(FunctionIndex, M, VE, Stream);
3238 
3239   WriteValueSymbolTable(M->getValueSymbolTable(), VE, Stream,
3240                         VSTOffsetPlaceholder, BitcodeStartBit, &FunctionIndex);
3241 
3242   Stream.ExitBlock();
3243 }
3244 
3245 /// EmitDarwinBCHeader - If generating a bc file on darwin, we have to emit a
3246 /// header and trailer to make it compatible with the system archiver.  To do
3247 /// this we emit the following header, and then emit a trailer that pads the
3248 /// file out to be a multiple of 16 bytes.
3249 ///
3250 /// struct bc_header {
3251 ///   uint32_t Magic;         // 0x0B17C0DE
3252 ///   uint32_t Version;       // Version, currently always 0.
3253 ///   uint32_t BitcodeOffset; // Offset to traditional bitcode file.
3254 ///   uint32_t BitcodeSize;   // Size of traditional bitcode file.
3255 ///   uint32_t CPUType;       // CPU specifier.
3256 ///   ... potentially more later ...
3257 /// };
3258 
3259 static void WriteInt32ToBuffer(uint32_t Value, SmallVectorImpl<char> &Buffer,
3260                                uint32_t &Position) {
3261   support::endian::write32le(&Buffer[Position], Value);
3262   Position += 4;
3263 }
3264 
3265 static void EmitDarwinBCHeaderAndTrailer(SmallVectorImpl<char> &Buffer,
3266                                          const Triple &TT) {
3267   unsigned CPUType = ~0U;
3268 
3269   // Match x86_64-*, i[3-9]86-*, powerpc-*, powerpc64-*, arm-*, thumb-*,
3270   // armv[0-9]-*, thumbv[0-9]-*, armv5te-*, or armv6t2-*. The CPUType is a magic
3271   // number from /usr/include/mach/machine.h.  It is ok to reproduce the
3272   // specific constants here because they are implicitly part of the Darwin ABI.
3273   enum {
3274     DARWIN_CPU_ARCH_ABI64      = 0x01000000,
3275     DARWIN_CPU_TYPE_X86        = 7,
3276     DARWIN_CPU_TYPE_ARM        = 12,
3277     DARWIN_CPU_TYPE_POWERPC    = 18
3278   };
3279 
3280   Triple::ArchType Arch = TT.getArch();
3281   if (Arch == Triple::x86_64)
3282     CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64;
3283   else if (Arch == Triple::x86)
3284     CPUType = DARWIN_CPU_TYPE_X86;
3285   else if (Arch == Triple::ppc)
3286     CPUType = DARWIN_CPU_TYPE_POWERPC;
3287   else if (Arch == Triple::ppc64)
3288     CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64;
3289   else if (Arch == Triple::arm || Arch == Triple::thumb)
3290     CPUType = DARWIN_CPU_TYPE_ARM;
3291 
3292   // Traditional Bitcode starts after header.
3293   assert(Buffer.size() >= BWH_HeaderSize &&
3294          "Expected header size to be reserved");
3295   unsigned BCOffset = BWH_HeaderSize;
3296   unsigned BCSize = Buffer.size() - BWH_HeaderSize;
3297 
3298   // Write the magic and version.
3299   unsigned Position = 0;
3300   WriteInt32ToBuffer(0x0B17C0DE , Buffer, Position);
3301   WriteInt32ToBuffer(0          , Buffer, Position); // Version.
3302   WriteInt32ToBuffer(BCOffset   , Buffer, Position);
3303   WriteInt32ToBuffer(BCSize     , Buffer, Position);
3304   WriteInt32ToBuffer(CPUType    , Buffer, Position);
3305 
3306   // If the file is not a multiple of 16 bytes, insert dummy padding.
3307   while (Buffer.size() & 15)
3308     Buffer.push_back(0);
3309 }
3310 
3311 /// Helper to write the header common to all bitcode files.
3312 static void WriteBitcodeHeader(BitstreamWriter &Stream) {
3313   // Emit the file header.
3314   Stream.Emit((unsigned)'B', 8);
3315   Stream.Emit((unsigned)'C', 8);
3316   Stream.Emit(0x0, 4);
3317   Stream.Emit(0xC, 4);
3318   Stream.Emit(0xE, 4);
3319   Stream.Emit(0xD, 4);
3320 }
3321 
3322 /// WriteBitcodeToFile - Write the specified module to the specified output
3323 /// stream.
3324 void llvm::WriteBitcodeToFile(const Module *M, raw_ostream &Out,
3325                               bool ShouldPreserveUseListOrder,
3326                               bool EmitSummaryIndex) {
3327   SmallVector<char, 0> Buffer;
3328   Buffer.reserve(256*1024);
3329 
3330   // If this is darwin or another generic macho target, reserve space for the
3331   // header.
3332   Triple TT(M->getTargetTriple());
3333   if (TT.isOSDarwin() || TT.isOSBinFormatMachO())
3334     Buffer.insert(Buffer.begin(), BWH_HeaderSize, 0);
3335 
3336   // Emit the module into the buffer.
3337   {
3338     BitstreamWriter Stream(Buffer);
3339     // Save the start bit of the actual bitcode, in case there is space
3340     // saved at the start for the darwin header above. The reader stream
3341     // will start at the bitcode, and we need the offset of the VST
3342     // to line up.
3343     uint64_t BitcodeStartBit = Stream.GetCurrentBitNo();
3344 
3345     // Emit the file header.
3346     WriteBitcodeHeader(Stream);
3347 
3348     WriteIdentificationBlock(M, Stream);
3349 
3350     // Emit the module.
3351     WriteModule(M, Stream, ShouldPreserveUseListOrder, BitcodeStartBit,
3352                 EmitSummaryIndex);
3353   }
3354 
3355   if (TT.isOSDarwin() || TT.isOSBinFormatMachO())
3356     EmitDarwinBCHeaderAndTrailer(Buffer, TT);
3357 
3358   // Write the generated bitstream to "Out".
3359   Out.write((char*)&Buffer.front(), Buffer.size());
3360 }
3361 
3362 // Write the specified module summary index to the given raw output stream,
3363 // where it will be written in a new bitcode block. This is used when
3364 // writing the combined index file for ThinLTO.
3365 void llvm::WriteIndexToFile(const ModuleSummaryIndex &Index, raw_ostream &Out) {
3366   SmallVector<char, 0> Buffer;
3367   Buffer.reserve(256 * 1024);
3368 
3369   BitstreamWriter Stream(Buffer);
3370 
3371   // Emit the bitcode header.
3372   WriteBitcodeHeader(Stream);
3373 
3374   Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
3375 
3376   SmallVector<unsigned, 1> Vals;
3377   unsigned CurVersion = 1;
3378   Vals.push_back(CurVersion);
3379   Stream.EmitRecord(bitc::MODULE_CODE_VERSION, Vals);
3380 
3381   // If we have a VST, write the VSTOFFSET record placeholder and record
3382   // its offset.
3383   uint64_t VSTOffsetPlaceholder = WriteValueSymbolTableForwardDecl(Stream);
3384 
3385   // Write the module paths in the combined index.
3386   WriteModStrings(Index, Stream);
3387 
3388   // Assign unique value ids to all functions in the index for use
3389   // in writing out the call graph edges. Save the mapping from GUID
3390   // to the new global value id to use when writing those edges, which
3391   // are currently saved in the index in terms of GUID.
3392   std::map<uint64_t, unsigned> GUIDToValueIdMap;
3393   unsigned GlobalValueId = 0;
3394   for (auto &II : Index)
3395     GUIDToValueIdMap[II.first] = ++GlobalValueId;
3396 
3397   // Write the summary combined index records.
3398   WriteCombinedGlobalValueSummary(Index, Stream, GUIDToValueIdMap,
3399                                   GlobalValueId);
3400 
3401   // Need a special VST writer for the combined index (we don't have a
3402   // real VST and real values when this is invoked).
3403   WriteCombinedValueSymbolTable(Index, Stream, GUIDToValueIdMap,
3404                                 VSTOffsetPlaceholder);
3405 
3406   Stream.ExitBlock();
3407 
3408   Out.write((char *)&Buffer.front(), Buffer.size());
3409 }
3410