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