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