xref: /llvm-project/llvm/lib/Bitcode/Writer/BitcodeWriter.cpp (revision b5b289339b51e4f180ffca55e31d62429275ee67)
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(VE.getMetadataOrNullID(N->getSubprograms().get()));
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->getTemplateParams().get()));
1131   Record.push_back(VE.getMetadataOrNullID(N->getDeclaration()));
1132   Record.push_back(VE.getMetadataOrNullID(N->getVariables().get()));
1133 
1134   Stream.EmitRecord(bitc::METADATA_SUBPROGRAM, Record, Abbrev);
1135   Record.clear();
1136 }
1137 
1138 static void writeDILexicalBlock(const DILexicalBlock *N,
1139                                 const ValueEnumerator &VE,
1140                                 BitstreamWriter &Stream,
1141                                 SmallVectorImpl<uint64_t> &Record,
1142                                 unsigned Abbrev) {
1143   Record.push_back(N->isDistinct());
1144   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1145   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1146   Record.push_back(N->getLine());
1147   Record.push_back(N->getColumn());
1148 
1149   Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK, Record, Abbrev);
1150   Record.clear();
1151 }
1152 
1153 static void writeDILexicalBlockFile(const DILexicalBlockFile *N,
1154                                     const ValueEnumerator &VE,
1155                                     BitstreamWriter &Stream,
1156                                     SmallVectorImpl<uint64_t> &Record,
1157                                     unsigned Abbrev) {
1158   Record.push_back(N->isDistinct());
1159   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1160   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1161   Record.push_back(N->getDiscriminator());
1162 
1163   Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK_FILE, Record, Abbrev);
1164   Record.clear();
1165 }
1166 
1167 static void writeDINamespace(const DINamespace *N, const ValueEnumerator &VE,
1168                              BitstreamWriter &Stream,
1169                              SmallVectorImpl<uint64_t> &Record,
1170                              unsigned Abbrev) {
1171   Record.push_back(N->isDistinct());
1172   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1173   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1174   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1175   Record.push_back(N->getLine());
1176 
1177   Stream.EmitRecord(bitc::METADATA_NAMESPACE, Record, Abbrev);
1178   Record.clear();
1179 }
1180 
1181 static void writeDIMacro(const DIMacro *N, const ValueEnumerator &VE,
1182                          BitstreamWriter &Stream,
1183                          SmallVectorImpl<uint64_t> &Record, unsigned Abbrev) {
1184   Record.push_back(N->isDistinct());
1185   Record.push_back(N->getMacinfoType());
1186   Record.push_back(N->getLine());
1187   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1188   Record.push_back(VE.getMetadataOrNullID(N->getRawValue()));
1189 
1190   Stream.EmitRecord(bitc::METADATA_MACRO, Record, Abbrev);
1191   Record.clear();
1192 }
1193 
1194 static void writeDIMacroFile(const DIMacroFile *N, const ValueEnumerator &VE,
1195                              BitstreamWriter &Stream,
1196                              SmallVectorImpl<uint64_t> &Record,
1197                              unsigned Abbrev) {
1198   Record.push_back(N->isDistinct());
1199   Record.push_back(N->getMacinfoType());
1200   Record.push_back(N->getLine());
1201   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1202   Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
1203 
1204   Stream.EmitRecord(bitc::METADATA_MACRO_FILE, Record, Abbrev);
1205   Record.clear();
1206 }
1207 
1208 static void writeDIModule(const DIModule *N, const ValueEnumerator &VE,
1209                           BitstreamWriter &Stream,
1210                           SmallVectorImpl<uint64_t> &Record, unsigned Abbrev) {
1211   Record.push_back(N->isDistinct());
1212   for (auto &I : N->operands())
1213     Record.push_back(VE.getMetadataOrNullID(I));
1214 
1215   Stream.EmitRecord(bitc::METADATA_MODULE, Record, Abbrev);
1216   Record.clear();
1217 }
1218 
1219 static void writeDITemplateTypeParameter(const DITemplateTypeParameter *N,
1220                                          const ValueEnumerator &VE,
1221                                          BitstreamWriter &Stream,
1222                                          SmallVectorImpl<uint64_t> &Record,
1223                                          unsigned Abbrev) {
1224   Record.push_back(N->isDistinct());
1225   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1226   Record.push_back(VE.getMetadataOrNullID(N->getType()));
1227 
1228   Stream.EmitRecord(bitc::METADATA_TEMPLATE_TYPE, Record, Abbrev);
1229   Record.clear();
1230 }
1231 
1232 static void writeDITemplateValueParameter(const DITemplateValueParameter *N,
1233                                           const ValueEnumerator &VE,
1234                                           BitstreamWriter &Stream,
1235                                           SmallVectorImpl<uint64_t> &Record,
1236                                           unsigned Abbrev) {
1237   Record.push_back(N->isDistinct());
1238   Record.push_back(N->getTag());
1239   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1240   Record.push_back(VE.getMetadataOrNullID(N->getType()));
1241   Record.push_back(VE.getMetadataOrNullID(N->getValue()));
1242 
1243   Stream.EmitRecord(bitc::METADATA_TEMPLATE_VALUE, Record, Abbrev);
1244   Record.clear();
1245 }
1246 
1247 static void writeDIGlobalVariable(const DIGlobalVariable *N,
1248                                   const ValueEnumerator &VE,
1249                                   BitstreamWriter &Stream,
1250                                   SmallVectorImpl<uint64_t> &Record,
1251                                   unsigned Abbrev) {
1252   Record.push_back(N->isDistinct());
1253   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1254   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1255   Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
1256   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1257   Record.push_back(N->getLine());
1258   Record.push_back(VE.getMetadataOrNullID(N->getType()));
1259   Record.push_back(N->isLocalToUnit());
1260   Record.push_back(N->isDefinition());
1261   Record.push_back(VE.getMetadataOrNullID(N->getRawVariable()));
1262   Record.push_back(VE.getMetadataOrNullID(N->getStaticDataMemberDeclaration()));
1263 
1264   Stream.EmitRecord(bitc::METADATA_GLOBAL_VAR, Record, Abbrev);
1265   Record.clear();
1266 }
1267 
1268 static void writeDILocalVariable(const DILocalVariable *N,
1269                                  const ValueEnumerator &VE,
1270                                  BitstreamWriter &Stream,
1271                                  SmallVectorImpl<uint64_t> &Record,
1272                                  unsigned Abbrev) {
1273   Record.push_back(N->isDistinct());
1274   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1275   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1276   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1277   Record.push_back(N->getLine());
1278   Record.push_back(VE.getMetadataOrNullID(N->getType()));
1279   Record.push_back(N->getArg());
1280   Record.push_back(N->getFlags());
1281 
1282   Stream.EmitRecord(bitc::METADATA_LOCAL_VAR, Record, Abbrev);
1283   Record.clear();
1284 }
1285 
1286 static void writeDIExpression(const DIExpression *N, const ValueEnumerator &,
1287                               BitstreamWriter &Stream,
1288                               SmallVectorImpl<uint64_t> &Record,
1289                               unsigned Abbrev) {
1290   Record.reserve(N->getElements().size() + 1);
1291 
1292   Record.push_back(N->isDistinct());
1293   Record.append(N->elements_begin(), N->elements_end());
1294 
1295   Stream.EmitRecord(bitc::METADATA_EXPRESSION, Record, Abbrev);
1296   Record.clear();
1297 }
1298 
1299 static void writeDIObjCProperty(const DIObjCProperty *N,
1300                                 const ValueEnumerator &VE,
1301                                 BitstreamWriter &Stream,
1302                                 SmallVectorImpl<uint64_t> &Record,
1303                                 unsigned Abbrev) {
1304   Record.push_back(N->isDistinct());
1305   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1306   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1307   Record.push_back(N->getLine());
1308   Record.push_back(VE.getMetadataOrNullID(N->getRawSetterName()));
1309   Record.push_back(VE.getMetadataOrNullID(N->getRawGetterName()));
1310   Record.push_back(N->getAttributes());
1311   Record.push_back(VE.getMetadataOrNullID(N->getType()));
1312 
1313   Stream.EmitRecord(bitc::METADATA_OBJC_PROPERTY, Record, Abbrev);
1314   Record.clear();
1315 }
1316 
1317 static void writeDIImportedEntity(const DIImportedEntity *N,
1318                                   const ValueEnumerator &VE,
1319                                   BitstreamWriter &Stream,
1320                                   SmallVectorImpl<uint64_t> &Record,
1321                                   unsigned Abbrev) {
1322   Record.push_back(N->isDistinct());
1323   Record.push_back(N->getTag());
1324   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1325   Record.push_back(VE.getMetadataOrNullID(N->getEntity()));
1326   Record.push_back(N->getLine());
1327   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1328 
1329   Stream.EmitRecord(bitc::METADATA_IMPORTED_ENTITY, Record, Abbrev);
1330   Record.clear();
1331 }
1332 
1333 static unsigned createNamedMetadataAbbrev(BitstreamWriter &Stream) {
1334   BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1335   Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_NAME));
1336   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1337   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
1338   return Stream.EmitAbbrev(Abbv);
1339 }
1340 
1341 static void writeNamedMetadata(const Module &M, const ValueEnumerator &VE,
1342                                BitstreamWriter &Stream,
1343                                SmallVectorImpl<uint64_t> &Record) {
1344   if (M.named_metadata_empty())
1345     return;
1346 
1347   unsigned Abbrev = createNamedMetadataAbbrev(Stream);
1348   for (const NamedMDNode &NMD : M.named_metadata()) {
1349     // Write name.
1350     StringRef Str = NMD.getName();
1351     Record.append(Str.bytes_begin(), Str.bytes_end());
1352     Stream.EmitRecord(bitc::METADATA_NAME, Record, Abbrev);
1353     Record.clear();
1354 
1355     // Write named metadata operands.
1356     for (const MDNode *N : NMD.operands())
1357       Record.push_back(VE.getMetadataID(N));
1358     Stream.EmitRecord(bitc::METADATA_NAMED_NODE, Record, 0);
1359     Record.clear();
1360   }
1361 }
1362 
1363 static unsigned createMetadataStringsAbbrev(BitstreamWriter &Stream) {
1364   BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1365   Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_STRINGS));
1366   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of strings
1367   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // offset to chars
1368   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1369   return Stream.EmitAbbrev(Abbv);
1370 }
1371 
1372 /// Write out a record for MDString.
1373 ///
1374 /// All the metadata strings in a metadata block are emitted in a single
1375 /// record.  The sizes and strings themselves are shoved into a blob.
1376 static void writeMetadataStrings(ArrayRef<const Metadata *> Strings,
1377                                  BitstreamWriter &Stream,
1378                                  SmallVectorImpl<uint64_t> &Record) {
1379   if (Strings.empty())
1380     return;
1381 
1382   // Start the record with the number of strings.
1383   Record.push_back(bitc::METADATA_STRINGS);
1384   Record.push_back(Strings.size());
1385 
1386   // Emit the sizes of the strings in the blob.
1387   SmallString<256> Blob;
1388   {
1389     BitstreamWriter W(Blob);
1390     for (const Metadata *MD : Strings)
1391       W.EmitVBR(cast<MDString>(MD)->getLength(), 6);
1392     W.FlushToWord();
1393   }
1394 
1395   // Add the offset to the strings to the record.
1396   Record.push_back(Blob.size());
1397 
1398   // Add the strings to the blob.
1399   for (const Metadata *MD : Strings)
1400     Blob.append(cast<MDString>(MD)->getString());
1401 
1402   // Emit the final record.
1403   Stream.EmitRecordWithBlob(createMetadataStringsAbbrev(Stream), Record, Blob);
1404   Record.clear();
1405 }
1406 
1407 static void writeMetadataRecords(ArrayRef<const Metadata *> MDs,
1408                                  const ValueEnumerator &VE,
1409                                  BitstreamWriter &Stream,
1410                                  SmallVectorImpl<uint64_t> &Record) {
1411   if (MDs.empty())
1412     return;
1413 
1414   // Initialize MDNode abbreviations.
1415 #define HANDLE_MDNODE_LEAF(CLASS) unsigned CLASS##Abbrev = 0;
1416 #include "llvm/IR/Metadata.def"
1417 
1418   for (const Metadata *MD : MDs) {
1419     if (const MDNode *N = dyn_cast<MDNode>(MD)) {
1420       assert(N->isResolved() && "Expected forward references to be resolved");
1421 
1422       switch (N->getMetadataID()) {
1423       default:
1424         llvm_unreachable("Invalid MDNode subclass");
1425 #define HANDLE_MDNODE_LEAF(CLASS)                                              \
1426   case Metadata::CLASS##Kind:                                                  \
1427     write##CLASS(cast<CLASS>(N), VE, Stream, Record, CLASS##Abbrev);           \
1428     continue;
1429 #include "llvm/IR/Metadata.def"
1430       }
1431     }
1432     writeValueAsMetadata(cast<ValueAsMetadata>(MD), VE, Stream, Record);
1433   }
1434 }
1435 
1436 static void writeModuleMetadata(const Module &M,
1437                                 const ValueEnumerator &VE,
1438                                 BitstreamWriter &Stream) {
1439   if (!VE.hasMDs() && M.named_metadata_empty())
1440     return;
1441 
1442   Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
1443   SmallVector<uint64_t, 64> Record;
1444   writeMetadataStrings(VE.getMDStrings(), Stream, Record);
1445   writeMetadataRecords(VE.getNonMDStrings(), VE, Stream, Record);
1446   writeNamedMetadata(M, VE, Stream, Record);
1447   Stream.ExitBlock();
1448 }
1449 
1450 static void writeFunctionMetadata(const Function &F, const ValueEnumerator &VE,
1451                                   BitstreamWriter &Stream) {
1452   if (!VE.hasMDs())
1453     return;
1454 
1455   Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
1456   SmallVector<uint64_t, 64> Record;
1457   writeMetadataStrings(VE.getMDStrings(), Stream, Record);
1458   writeMetadataRecords(VE.getNonMDStrings(), VE, Stream, Record);
1459   Stream.ExitBlock();
1460 }
1461 
1462 static void WriteMetadataAttachment(const Function &F,
1463                                     const ValueEnumerator &VE,
1464                                     BitstreamWriter &Stream) {
1465   Stream.EnterSubblock(bitc::METADATA_ATTACHMENT_ID, 3);
1466 
1467   SmallVector<uint64_t, 64> Record;
1468 
1469   // Write metadata attachments
1470   // METADATA_ATTACHMENT - [m x [value, [n x [id, mdnode]]]
1471   SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
1472   F.getAllMetadata(MDs);
1473   if (!MDs.empty()) {
1474     for (const auto &I : MDs) {
1475       Record.push_back(I.first);
1476       Record.push_back(VE.getMetadataID(I.second));
1477     }
1478     Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
1479     Record.clear();
1480   }
1481 
1482   for (const BasicBlock &BB : F)
1483     for (const Instruction &I : BB) {
1484       MDs.clear();
1485       I.getAllMetadataOtherThanDebugLoc(MDs);
1486 
1487       // If no metadata, ignore instruction.
1488       if (MDs.empty()) continue;
1489 
1490       Record.push_back(VE.getInstructionID(&I));
1491 
1492       for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
1493         Record.push_back(MDs[i].first);
1494         Record.push_back(VE.getMetadataID(MDs[i].second));
1495       }
1496       Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
1497       Record.clear();
1498     }
1499 
1500   Stream.ExitBlock();
1501 }
1502 
1503 static void WriteModuleMetadataStore(const Module *M, BitstreamWriter &Stream) {
1504   SmallVector<uint64_t, 64> Record;
1505 
1506   // Write metadata kinds
1507   // METADATA_KIND - [n x [id, name]]
1508   SmallVector<StringRef, 8> Names;
1509   M->getMDKindNames(Names);
1510 
1511   if (Names.empty()) return;
1512 
1513   Stream.EnterSubblock(bitc::METADATA_KIND_BLOCK_ID, 3);
1514 
1515   for (unsigned MDKindID = 0, e = Names.size(); MDKindID != e; ++MDKindID) {
1516     Record.push_back(MDKindID);
1517     StringRef KName = Names[MDKindID];
1518     Record.append(KName.begin(), KName.end());
1519 
1520     Stream.EmitRecord(bitc::METADATA_KIND, Record, 0);
1521     Record.clear();
1522   }
1523 
1524   Stream.ExitBlock();
1525 }
1526 
1527 static void WriteOperandBundleTags(const Module *M, BitstreamWriter &Stream) {
1528   // Write metadata kinds
1529   //
1530   // OPERAND_BUNDLE_TAGS_BLOCK_ID : N x OPERAND_BUNDLE_TAG
1531   //
1532   // OPERAND_BUNDLE_TAG - [strchr x N]
1533 
1534   SmallVector<StringRef, 8> Tags;
1535   M->getOperandBundleTags(Tags);
1536 
1537   if (Tags.empty())
1538     return;
1539 
1540   Stream.EnterSubblock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID, 3);
1541 
1542   SmallVector<uint64_t, 64> Record;
1543 
1544   for (auto Tag : Tags) {
1545     Record.append(Tag.begin(), Tag.end());
1546 
1547     Stream.EmitRecord(bitc::OPERAND_BUNDLE_TAG, Record, 0);
1548     Record.clear();
1549   }
1550 
1551   Stream.ExitBlock();
1552 }
1553 
1554 static void emitSignedInt64(SmallVectorImpl<uint64_t> &Vals, uint64_t V) {
1555   if ((int64_t)V >= 0)
1556     Vals.push_back(V << 1);
1557   else
1558     Vals.push_back((-V << 1) | 1);
1559 }
1560 
1561 static void WriteConstants(unsigned FirstVal, unsigned LastVal,
1562                            const ValueEnumerator &VE,
1563                            BitstreamWriter &Stream, bool isGlobal) {
1564   if (FirstVal == LastVal) return;
1565 
1566   Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 4);
1567 
1568   unsigned AggregateAbbrev = 0;
1569   unsigned String8Abbrev = 0;
1570   unsigned CString7Abbrev = 0;
1571   unsigned CString6Abbrev = 0;
1572   // If this is a constant pool for the module, emit module-specific abbrevs.
1573   if (isGlobal) {
1574     // Abbrev for CST_CODE_AGGREGATE.
1575     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1576     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_AGGREGATE));
1577     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1578     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal+1)));
1579     AggregateAbbrev = Stream.EmitAbbrev(Abbv);
1580 
1581     // Abbrev for CST_CODE_STRING.
1582     Abbv = new BitCodeAbbrev();
1583     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_STRING));
1584     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1585     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
1586     String8Abbrev = Stream.EmitAbbrev(Abbv);
1587     // Abbrev for CST_CODE_CSTRING.
1588     Abbv = new BitCodeAbbrev();
1589     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
1590     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1591     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
1592     CString7Abbrev = Stream.EmitAbbrev(Abbv);
1593     // Abbrev for CST_CODE_CSTRING.
1594     Abbv = new BitCodeAbbrev();
1595     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
1596     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1597     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
1598     CString6Abbrev = Stream.EmitAbbrev(Abbv);
1599   }
1600 
1601   SmallVector<uint64_t, 64> Record;
1602 
1603   const ValueEnumerator::ValueList &Vals = VE.getValues();
1604   Type *LastTy = nullptr;
1605   for (unsigned i = FirstVal; i != LastVal; ++i) {
1606     const Value *V = Vals[i].first;
1607     // If we need to switch types, do so now.
1608     if (V->getType() != LastTy) {
1609       LastTy = V->getType();
1610       Record.push_back(VE.getTypeID(LastTy));
1611       Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record,
1612                         CONSTANTS_SETTYPE_ABBREV);
1613       Record.clear();
1614     }
1615 
1616     if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
1617       Record.push_back(unsigned(IA->hasSideEffects()) |
1618                        unsigned(IA->isAlignStack()) << 1 |
1619                        unsigned(IA->getDialect()&1) << 2);
1620 
1621       // Add the asm string.
1622       const std::string &AsmStr = IA->getAsmString();
1623       Record.push_back(AsmStr.size());
1624       Record.append(AsmStr.begin(), AsmStr.end());
1625 
1626       // Add the constraint string.
1627       const std::string &ConstraintStr = IA->getConstraintString();
1628       Record.push_back(ConstraintStr.size());
1629       Record.append(ConstraintStr.begin(), ConstraintStr.end());
1630       Stream.EmitRecord(bitc::CST_CODE_INLINEASM, Record);
1631       Record.clear();
1632       continue;
1633     }
1634     const Constant *C = cast<Constant>(V);
1635     unsigned Code = -1U;
1636     unsigned AbbrevToUse = 0;
1637     if (C->isNullValue()) {
1638       Code = bitc::CST_CODE_NULL;
1639     } else if (isa<UndefValue>(C)) {
1640       Code = bitc::CST_CODE_UNDEF;
1641     } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {
1642       if (IV->getBitWidth() <= 64) {
1643         uint64_t V = IV->getSExtValue();
1644         emitSignedInt64(Record, V);
1645         Code = bitc::CST_CODE_INTEGER;
1646         AbbrevToUse = CONSTANTS_INTEGER_ABBREV;
1647       } else {                             // Wide integers, > 64 bits in size.
1648         // We have an arbitrary precision integer value to write whose
1649         // bit width is > 64. However, in canonical unsigned integer
1650         // format it is likely that the high bits are going to be zero.
1651         // So, we only write the number of active words.
1652         unsigned NWords = IV->getValue().getActiveWords();
1653         const uint64_t *RawWords = IV->getValue().getRawData();
1654         for (unsigned i = 0; i != NWords; ++i) {
1655           emitSignedInt64(Record, RawWords[i]);
1656         }
1657         Code = bitc::CST_CODE_WIDE_INTEGER;
1658       }
1659     } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
1660       Code = bitc::CST_CODE_FLOAT;
1661       Type *Ty = CFP->getType();
1662       if (Ty->isHalfTy() || Ty->isFloatTy() || Ty->isDoubleTy()) {
1663         Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
1664       } else if (Ty->isX86_FP80Ty()) {
1665         // api needed to prevent premature destruction
1666         // bits are not in the same order as a normal i80 APInt, compensate.
1667         APInt api = CFP->getValueAPF().bitcastToAPInt();
1668         const uint64_t *p = api.getRawData();
1669         Record.push_back((p[1] << 48) | (p[0] >> 16));
1670         Record.push_back(p[0] & 0xffffLL);
1671       } else if (Ty->isFP128Ty() || Ty->isPPC_FP128Ty()) {
1672         APInt api = CFP->getValueAPF().bitcastToAPInt();
1673         const uint64_t *p = api.getRawData();
1674         Record.push_back(p[0]);
1675         Record.push_back(p[1]);
1676       } else {
1677         assert (0 && "Unknown FP type!");
1678       }
1679     } else if (isa<ConstantDataSequential>(C) &&
1680                cast<ConstantDataSequential>(C)->isString()) {
1681       const ConstantDataSequential *Str = cast<ConstantDataSequential>(C);
1682       // Emit constant strings specially.
1683       unsigned NumElts = Str->getNumElements();
1684       // If this is a null-terminated string, use the denser CSTRING encoding.
1685       if (Str->isCString()) {
1686         Code = bitc::CST_CODE_CSTRING;
1687         --NumElts;  // Don't encode the null, which isn't allowed by char6.
1688       } else {
1689         Code = bitc::CST_CODE_STRING;
1690         AbbrevToUse = String8Abbrev;
1691       }
1692       bool isCStr7 = Code == bitc::CST_CODE_CSTRING;
1693       bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING;
1694       for (unsigned i = 0; i != NumElts; ++i) {
1695         unsigned char V = Str->getElementAsInteger(i);
1696         Record.push_back(V);
1697         isCStr7 &= (V & 128) == 0;
1698         if (isCStrChar6)
1699           isCStrChar6 = BitCodeAbbrevOp::isChar6(V);
1700       }
1701 
1702       if (isCStrChar6)
1703         AbbrevToUse = CString6Abbrev;
1704       else if (isCStr7)
1705         AbbrevToUse = CString7Abbrev;
1706     } else if (const ConstantDataSequential *CDS =
1707                   dyn_cast<ConstantDataSequential>(C)) {
1708       Code = bitc::CST_CODE_DATA;
1709       Type *EltTy = CDS->getType()->getElementType();
1710       if (isa<IntegerType>(EltTy)) {
1711         for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
1712           Record.push_back(CDS->getElementAsInteger(i));
1713       } else {
1714         for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
1715           Record.push_back(
1716               CDS->getElementAsAPFloat(i).bitcastToAPInt().getLimitedValue());
1717       }
1718     } else if (isa<ConstantAggregate>(C)) {
1719       Code = bitc::CST_CODE_AGGREGATE;
1720       for (const Value *Op : C->operands())
1721         Record.push_back(VE.getValueID(Op));
1722       AbbrevToUse = AggregateAbbrev;
1723     } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1724       switch (CE->getOpcode()) {
1725       default:
1726         if (Instruction::isCast(CE->getOpcode())) {
1727           Code = bitc::CST_CODE_CE_CAST;
1728           Record.push_back(GetEncodedCastOpcode(CE->getOpcode()));
1729           Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
1730           Record.push_back(VE.getValueID(C->getOperand(0)));
1731           AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;
1732         } else {
1733           assert(CE->getNumOperands() == 2 && "Unknown constant expr!");
1734           Code = bitc::CST_CODE_CE_BINOP;
1735           Record.push_back(GetEncodedBinaryOpcode(CE->getOpcode()));
1736           Record.push_back(VE.getValueID(C->getOperand(0)));
1737           Record.push_back(VE.getValueID(C->getOperand(1)));
1738           uint64_t Flags = GetOptimizationFlags(CE);
1739           if (Flags != 0)
1740             Record.push_back(Flags);
1741         }
1742         break;
1743       case Instruction::GetElementPtr: {
1744         Code = bitc::CST_CODE_CE_GEP;
1745         const auto *GO = cast<GEPOperator>(C);
1746         if (GO->isInBounds())
1747           Code = bitc::CST_CODE_CE_INBOUNDS_GEP;
1748         Record.push_back(VE.getTypeID(GO->getSourceElementType()));
1749         for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
1750           Record.push_back(VE.getTypeID(C->getOperand(i)->getType()));
1751           Record.push_back(VE.getValueID(C->getOperand(i)));
1752         }
1753         break;
1754       }
1755       case Instruction::Select:
1756         Code = bitc::CST_CODE_CE_SELECT;
1757         Record.push_back(VE.getValueID(C->getOperand(0)));
1758         Record.push_back(VE.getValueID(C->getOperand(1)));
1759         Record.push_back(VE.getValueID(C->getOperand(2)));
1760         break;
1761       case Instruction::ExtractElement:
1762         Code = bitc::CST_CODE_CE_EXTRACTELT;
1763         Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
1764         Record.push_back(VE.getValueID(C->getOperand(0)));
1765         Record.push_back(VE.getTypeID(C->getOperand(1)->getType()));
1766         Record.push_back(VE.getValueID(C->getOperand(1)));
1767         break;
1768       case Instruction::InsertElement:
1769         Code = bitc::CST_CODE_CE_INSERTELT;
1770         Record.push_back(VE.getValueID(C->getOperand(0)));
1771         Record.push_back(VE.getValueID(C->getOperand(1)));
1772         Record.push_back(VE.getTypeID(C->getOperand(2)->getType()));
1773         Record.push_back(VE.getValueID(C->getOperand(2)));
1774         break;
1775       case Instruction::ShuffleVector:
1776         // If the return type and argument types are the same, this is a
1777         // standard shufflevector instruction.  If the types are different,
1778         // then the shuffle is widening or truncating the input vectors, and
1779         // the argument type must also be encoded.
1780         if (C->getType() == C->getOperand(0)->getType()) {
1781           Code = bitc::CST_CODE_CE_SHUFFLEVEC;
1782         } else {
1783           Code = bitc::CST_CODE_CE_SHUFVEC_EX;
1784           Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
1785         }
1786         Record.push_back(VE.getValueID(C->getOperand(0)));
1787         Record.push_back(VE.getValueID(C->getOperand(1)));
1788         Record.push_back(VE.getValueID(C->getOperand(2)));
1789         break;
1790       case Instruction::ICmp:
1791       case Instruction::FCmp:
1792         Code = bitc::CST_CODE_CE_CMP;
1793         Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
1794         Record.push_back(VE.getValueID(C->getOperand(0)));
1795         Record.push_back(VE.getValueID(C->getOperand(1)));
1796         Record.push_back(CE->getPredicate());
1797         break;
1798       }
1799     } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) {
1800       Code = bitc::CST_CODE_BLOCKADDRESS;
1801       Record.push_back(VE.getTypeID(BA->getFunction()->getType()));
1802       Record.push_back(VE.getValueID(BA->getFunction()));
1803       Record.push_back(VE.getGlobalBasicBlockID(BA->getBasicBlock()));
1804     } else {
1805 #ifndef NDEBUG
1806       C->dump();
1807 #endif
1808       llvm_unreachable("Unknown constant!");
1809     }
1810     Stream.EmitRecord(Code, Record, AbbrevToUse);
1811     Record.clear();
1812   }
1813 
1814   Stream.ExitBlock();
1815 }
1816 
1817 static void WriteModuleConstants(const ValueEnumerator &VE,
1818                                  BitstreamWriter &Stream) {
1819   const ValueEnumerator::ValueList &Vals = VE.getValues();
1820 
1821   // Find the first constant to emit, which is the first non-globalvalue value.
1822   // We know globalvalues have been emitted by WriteModuleInfo.
1823   for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
1824     if (!isa<GlobalValue>(Vals[i].first)) {
1825       WriteConstants(i, Vals.size(), VE, Stream, true);
1826       return;
1827     }
1828   }
1829 }
1830 
1831 /// PushValueAndType - The file has to encode both the value and type id for
1832 /// many values, because we need to know what type to create for forward
1833 /// references.  However, most operands are not forward references, so this type
1834 /// field is not needed.
1835 ///
1836 /// This function adds V's value ID to Vals.  If the value ID is higher than the
1837 /// instruction ID, then it is a forward reference, and it also includes the
1838 /// type ID.  The value ID that is written is encoded relative to the InstID.
1839 static bool PushValueAndType(const Value *V, unsigned InstID,
1840                              SmallVectorImpl<unsigned> &Vals,
1841                              ValueEnumerator &VE) {
1842   unsigned ValID = VE.getValueID(V);
1843   // Make encoding relative to the InstID.
1844   Vals.push_back(InstID - ValID);
1845   if (ValID >= InstID) {
1846     Vals.push_back(VE.getTypeID(V->getType()));
1847     return true;
1848   }
1849   return false;
1850 }
1851 
1852 static void WriteOperandBundles(BitstreamWriter &Stream, ImmutableCallSite CS,
1853                                 unsigned InstID, ValueEnumerator &VE) {
1854   SmallVector<unsigned, 64> Record;
1855   LLVMContext &C = CS.getInstruction()->getContext();
1856 
1857   for (unsigned i = 0, e = CS.getNumOperandBundles(); i != e; ++i) {
1858     const auto &Bundle = CS.getOperandBundleAt(i);
1859     Record.push_back(C.getOperandBundleTagID(Bundle.getTagName()));
1860 
1861     for (auto &Input : Bundle.Inputs)
1862       PushValueAndType(Input, InstID, Record, VE);
1863 
1864     Stream.EmitRecord(bitc::FUNC_CODE_OPERAND_BUNDLE, Record);
1865     Record.clear();
1866   }
1867 }
1868 
1869 /// pushValue - Like PushValueAndType, but where the type of the value is
1870 /// omitted (perhaps it was already encoded in an earlier operand).
1871 static void pushValue(const Value *V, unsigned InstID,
1872                       SmallVectorImpl<unsigned> &Vals,
1873                       ValueEnumerator &VE) {
1874   unsigned ValID = VE.getValueID(V);
1875   Vals.push_back(InstID - ValID);
1876 }
1877 
1878 static void pushValueSigned(const Value *V, unsigned InstID,
1879                             SmallVectorImpl<uint64_t> &Vals,
1880                             ValueEnumerator &VE) {
1881   unsigned ValID = VE.getValueID(V);
1882   int64_t diff = ((int32_t)InstID - (int32_t)ValID);
1883   emitSignedInt64(Vals, diff);
1884 }
1885 
1886 /// WriteInstruction - Emit an instruction to the specified stream.
1887 static void WriteInstruction(const Instruction &I, unsigned InstID,
1888                              ValueEnumerator &VE, BitstreamWriter &Stream,
1889                              SmallVectorImpl<unsigned> &Vals) {
1890   unsigned Code = 0;
1891   unsigned AbbrevToUse = 0;
1892   VE.setInstructionID(&I);
1893   switch (I.getOpcode()) {
1894   default:
1895     if (Instruction::isCast(I.getOpcode())) {
1896       Code = bitc::FUNC_CODE_INST_CAST;
1897       if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
1898         AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
1899       Vals.push_back(VE.getTypeID(I.getType()));
1900       Vals.push_back(GetEncodedCastOpcode(I.getOpcode()));
1901     } else {
1902       assert(isa<BinaryOperator>(I) && "Unknown instruction!");
1903       Code = bitc::FUNC_CODE_INST_BINOP;
1904       if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
1905         AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
1906       pushValue(I.getOperand(1), InstID, Vals, VE);
1907       Vals.push_back(GetEncodedBinaryOpcode(I.getOpcode()));
1908       uint64_t Flags = GetOptimizationFlags(&I);
1909       if (Flags != 0) {
1910         if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV)
1911           AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV;
1912         Vals.push_back(Flags);
1913       }
1914     }
1915     break;
1916 
1917   case Instruction::GetElementPtr: {
1918     Code = bitc::FUNC_CODE_INST_GEP;
1919     AbbrevToUse = FUNCTION_INST_GEP_ABBREV;
1920     auto &GEPInst = cast<GetElementPtrInst>(I);
1921     Vals.push_back(GEPInst.isInBounds());
1922     Vals.push_back(VE.getTypeID(GEPInst.getSourceElementType()));
1923     for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
1924       PushValueAndType(I.getOperand(i), InstID, Vals, VE);
1925     break;
1926   }
1927   case Instruction::ExtractValue: {
1928     Code = bitc::FUNC_CODE_INST_EXTRACTVAL;
1929     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1930     const ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
1931     Vals.append(EVI->idx_begin(), EVI->idx_end());
1932     break;
1933   }
1934   case Instruction::InsertValue: {
1935     Code = bitc::FUNC_CODE_INST_INSERTVAL;
1936     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1937     PushValueAndType(I.getOperand(1), InstID, Vals, VE);
1938     const InsertValueInst *IVI = cast<InsertValueInst>(&I);
1939     Vals.append(IVI->idx_begin(), IVI->idx_end());
1940     break;
1941   }
1942   case Instruction::Select:
1943     Code = bitc::FUNC_CODE_INST_VSELECT;
1944     PushValueAndType(I.getOperand(1), InstID, Vals, VE);
1945     pushValue(I.getOperand(2), InstID, Vals, VE);
1946     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1947     break;
1948   case Instruction::ExtractElement:
1949     Code = bitc::FUNC_CODE_INST_EXTRACTELT;
1950     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1951     PushValueAndType(I.getOperand(1), InstID, Vals, VE);
1952     break;
1953   case Instruction::InsertElement:
1954     Code = bitc::FUNC_CODE_INST_INSERTELT;
1955     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1956     pushValue(I.getOperand(1), InstID, Vals, VE);
1957     PushValueAndType(I.getOperand(2), InstID, Vals, VE);
1958     break;
1959   case Instruction::ShuffleVector:
1960     Code = bitc::FUNC_CODE_INST_SHUFFLEVEC;
1961     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1962     pushValue(I.getOperand(1), InstID, Vals, VE);
1963     pushValue(I.getOperand(2), InstID, Vals, VE);
1964     break;
1965   case Instruction::ICmp:
1966   case Instruction::FCmp: {
1967     // compare returning Int1Ty or vector of Int1Ty
1968     Code = bitc::FUNC_CODE_INST_CMP2;
1969     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1970     pushValue(I.getOperand(1), InstID, Vals, VE);
1971     Vals.push_back(cast<CmpInst>(I).getPredicate());
1972     uint64_t Flags = GetOptimizationFlags(&I);
1973     if (Flags != 0)
1974       Vals.push_back(Flags);
1975     break;
1976   }
1977 
1978   case Instruction::Ret:
1979     {
1980       Code = bitc::FUNC_CODE_INST_RET;
1981       unsigned NumOperands = I.getNumOperands();
1982       if (NumOperands == 0)
1983         AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
1984       else if (NumOperands == 1) {
1985         if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
1986           AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
1987       } else {
1988         for (unsigned i = 0, e = NumOperands; i != e; ++i)
1989           PushValueAndType(I.getOperand(i), InstID, Vals, VE);
1990       }
1991     }
1992     break;
1993   case Instruction::Br:
1994     {
1995       Code = bitc::FUNC_CODE_INST_BR;
1996       const BranchInst &II = cast<BranchInst>(I);
1997       Vals.push_back(VE.getValueID(II.getSuccessor(0)));
1998       if (II.isConditional()) {
1999         Vals.push_back(VE.getValueID(II.getSuccessor(1)));
2000         pushValue(II.getCondition(), InstID, Vals, VE);
2001       }
2002     }
2003     break;
2004   case Instruction::Switch:
2005     {
2006       Code = bitc::FUNC_CODE_INST_SWITCH;
2007       const SwitchInst &SI = cast<SwitchInst>(I);
2008       Vals.push_back(VE.getTypeID(SI.getCondition()->getType()));
2009       pushValue(SI.getCondition(), InstID, Vals, VE);
2010       Vals.push_back(VE.getValueID(SI.getDefaultDest()));
2011       for (SwitchInst::ConstCaseIt Case : SI.cases()) {
2012         Vals.push_back(VE.getValueID(Case.getCaseValue()));
2013         Vals.push_back(VE.getValueID(Case.getCaseSuccessor()));
2014       }
2015     }
2016     break;
2017   case Instruction::IndirectBr:
2018     Code = bitc::FUNC_CODE_INST_INDIRECTBR;
2019     Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
2020     // Encode the address operand as relative, but not the basic blocks.
2021     pushValue(I.getOperand(0), InstID, Vals, VE);
2022     for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i)
2023       Vals.push_back(VE.getValueID(I.getOperand(i)));
2024     break;
2025 
2026   case Instruction::Invoke: {
2027     const InvokeInst *II = cast<InvokeInst>(&I);
2028     const Value *Callee = II->getCalledValue();
2029     FunctionType *FTy = II->getFunctionType();
2030 
2031     if (II->hasOperandBundles())
2032       WriteOperandBundles(Stream, II, InstID, VE);
2033 
2034     Code = bitc::FUNC_CODE_INST_INVOKE;
2035 
2036     Vals.push_back(VE.getAttributeID(II->getAttributes()));
2037     Vals.push_back(II->getCallingConv() | 1 << 13);
2038     Vals.push_back(VE.getValueID(II->getNormalDest()));
2039     Vals.push_back(VE.getValueID(II->getUnwindDest()));
2040     Vals.push_back(VE.getTypeID(FTy));
2041     PushValueAndType(Callee, InstID, Vals, VE);
2042 
2043     // Emit value #'s for the fixed parameters.
2044     for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
2045       pushValue(I.getOperand(i), InstID, Vals, VE);  // fixed param.
2046 
2047     // Emit type/value pairs for varargs params.
2048     if (FTy->isVarArg()) {
2049       for (unsigned i = FTy->getNumParams(), e = I.getNumOperands()-3;
2050            i != e; ++i)
2051         PushValueAndType(I.getOperand(i), InstID, Vals, VE); // vararg
2052     }
2053     break;
2054   }
2055   case Instruction::Resume:
2056     Code = bitc::FUNC_CODE_INST_RESUME;
2057     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
2058     break;
2059   case Instruction::CleanupRet: {
2060     Code = bitc::FUNC_CODE_INST_CLEANUPRET;
2061     const auto &CRI = cast<CleanupReturnInst>(I);
2062     pushValue(CRI.getCleanupPad(), InstID, Vals, VE);
2063     if (CRI.hasUnwindDest())
2064       Vals.push_back(VE.getValueID(CRI.getUnwindDest()));
2065     break;
2066   }
2067   case Instruction::CatchRet: {
2068     Code = bitc::FUNC_CODE_INST_CATCHRET;
2069     const auto &CRI = cast<CatchReturnInst>(I);
2070     pushValue(CRI.getCatchPad(), InstID, Vals, VE);
2071     Vals.push_back(VE.getValueID(CRI.getSuccessor()));
2072     break;
2073   }
2074   case Instruction::CleanupPad:
2075   case Instruction::CatchPad: {
2076     const auto &FuncletPad = cast<FuncletPadInst>(I);
2077     Code = isa<CatchPadInst>(FuncletPad) ? bitc::FUNC_CODE_INST_CATCHPAD
2078                                          : bitc::FUNC_CODE_INST_CLEANUPPAD;
2079     pushValue(FuncletPad.getParentPad(), InstID, Vals, VE);
2080 
2081     unsigned NumArgOperands = FuncletPad.getNumArgOperands();
2082     Vals.push_back(NumArgOperands);
2083     for (unsigned Op = 0; Op != NumArgOperands; ++Op)
2084       PushValueAndType(FuncletPad.getArgOperand(Op), InstID, Vals, VE);
2085     break;
2086   }
2087   case Instruction::CatchSwitch: {
2088     Code = bitc::FUNC_CODE_INST_CATCHSWITCH;
2089     const auto &CatchSwitch = cast<CatchSwitchInst>(I);
2090 
2091     pushValue(CatchSwitch.getParentPad(), InstID, Vals, VE);
2092 
2093     unsigned NumHandlers = CatchSwitch.getNumHandlers();
2094     Vals.push_back(NumHandlers);
2095     for (const BasicBlock *CatchPadBB : CatchSwitch.handlers())
2096       Vals.push_back(VE.getValueID(CatchPadBB));
2097 
2098     if (CatchSwitch.hasUnwindDest())
2099       Vals.push_back(VE.getValueID(CatchSwitch.getUnwindDest()));
2100     break;
2101   }
2102   case Instruction::Unreachable:
2103     Code = bitc::FUNC_CODE_INST_UNREACHABLE;
2104     AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
2105     break;
2106 
2107   case Instruction::PHI: {
2108     const PHINode &PN = cast<PHINode>(I);
2109     Code = bitc::FUNC_CODE_INST_PHI;
2110     // With the newer instruction encoding, forward references could give
2111     // negative valued IDs.  This is most common for PHIs, so we use
2112     // signed VBRs.
2113     SmallVector<uint64_t, 128> Vals64;
2114     Vals64.push_back(VE.getTypeID(PN.getType()));
2115     for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
2116       pushValueSigned(PN.getIncomingValue(i), InstID, Vals64, VE);
2117       Vals64.push_back(VE.getValueID(PN.getIncomingBlock(i)));
2118     }
2119     // Emit a Vals64 vector and exit.
2120     Stream.EmitRecord(Code, Vals64, AbbrevToUse);
2121     Vals64.clear();
2122     return;
2123   }
2124 
2125   case Instruction::LandingPad: {
2126     const LandingPadInst &LP = cast<LandingPadInst>(I);
2127     Code = bitc::FUNC_CODE_INST_LANDINGPAD;
2128     Vals.push_back(VE.getTypeID(LP.getType()));
2129     Vals.push_back(LP.isCleanup());
2130     Vals.push_back(LP.getNumClauses());
2131     for (unsigned I = 0, E = LP.getNumClauses(); I != E; ++I) {
2132       if (LP.isCatch(I))
2133         Vals.push_back(LandingPadInst::Catch);
2134       else
2135         Vals.push_back(LandingPadInst::Filter);
2136       PushValueAndType(LP.getClause(I), InstID, Vals, VE);
2137     }
2138     break;
2139   }
2140 
2141   case Instruction::Alloca: {
2142     Code = bitc::FUNC_CODE_INST_ALLOCA;
2143     const AllocaInst &AI = cast<AllocaInst>(I);
2144     Vals.push_back(VE.getTypeID(AI.getAllocatedType()));
2145     Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
2146     Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
2147     unsigned AlignRecord = Log2_32(AI.getAlignment()) + 1;
2148     assert(Log2_32(Value::MaximumAlignment) + 1 < 1 << 5 &&
2149            "not enough bits for maximum alignment");
2150     assert(AlignRecord < 1 << 5 && "alignment greater than 1 << 64");
2151     AlignRecord |= AI.isUsedWithInAlloca() << 5;
2152     AlignRecord |= 1 << 6;
2153     AlignRecord |= AI.isSwiftError() << 7;
2154     Vals.push_back(AlignRecord);
2155     break;
2156   }
2157 
2158   case Instruction::Load:
2159     if (cast<LoadInst>(I).isAtomic()) {
2160       Code = bitc::FUNC_CODE_INST_LOADATOMIC;
2161       PushValueAndType(I.getOperand(0), InstID, Vals, VE);
2162     } else {
2163       Code = bitc::FUNC_CODE_INST_LOAD;
2164       if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))  // ptr
2165         AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
2166     }
2167     Vals.push_back(VE.getTypeID(I.getType()));
2168     Vals.push_back(Log2_32(cast<LoadInst>(I).getAlignment())+1);
2169     Vals.push_back(cast<LoadInst>(I).isVolatile());
2170     if (cast<LoadInst>(I).isAtomic()) {
2171       Vals.push_back(GetEncodedOrdering(cast<LoadInst>(I).getOrdering()));
2172       Vals.push_back(GetEncodedSynchScope(cast<LoadInst>(I).getSynchScope()));
2173     }
2174     break;
2175   case Instruction::Store:
2176     if (cast<StoreInst>(I).isAtomic())
2177       Code = bitc::FUNC_CODE_INST_STOREATOMIC;
2178     else
2179       Code = bitc::FUNC_CODE_INST_STORE;
2180     PushValueAndType(I.getOperand(1), InstID, Vals, VE);  // ptrty + ptr
2181     PushValueAndType(I.getOperand(0), InstID, Vals, VE);  // valty + val
2182     Vals.push_back(Log2_32(cast<StoreInst>(I).getAlignment())+1);
2183     Vals.push_back(cast<StoreInst>(I).isVolatile());
2184     if (cast<StoreInst>(I).isAtomic()) {
2185       Vals.push_back(GetEncodedOrdering(cast<StoreInst>(I).getOrdering()));
2186       Vals.push_back(GetEncodedSynchScope(cast<StoreInst>(I).getSynchScope()));
2187     }
2188     break;
2189   case Instruction::AtomicCmpXchg:
2190     Code = bitc::FUNC_CODE_INST_CMPXCHG;
2191     PushValueAndType(I.getOperand(0), InstID, Vals, VE);  // ptrty + ptr
2192     PushValueAndType(I.getOperand(1), InstID, Vals, VE);  // cmp.
2193     pushValue(I.getOperand(2), InstID, Vals, VE);         // newval.
2194     Vals.push_back(cast<AtomicCmpXchgInst>(I).isVolatile());
2195     Vals.push_back(GetEncodedOrdering(
2196                      cast<AtomicCmpXchgInst>(I).getSuccessOrdering()));
2197     Vals.push_back(GetEncodedSynchScope(
2198                      cast<AtomicCmpXchgInst>(I).getSynchScope()));
2199     Vals.push_back(GetEncodedOrdering(
2200                      cast<AtomicCmpXchgInst>(I).getFailureOrdering()));
2201     Vals.push_back(cast<AtomicCmpXchgInst>(I).isWeak());
2202     break;
2203   case Instruction::AtomicRMW:
2204     Code = bitc::FUNC_CODE_INST_ATOMICRMW;
2205     PushValueAndType(I.getOperand(0), InstID, Vals, VE);  // ptrty + ptr
2206     pushValue(I.getOperand(1), InstID, Vals, VE);         // val.
2207     Vals.push_back(GetEncodedRMWOperation(
2208                      cast<AtomicRMWInst>(I).getOperation()));
2209     Vals.push_back(cast<AtomicRMWInst>(I).isVolatile());
2210     Vals.push_back(GetEncodedOrdering(cast<AtomicRMWInst>(I).getOrdering()));
2211     Vals.push_back(GetEncodedSynchScope(
2212                      cast<AtomicRMWInst>(I).getSynchScope()));
2213     break;
2214   case Instruction::Fence:
2215     Code = bitc::FUNC_CODE_INST_FENCE;
2216     Vals.push_back(GetEncodedOrdering(cast<FenceInst>(I).getOrdering()));
2217     Vals.push_back(GetEncodedSynchScope(cast<FenceInst>(I).getSynchScope()));
2218     break;
2219   case Instruction::Call: {
2220     const CallInst &CI = cast<CallInst>(I);
2221     FunctionType *FTy = CI.getFunctionType();
2222 
2223     if (CI.hasOperandBundles())
2224       WriteOperandBundles(Stream, &CI, InstID, VE);
2225 
2226     Code = bitc::FUNC_CODE_INST_CALL;
2227 
2228     Vals.push_back(VE.getAttributeID(CI.getAttributes()));
2229 
2230     unsigned Flags = GetOptimizationFlags(&I);
2231     Vals.push_back(CI.getCallingConv() << bitc::CALL_CCONV |
2232                    unsigned(CI.isTailCall()) << bitc::CALL_TAIL |
2233                    unsigned(CI.isMustTailCall()) << bitc::CALL_MUSTTAIL |
2234                    1 << bitc::CALL_EXPLICIT_TYPE |
2235                    unsigned(CI.isNoTailCall()) << bitc::CALL_NOTAIL |
2236                    unsigned(Flags != 0) << bitc::CALL_FMF);
2237     if (Flags != 0)
2238       Vals.push_back(Flags);
2239 
2240     Vals.push_back(VE.getTypeID(FTy));
2241     PushValueAndType(CI.getCalledValue(), InstID, Vals, VE);  // Callee
2242 
2243     // Emit value #'s for the fixed parameters.
2244     for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
2245       // Check for labels (can happen with asm labels).
2246       if (FTy->getParamType(i)->isLabelTy())
2247         Vals.push_back(VE.getValueID(CI.getArgOperand(i)));
2248       else
2249         pushValue(CI.getArgOperand(i), InstID, Vals, VE);  // fixed param.
2250     }
2251 
2252     // Emit type/value pairs for varargs params.
2253     if (FTy->isVarArg()) {
2254       for (unsigned i = FTy->getNumParams(), e = CI.getNumArgOperands();
2255            i != e; ++i)
2256         PushValueAndType(CI.getArgOperand(i), InstID, Vals, VE);  // varargs
2257     }
2258     break;
2259   }
2260   case Instruction::VAArg:
2261     Code = bitc::FUNC_CODE_INST_VAARG;
2262     Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));   // valistty
2263     pushValue(I.getOperand(0), InstID, Vals, VE); // valist.
2264     Vals.push_back(VE.getTypeID(I.getType())); // restype.
2265     break;
2266   }
2267 
2268   Stream.EmitRecord(Code, Vals, AbbrevToUse);
2269   Vals.clear();
2270 }
2271 
2272 /// Emit names for globals/functions etc. The VSTOffsetPlaceholder,
2273 /// BitcodeStartBit and ModuleSummaryIndex are only passed for the module-level
2274 /// VST, where we are including a function bitcode index and need to
2275 /// backpatch the VST forward declaration record.
2276 static void WriteValueSymbolTable(
2277     const ValueSymbolTable &VST, const ValueEnumerator &VE,
2278     BitstreamWriter &Stream, uint64_t VSTOffsetPlaceholder = 0,
2279     uint64_t BitcodeStartBit = 0,
2280     DenseMap<const Function *, uint64_t> *FunctionToBitcodeIndex = nullptr) {
2281   if (VST.empty()) {
2282     // WriteValueSymbolTableForwardDecl should have returned early as
2283     // well. Ensure this handling remains in sync by asserting that
2284     // the placeholder offset is not set.
2285     assert(VSTOffsetPlaceholder == 0);
2286     return;
2287   }
2288 
2289   if (VSTOffsetPlaceholder > 0) {
2290     // Get the offset of the VST we are writing, and backpatch it into
2291     // the VST forward declaration record.
2292     uint64_t VSTOffset = Stream.GetCurrentBitNo();
2293     // The BitcodeStartBit was the stream offset of the actual bitcode
2294     // (e.g. excluding any initial darwin header).
2295     VSTOffset -= BitcodeStartBit;
2296     assert((VSTOffset & 31) == 0 && "VST block not 32-bit aligned");
2297     Stream.BackpatchWord(VSTOffsetPlaceholder, VSTOffset / 32);
2298   }
2299 
2300   Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
2301 
2302   // For the module-level VST, add abbrev Ids for the VST_CODE_FNENTRY
2303   // records, which are not used in the per-function VSTs.
2304   unsigned FnEntry8BitAbbrev;
2305   unsigned FnEntry7BitAbbrev;
2306   unsigned FnEntry6BitAbbrev;
2307   if (VSTOffsetPlaceholder > 0) {
2308     // 8-bit fixed-width VST_CODE_FNENTRY function strings.
2309     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2310     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_FNENTRY));
2311     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
2312     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // funcoffset
2313     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2314     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
2315     FnEntry8BitAbbrev = Stream.EmitAbbrev(Abbv);
2316 
2317     // 7-bit fixed width VST_CODE_FNENTRY function strings.
2318     Abbv = new BitCodeAbbrev();
2319     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_FNENTRY));
2320     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
2321     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // funcoffset
2322     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2323     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
2324     FnEntry7BitAbbrev = Stream.EmitAbbrev(Abbv);
2325 
2326     // 6-bit char6 VST_CODE_FNENTRY function strings.
2327     Abbv = new BitCodeAbbrev();
2328     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_FNENTRY));
2329     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
2330     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // funcoffset
2331     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2332     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
2333     FnEntry6BitAbbrev = Stream.EmitAbbrev(Abbv);
2334   }
2335 
2336   // FIXME: Set up the abbrev, we know how many values there are!
2337   // FIXME: We know if the type names can use 7-bit ascii.
2338   SmallVector<unsigned, 64> NameVals;
2339 
2340   for (const ValueName &Name : VST) {
2341     // Figure out the encoding to use for the name.
2342     StringEncoding Bits =
2343         getStringEncoding(Name.getKeyData(), Name.getKeyLength());
2344 
2345     unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
2346     NameVals.push_back(VE.getValueID(Name.getValue()));
2347 
2348     Function *F = dyn_cast<Function>(Name.getValue());
2349     if (!F) {
2350       // If value is an alias, need to get the aliased base object to
2351       // see if it is a function.
2352       auto *GA = dyn_cast<GlobalAlias>(Name.getValue());
2353       if (GA && GA->getBaseObject())
2354         F = dyn_cast<Function>(GA->getBaseObject());
2355     }
2356 
2357     // VST_CODE_ENTRY:   [valueid, namechar x N]
2358     // VST_CODE_FNENTRY: [valueid, funcoffset, namechar x N]
2359     // VST_CODE_BBENTRY: [bbid, namechar x N]
2360     unsigned Code;
2361     if (isa<BasicBlock>(Name.getValue())) {
2362       Code = bitc::VST_CODE_BBENTRY;
2363       if (Bits == SE_Char6)
2364         AbbrevToUse = VST_BBENTRY_6_ABBREV;
2365     } else if (F && !F->isDeclaration()) {
2366       // Must be the module-level VST, where we pass in the Index and
2367       // have a VSTOffsetPlaceholder. The function-level VST should not
2368       // contain any Function symbols.
2369       assert(FunctionToBitcodeIndex);
2370       assert(VSTOffsetPlaceholder > 0);
2371 
2372       // Save the word offset of the function (from the start of the
2373       // actual bitcode written to the stream).
2374       uint64_t BitcodeIndex = (*FunctionToBitcodeIndex)[F] - BitcodeStartBit;
2375       assert((BitcodeIndex & 31) == 0 && "function block not 32-bit aligned");
2376       NameVals.push_back(BitcodeIndex / 32);
2377 
2378       Code = bitc::VST_CODE_FNENTRY;
2379       AbbrevToUse = FnEntry8BitAbbrev;
2380       if (Bits == SE_Char6)
2381         AbbrevToUse = FnEntry6BitAbbrev;
2382       else if (Bits == SE_Fixed7)
2383         AbbrevToUse = FnEntry7BitAbbrev;
2384     } else {
2385       Code = bitc::VST_CODE_ENTRY;
2386       if (Bits == SE_Char6)
2387         AbbrevToUse = VST_ENTRY_6_ABBREV;
2388       else if (Bits == SE_Fixed7)
2389         AbbrevToUse = VST_ENTRY_7_ABBREV;
2390     }
2391 
2392     for (const auto P : Name.getKey())
2393       NameVals.push_back((unsigned char)P);
2394 
2395     // Emit the finished record.
2396     Stream.EmitRecord(Code, NameVals, AbbrevToUse);
2397     NameVals.clear();
2398   }
2399   Stream.ExitBlock();
2400 }
2401 
2402 /// Emit function names and summary offsets for the combined index
2403 /// used by ThinLTO.
2404 static void WriteCombinedValueSymbolTable(
2405     const ModuleSummaryIndex &Index, BitstreamWriter &Stream,
2406     std::map<GlobalValue::GUID, unsigned> &GUIDToValueIdMap,
2407     uint64_t VSTOffsetPlaceholder) {
2408   assert(VSTOffsetPlaceholder > 0 && "Expected non-zero VSTOffsetPlaceholder");
2409   // Get the offset of the VST we are writing, and backpatch it into
2410   // the VST forward declaration record.
2411   uint64_t VSTOffset = Stream.GetCurrentBitNo();
2412   assert((VSTOffset & 31) == 0 && "VST block not 32-bit aligned");
2413   Stream.BackpatchWord(VSTOffsetPlaceholder, VSTOffset / 32);
2414 
2415   Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
2416 
2417   BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2418   Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_COMBINED_GVDEFENTRY));
2419   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
2420   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // sumoffset
2421   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // guid
2422   unsigned DefEntryAbbrev = Stream.EmitAbbrev(Abbv);
2423 
2424   Abbv = new BitCodeAbbrev();
2425   Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_COMBINED_ENTRY));
2426   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
2427   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // refguid
2428   unsigned EntryAbbrev = Stream.EmitAbbrev(Abbv);
2429 
2430   SmallVector<uint64_t, 64> NameVals;
2431 
2432   for (const auto &FII : Index) {
2433     GlobalValue::GUID FuncGUID = FII.first;
2434     const auto &VMI = GUIDToValueIdMap.find(FuncGUID);
2435     assert(VMI != GUIDToValueIdMap.end());
2436 
2437     for (const auto &FI : FII.second) {
2438       // VST_CODE_COMBINED_GVDEFENTRY: [valueid, sumoffset, guid]
2439       NameVals.push_back(VMI->second);
2440       NameVals.push_back(FI->bitcodeIndex());
2441       NameVals.push_back(FuncGUID);
2442 
2443       // Emit the finished record.
2444       Stream.EmitRecord(bitc::VST_CODE_COMBINED_GVDEFENTRY, NameVals,
2445                         DefEntryAbbrev);
2446       NameVals.clear();
2447     }
2448     GUIDToValueIdMap.erase(VMI);
2449   }
2450   for (const auto &GVI : GUIDToValueIdMap) {
2451     // VST_CODE_COMBINED_ENTRY: [valueid, refguid]
2452     NameVals.push_back(GVI.second);
2453     NameVals.push_back(GVI.first);
2454 
2455     // Emit the finished record.
2456     Stream.EmitRecord(bitc::VST_CODE_COMBINED_ENTRY, NameVals, EntryAbbrev);
2457     NameVals.clear();
2458   }
2459   Stream.ExitBlock();
2460 }
2461 
2462 static void WriteUseList(ValueEnumerator &VE, UseListOrder &&Order,
2463                          BitstreamWriter &Stream) {
2464   assert(Order.Shuffle.size() >= 2 && "Shuffle too small");
2465   unsigned Code;
2466   if (isa<BasicBlock>(Order.V))
2467     Code = bitc::USELIST_CODE_BB;
2468   else
2469     Code = bitc::USELIST_CODE_DEFAULT;
2470 
2471   SmallVector<uint64_t, 64> Record(Order.Shuffle.begin(), Order.Shuffle.end());
2472   Record.push_back(VE.getValueID(Order.V));
2473   Stream.EmitRecord(Code, Record);
2474 }
2475 
2476 static void WriteUseListBlock(const Function *F, ValueEnumerator &VE,
2477                               BitstreamWriter &Stream) {
2478   assert(VE.shouldPreserveUseListOrder() &&
2479          "Expected to be preserving use-list order");
2480 
2481   auto hasMore = [&]() {
2482     return !VE.UseListOrders.empty() && VE.UseListOrders.back().F == F;
2483   };
2484   if (!hasMore())
2485     // Nothing to do.
2486     return;
2487 
2488   Stream.EnterSubblock(bitc::USELIST_BLOCK_ID, 3);
2489   while (hasMore()) {
2490     WriteUseList(VE, std::move(VE.UseListOrders.back()), Stream);
2491     VE.UseListOrders.pop_back();
2492   }
2493   Stream.ExitBlock();
2494 }
2495 
2496 /// Emit a function body to the module stream.
2497 static void
2498 WriteFunction(const Function &F, const Module *M, ValueEnumerator &VE,
2499               BitstreamWriter &Stream,
2500               DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) {
2501   // Save the bitcode index of the start of this function block for recording
2502   // in the VST.
2503   FunctionToBitcodeIndex[&F] = Stream.GetCurrentBitNo();
2504 
2505   Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 4);
2506   VE.incorporateFunction(F);
2507 
2508   SmallVector<unsigned, 64> Vals;
2509 
2510   // Emit the number of basic blocks, so the reader can create them ahead of
2511   // time.
2512   Vals.push_back(VE.getBasicBlocks().size());
2513   Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals);
2514   Vals.clear();
2515 
2516   // If there are function-local constants, emit them now.
2517   unsigned CstStart, CstEnd;
2518   VE.getFunctionConstantRange(CstStart, CstEnd);
2519   WriteConstants(CstStart, CstEnd, VE, Stream, false);
2520 
2521   // If there is function-local metadata, emit it now.
2522   writeFunctionMetadata(F, VE, Stream);
2523 
2524   // Keep a running idea of what the instruction ID is.
2525   unsigned InstID = CstEnd;
2526 
2527   bool NeedsMetadataAttachment = F.hasMetadata();
2528 
2529   DILocation *LastDL = nullptr;
2530   // Finally, emit all the instructions, in order.
2531   for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
2532     for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
2533          I != E; ++I) {
2534       WriteInstruction(*I, InstID, VE, Stream, Vals);
2535 
2536       if (!I->getType()->isVoidTy())
2537         ++InstID;
2538 
2539       // If the instruction has metadata, write a metadata attachment later.
2540       NeedsMetadataAttachment |= I->hasMetadataOtherThanDebugLoc();
2541 
2542       // If the instruction has a debug location, emit it.
2543       DILocation *DL = I->getDebugLoc();
2544       if (!DL)
2545         continue;
2546 
2547       if (DL == LastDL) {
2548         // Just repeat the same debug loc as last time.
2549         Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC_AGAIN, Vals);
2550         continue;
2551       }
2552 
2553       Vals.push_back(DL->getLine());
2554       Vals.push_back(DL->getColumn());
2555       Vals.push_back(VE.getMetadataOrNullID(DL->getScope()));
2556       Vals.push_back(VE.getMetadataOrNullID(DL->getInlinedAt()));
2557       Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC, Vals);
2558       Vals.clear();
2559 
2560       LastDL = DL;
2561     }
2562 
2563   // Emit names for all the instructions etc.
2564   WriteValueSymbolTable(F.getValueSymbolTable(), VE, Stream);
2565 
2566   if (NeedsMetadataAttachment)
2567     WriteMetadataAttachment(F, VE, Stream);
2568   if (VE.shouldPreserveUseListOrder())
2569     WriteUseListBlock(&F, VE, Stream);
2570   VE.purgeFunction();
2571   Stream.ExitBlock();
2572 }
2573 
2574 // Emit blockinfo, which defines the standard abbreviations etc.
2575 static void WriteBlockInfo(const ValueEnumerator &VE, BitstreamWriter &Stream) {
2576   // We only want to emit block info records for blocks that have multiple
2577   // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK.
2578   // Other blocks can define their abbrevs inline.
2579   Stream.EnterBlockInfoBlock(2);
2580 
2581   { // 8-bit fixed-width VST_CODE_ENTRY/VST_CODE_BBENTRY strings.
2582     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2583     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3));
2584     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2585     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2586     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
2587     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
2588                                    Abbv) != VST_ENTRY_8_ABBREV)
2589       llvm_unreachable("Unexpected abbrev ordering!");
2590   }
2591 
2592   { // 7-bit fixed width VST_CODE_ENTRY strings.
2593     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2594     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
2595     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2596     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2597     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
2598     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
2599                                    Abbv) != VST_ENTRY_7_ABBREV)
2600       llvm_unreachable("Unexpected abbrev ordering!");
2601   }
2602   { // 6-bit char6 VST_CODE_ENTRY strings.
2603     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2604     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
2605     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2606     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2607     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
2608     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
2609                                    Abbv) != VST_ENTRY_6_ABBREV)
2610       llvm_unreachable("Unexpected abbrev ordering!");
2611   }
2612   { // 6-bit char6 VST_CODE_BBENTRY strings.
2613     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2614     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY));
2615     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2616     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2617     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
2618     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
2619                                    Abbv) != VST_BBENTRY_6_ABBREV)
2620       llvm_unreachable("Unexpected abbrev ordering!");
2621   }
2622 
2623 
2624 
2625   { // SETTYPE abbrev for CONSTANTS_BLOCK.
2626     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2627     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_SETTYPE));
2628     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
2629                               VE.computeBitsRequiredForTypeIndicies()));
2630     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
2631                                    Abbv) != CONSTANTS_SETTYPE_ABBREV)
2632       llvm_unreachable("Unexpected abbrev ordering!");
2633   }
2634 
2635   { // INTEGER abbrev for CONSTANTS_BLOCK.
2636     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2637     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_INTEGER));
2638     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2639     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
2640                                    Abbv) != CONSTANTS_INTEGER_ABBREV)
2641       llvm_unreachable("Unexpected abbrev ordering!");
2642   }
2643 
2644   { // CE_CAST abbrev for CONSTANTS_BLOCK.
2645     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2646     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CE_CAST));
2647     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4));  // cast opc
2648     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,       // typeid
2649                               VE.computeBitsRequiredForTypeIndicies()));
2650     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));    // value id
2651 
2652     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
2653                                    Abbv) != CONSTANTS_CE_CAST_Abbrev)
2654       llvm_unreachable("Unexpected abbrev ordering!");
2655   }
2656   { // NULL abbrev for CONSTANTS_BLOCK.
2657     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2658     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_NULL));
2659     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
2660                                    Abbv) != CONSTANTS_NULL_Abbrev)
2661       llvm_unreachable("Unexpected abbrev ordering!");
2662   }
2663 
2664   // FIXME: This should only use space for first class types!
2665 
2666   { // INST_LOAD abbrev for FUNCTION_BLOCK.
2667     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2668     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_LOAD));
2669     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Ptr
2670     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,    // dest ty
2671                               VE.computeBitsRequiredForTypeIndicies()));
2672     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align
2673     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile
2674     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
2675                                    Abbv) != FUNCTION_INST_LOAD_ABBREV)
2676       llvm_unreachable("Unexpected abbrev ordering!");
2677   }
2678   { // INST_BINOP abbrev for FUNCTION_BLOCK.
2679     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2680     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
2681     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
2682     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
2683     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
2684     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
2685                                    Abbv) != FUNCTION_INST_BINOP_ABBREV)
2686       llvm_unreachable("Unexpected abbrev ordering!");
2687   }
2688   { // INST_BINOP_FLAGS abbrev for FUNCTION_BLOCK.
2689     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2690     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
2691     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
2692     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
2693     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
2694     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7)); // flags
2695     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
2696                                    Abbv) != FUNCTION_INST_BINOP_FLAGS_ABBREV)
2697       llvm_unreachable("Unexpected abbrev ordering!");
2698   }
2699   { // INST_CAST abbrev for FUNCTION_BLOCK.
2700     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2701     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST));
2702     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));    // OpVal
2703     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,       // dest ty
2704                               VE.computeBitsRequiredForTypeIndicies()));
2705     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4));  // opc
2706     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
2707                                    Abbv) != FUNCTION_INST_CAST_ABBREV)
2708       llvm_unreachable("Unexpected abbrev ordering!");
2709   }
2710 
2711   { // INST_RET abbrev for FUNCTION_BLOCK.
2712     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2713     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
2714     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
2715                                    Abbv) != FUNCTION_INST_RET_VOID_ABBREV)
2716       llvm_unreachable("Unexpected abbrev ordering!");
2717   }
2718   { // INST_RET abbrev for FUNCTION_BLOCK.
2719     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2720     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
2721     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ValID
2722     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
2723                                    Abbv) != FUNCTION_INST_RET_VAL_ABBREV)
2724       llvm_unreachable("Unexpected abbrev ordering!");
2725   }
2726   { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK.
2727     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2728     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNREACHABLE));
2729     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
2730                                    Abbv) != FUNCTION_INST_UNREACHABLE_ABBREV)
2731       llvm_unreachable("Unexpected abbrev ordering!");
2732   }
2733   {
2734     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2735     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_GEP));
2736     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
2737     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
2738                               Log2_32_Ceil(VE.getTypes().size() + 1)));
2739     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2740     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
2741     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
2742         FUNCTION_INST_GEP_ABBREV)
2743       llvm_unreachable("Unexpected abbrev ordering!");
2744   }
2745 
2746   Stream.ExitBlock();
2747 }
2748 
2749 /// Write the module path strings, currently only used when generating
2750 /// a combined index file.
2751 static void WriteModStrings(const ModuleSummaryIndex &I,
2752                             BitstreamWriter &Stream) {
2753   Stream.EnterSubblock(bitc::MODULE_STRTAB_BLOCK_ID, 3);
2754 
2755   // TODO: See which abbrev sizes we actually need to emit
2756 
2757   // 8-bit fixed-width MST_ENTRY strings.
2758   BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2759   Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
2760   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2761   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2762   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
2763   unsigned Abbrev8Bit = Stream.EmitAbbrev(Abbv);
2764 
2765   // 7-bit fixed width MST_ENTRY strings.
2766   Abbv = new BitCodeAbbrev();
2767   Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
2768   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2769   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2770   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
2771   unsigned Abbrev7Bit = Stream.EmitAbbrev(Abbv);
2772 
2773   // 6-bit char6 MST_ENTRY strings.
2774   Abbv = new BitCodeAbbrev();
2775   Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
2776   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2777   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2778   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
2779   unsigned Abbrev6Bit = Stream.EmitAbbrev(Abbv);
2780 
2781   // Module Hash, 160 bits SHA1. Optionally, emitted after each MST_CODE_ENTRY.
2782   Abbv = new BitCodeAbbrev();
2783   Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_HASH));
2784   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
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   unsigned AbbrevHash = Stream.EmitAbbrev(Abbv);
2790 
2791   SmallVector<unsigned, 64> Vals;
2792   for (const auto &MPSE : I.modulePaths()) {
2793     StringEncoding Bits =
2794         getStringEncoding(MPSE.getKey().data(), MPSE.getKey().size());
2795     unsigned AbbrevToUse = Abbrev8Bit;
2796     if (Bits == SE_Char6)
2797       AbbrevToUse = Abbrev6Bit;
2798     else if (Bits == SE_Fixed7)
2799       AbbrevToUse = Abbrev7Bit;
2800 
2801     Vals.push_back(MPSE.getValue().first);
2802 
2803     for (const auto P : MPSE.getKey())
2804       Vals.push_back((unsigned char)P);
2805 
2806     // Emit the finished record.
2807     Stream.EmitRecord(bitc::MST_CODE_ENTRY, Vals, AbbrevToUse);
2808 
2809     Vals.clear();
2810     // Emit an optional hash for the module now
2811     auto &Hash = MPSE.getValue().second;
2812     bool AllZero = true; // Detect if the hash is empty, and do not generate it
2813     for (auto Val : Hash) {
2814       if (Val)
2815         AllZero = false;
2816       Vals.push_back(Val);
2817     }
2818     if (!AllZero) {
2819       // Emit the hash record.
2820       Stream.EmitRecord(bitc::MST_CODE_HASH, Vals, AbbrevHash);
2821     }
2822 
2823     Vals.clear();
2824   }
2825   Stream.ExitBlock();
2826 }
2827 
2828 // Helper to emit a single function summary record.
2829 static void WritePerModuleFunctionSummaryRecord(
2830     SmallVector<uint64_t, 64> &NameVals, GlobalValueInfo *Info,
2831     unsigned ValueID, const ValueEnumerator &VE, unsigned FSCallsAbbrev,
2832     unsigned FSCallsProfileAbbrev, BitstreamWriter &Stream, const Function &F) {
2833   NameVals.push_back(ValueID);
2834 
2835   FunctionSummary *FS = cast<FunctionSummary>(Info->summary());
2836   NameVals.push_back(getEncodedLinkage(FS->linkage()));
2837   NameVals.push_back(FS->instCount());
2838   NameVals.push_back(FS->refs().size());
2839 
2840   for (auto &RI : FS->refs())
2841     NameVals.push_back(VE.getValueID(RI.getValue()));
2842 
2843   bool HasProfileData = F.getEntryCount().hasValue();
2844   for (auto &ECI : FS->calls()) {
2845     NameVals.push_back(VE.getValueID(ECI.first.getValue()));
2846     assert(ECI.second.CallsiteCount > 0 && "Expected at least one callsite");
2847     NameVals.push_back(ECI.second.CallsiteCount);
2848     if (HasProfileData)
2849       NameVals.push_back(ECI.second.ProfileCount);
2850   }
2851 
2852   unsigned FSAbbrev = (HasProfileData ? FSCallsProfileAbbrev : FSCallsAbbrev);
2853   unsigned Code =
2854       (HasProfileData ? bitc::FS_PERMODULE_PROFILE : bitc::FS_PERMODULE);
2855 
2856   // Emit the finished record.
2857   Stream.EmitRecord(Code, NameVals, FSAbbrev);
2858   NameVals.clear();
2859 }
2860 
2861 // Collect the global value references in the given variable's initializer,
2862 // and emit them in a summary record.
2863 static void WriteModuleLevelReferences(const GlobalVariable &V,
2864                                        const ModuleSummaryIndex &Index,
2865                                        const ValueEnumerator &VE,
2866                                        SmallVector<uint64_t, 64> &NameVals,
2867                                        unsigned FSModRefsAbbrev,
2868                                        BitstreamWriter &Stream) {
2869   // Only interested in recording variable defs in the summary.
2870   if (V.isDeclaration())
2871     return;
2872   NameVals.push_back(VE.getValueID(&V));
2873   NameVals.push_back(getEncodedLinkage(V.getLinkage()));
2874   auto *Info = Index.getGlobalValueInfo(V);
2875   GlobalVarSummary *VS = cast<GlobalVarSummary>(Info->summary());
2876   for (auto Ref : VS->refs())
2877     NameVals.push_back(VE.getValueID(Ref.getValue()));
2878   Stream.EmitRecord(bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS, NameVals,
2879                     FSModRefsAbbrev);
2880   NameVals.clear();
2881 }
2882 
2883 /// Emit the per-module summary section alongside the rest of
2884 /// the module's bitcode.
2885 static void WritePerModuleGlobalValueSummary(const Module *M,
2886                                              const ModuleSummaryIndex &Index,
2887                                              const ValueEnumerator &VE,
2888                                              BitstreamWriter &Stream) {
2889   if (M->empty())
2890     return;
2891 
2892   Stream.EnterSubblock(bitc::GLOBALVAL_SUMMARY_BLOCK_ID, 3);
2893 
2894   // Abbrev for FS_PERMODULE.
2895   BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2896   Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE));
2897   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // valueid
2898   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5)); // linkage
2899   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // instcount
2900   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // numrefs
2901   // numrefs x valueid, n x (valueid, callsitecount)
2902   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2903   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2904   unsigned FSCallsAbbrev = Stream.EmitAbbrev(Abbv);
2905 
2906   // Abbrev for FS_PERMODULE_PROFILE.
2907   Abbv = new BitCodeAbbrev();
2908   Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_PROFILE));
2909   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // valueid
2910   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5)); // linkage
2911   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // instcount
2912   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // numrefs
2913   // numrefs x valueid, n x (valueid, callsitecount, profilecount)
2914   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2915   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2916   unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(Abbv);
2917 
2918   // Abbrev for FS_PERMODULE_GLOBALVAR_INIT_REFS.
2919   Abbv = new BitCodeAbbrev();
2920   Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS));
2921   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
2922   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5)); // linkage
2923   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));  // valueids
2924   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2925   unsigned FSModRefsAbbrev = Stream.EmitAbbrev(Abbv);
2926 
2927   SmallVector<uint64_t, 64> NameVals;
2928   // Iterate over the list of functions instead of the Index to
2929   // ensure the ordering is stable.
2930   for (const Function &F : *M) {
2931     if (F.isDeclaration())
2932       continue;
2933     // Skip anonymous functions. We will emit a function summary for
2934     // any aliases below.
2935     if (!F.hasName())
2936       continue;
2937 
2938     auto *Info = Index.getGlobalValueInfo(F);
2939     WritePerModuleFunctionSummaryRecord(
2940         NameVals, Info,
2941         VE.getValueID(M->getValueSymbolTable().lookup(F.getName())), VE,
2942         FSCallsAbbrev, FSCallsProfileAbbrev, Stream, F);
2943   }
2944 
2945   // Capture references from GlobalVariable initializers, which are outside
2946   // of a function scope.
2947   for (const GlobalVariable &G : M->globals())
2948     WriteModuleLevelReferences(G, Index, VE, NameVals, FSModRefsAbbrev, Stream);
2949 
2950   Stream.ExitBlock();
2951 }
2952 
2953 /// Emit the combined summary section into the combined index file.
2954 static void WriteCombinedGlobalValueSummary(
2955     const ModuleSummaryIndex &Index, BitstreamWriter &Stream,
2956     std::map<GlobalValue::GUID, unsigned> &GUIDToValueIdMap,
2957     unsigned GlobalValueId) {
2958   Stream.EnterSubblock(bitc::GLOBALVAL_SUMMARY_BLOCK_ID, 3);
2959 
2960   // Abbrev for FS_COMBINED.
2961   BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2962   Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED));
2963   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // modid
2964   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5)); // linkage
2965   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // instcount
2966   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // numrefs
2967   // numrefs x valueid, n x (valueid, callsitecount)
2968   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2969   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2970   unsigned FSCallsAbbrev = Stream.EmitAbbrev(Abbv);
2971 
2972   // Abbrev for FS_COMBINED_PROFILE.
2973   Abbv = new BitCodeAbbrev();
2974   Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_PROFILE));
2975   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // modid
2976   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5)); // linkage
2977   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // instcount
2978   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // numrefs
2979   // numrefs x valueid, n x (valueid, callsitecount, profilecount)
2980   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2981   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2982   unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(Abbv);
2983 
2984   // Abbrev for FS_COMBINED_GLOBALVAR_INIT_REFS.
2985   Abbv = new BitCodeAbbrev();
2986   Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_GLOBALVAR_INIT_REFS));
2987   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // modid
2988   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5)); // linkage
2989   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));    // valueids
2990   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2991   unsigned FSModRefsAbbrev = Stream.EmitAbbrev(Abbv);
2992 
2993   SmallVector<uint64_t, 64> NameVals;
2994   for (const auto &FII : Index) {
2995     for (auto &FI : FII.second) {
2996       GlobalValueSummary *S = FI->summary();
2997       assert(S);
2998 
2999       if (auto *VS = dyn_cast<GlobalVarSummary>(S)) {
3000         NameVals.push_back(Index.getModuleId(VS->modulePath()));
3001         NameVals.push_back(getEncodedLinkage(VS->linkage()));
3002         for (auto &RI : VS->refs()) {
3003           const auto &VMI = GUIDToValueIdMap.find(RI.getGUID());
3004           unsigned RefId;
3005           // If this GUID doesn't have an entry, assign one.
3006           if (VMI == GUIDToValueIdMap.end()) {
3007             GUIDToValueIdMap[RI.getGUID()] = ++GlobalValueId;
3008             RefId = GlobalValueId;
3009           } else {
3010             RefId = VMI->second;
3011           }
3012           NameVals.push_back(RefId);
3013         }
3014 
3015         // Record the starting offset of this summary entry for use
3016         // in the VST entry. Add the current code size since the
3017         // reader will invoke readRecord after the abbrev id read.
3018         FI->setBitcodeIndex(Stream.GetCurrentBitNo() +
3019                             Stream.GetAbbrevIDWidth());
3020 
3021         // Emit the finished record.
3022         Stream.EmitRecord(bitc::FS_COMBINED_GLOBALVAR_INIT_REFS, NameVals,
3023                           FSModRefsAbbrev);
3024         NameVals.clear();
3025         continue;
3026       }
3027 
3028       auto *FS = cast<FunctionSummary>(S);
3029       NameVals.push_back(Index.getModuleId(FS->modulePath()));
3030       NameVals.push_back(getEncodedLinkage(FS->linkage()));
3031       NameVals.push_back(FS->instCount());
3032       NameVals.push_back(FS->refs().size());
3033 
3034       for (auto &RI : FS->refs()) {
3035         const auto &VMI = GUIDToValueIdMap.find(RI.getGUID());
3036         unsigned RefId;
3037         // If this GUID doesn't have an entry, assign one.
3038         if (VMI == GUIDToValueIdMap.end()) {
3039           GUIDToValueIdMap[RI.getGUID()] = ++GlobalValueId;
3040           RefId = GlobalValueId;
3041         } else {
3042           RefId = VMI->second;
3043         }
3044         NameVals.push_back(RefId);
3045       }
3046 
3047       bool HasProfileData = false;
3048       for (auto &EI : FS->calls()) {
3049         HasProfileData |= EI.second.ProfileCount != 0;
3050         if (HasProfileData)
3051           break;
3052       }
3053 
3054       for (auto &EI : FS->calls()) {
3055         const auto &VMI = GUIDToValueIdMap.find(EI.first.getGUID());
3056         // If this GUID doesn't have an entry, it doesn't have a function
3057         // summary and we don't need to record any calls to it.
3058         if (VMI == GUIDToValueIdMap.end())
3059           continue;
3060         NameVals.push_back(VMI->second);
3061         assert(EI.second.CallsiteCount > 0 && "Expected at least one callsite");
3062         NameVals.push_back(EI.second.CallsiteCount);
3063         if (HasProfileData)
3064           NameVals.push_back(EI.second.ProfileCount);
3065       }
3066 
3067       // Record the starting offset of this summary entry for use
3068       // in the VST entry. Add the current code size since the
3069       // reader will invoke readRecord after the abbrev id read.
3070       FI->setBitcodeIndex(Stream.GetCurrentBitNo() + Stream.GetAbbrevIDWidth());
3071 
3072       unsigned FSAbbrev =
3073           (HasProfileData ? FSCallsProfileAbbrev : FSCallsAbbrev);
3074       unsigned Code =
3075           (HasProfileData ? bitc::FS_COMBINED_PROFILE : bitc::FS_COMBINED);
3076 
3077       // Emit the finished record.
3078       Stream.EmitRecord(Code, NameVals, FSAbbrev);
3079       NameVals.clear();
3080     }
3081   }
3082 
3083   Stream.ExitBlock();
3084 }
3085 
3086 // Create the "IDENTIFICATION_BLOCK_ID" containing a single string with the
3087 // current llvm version, and a record for the epoch number.
3088 static void WriteIdentificationBlock(const Module *M, BitstreamWriter &Stream) {
3089   Stream.EnterSubblock(bitc::IDENTIFICATION_BLOCK_ID, 5);
3090 
3091   // Write the "user readable" string identifying the bitcode producer
3092   BitCodeAbbrev *Abbv = new BitCodeAbbrev();
3093   Abbv->Add(BitCodeAbbrevOp(bitc::IDENTIFICATION_CODE_STRING));
3094   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3095   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
3096   auto StringAbbrev = Stream.EmitAbbrev(Abbv);
3097   WriteStringRecord(bitc::IDENTIFICATION_CODE_STRING,
3098                     "LLVM" LLVM_VERSION_STRING, StringAbbrev, Stream);
3099 
3100   // Write the epoch version
3101   Abbv = new BitCodeAbbrev();
3102   Abbv->Add(BitCodeAbbrevOp(bitc::IDENTIFICATION_CODE_EPOCH));
3103   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
3104   auto EpochAbbrev = Stream.EmitAbbrev(Abbv);
3105   SmallVector<unsigned, 1> Vals = {bitc::BITCODE_CURRENT_EPOCH};
3106   Stream.EmitRecord(bitc::IDENTIFICATION_CODE_EPOCH, Vals, EpochAbbrev);
3107   Stream.ExitBlock();
3108 }
3109 
3110 static void writeModuleHash(BitstreamWriter &Stream,
3111                             SmallVectorImpl<char> &Buffer,
3112                             size_t BlockStartPos) {
3113   // Emit the module's hash.
3114   // MODULE_CODE_HASH: [5*i32]
3115   SHA1 Hasher;
3116   Hasher.update(ArrayRef<uint8_t>((uint8_t *)&Buffer[BlockStartPos],
3117                                   Buffer.size() - BlockStartPos));
3118   auto Hash = Hasher.result();
3119   SmallVector<uint64_t, 20> Vals;
3120   auto LShift = [&](unsigned char Val, unsigned Amount)
3121                     -> uint64_t { return ((uint64_t)Val) << Amount; };
3122   for (int Pos = 0; Pos < 20; Pos += 4) {
3123     uint32_t SubHash = LShift(Hash[Pos + 0], 24);
3124     SubHash |= LShift(Hash[Pos + 1], 16) | LShift(Hash[Pos + 2], 8) |
3125                (unsigned)(unsigned char)Hash[Pos + 3];
3126     Vals.push_back(SubHash);
3127   }
3128 
3129   // Emit the finished record.
3130   Stream.EmitRecord(bitc::MODULE_CODE_HASH, Vals);
3131 }
3132 
3133 /// WriteModule - Emit the specified module to the bitstream.
3134 static void WriteModule(const Module *M, BitstreamWriter &Stream,
3135                         bool ShouldPreserveUseListOrder,
3136                         uint64_t BitcodeStartBit,
3137                         const ModuleSummaryIndex *Index, bool GenerateHash,
3138                         SmallVectorImpl<char> &Buffer) {
3139   Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
3140   size_t BlockStartPos = Buffer.size();
3141 
3142   SmallVector<unsigned, 1> Vals;
3143   unsigned CurVersion = 1;
3144   Vals.push_back(CurVersion);
3145   Stream.EmitRecord(bitc::MODULE_CODE_VERSION, Vals);
3146 
3147   // Analyze the module, enumerating globals, functions, etc.
3148   ValueEnumerator VE(*M, ShouldPreserveUseListOrder);
3149 
3150   // Emit blockinfo, which defines the standard abbreviations etc.
3151   WriteBlockInfo(VE, Stream);
3152 
3153   // Emit information about attribute groups.
3154   WriteAttributeGroupTable(VE, Stream);
3155 
3156   // Emit information about parameter attributes.
3157   WriteAttributeTable(VE, Stream);
3158 
3159   // Emit information describing all of the types in the module.
3160   WriteTypeTable(VE, Stream);
3161 
3162   writeComdats(VE, Stream);
3163 
3164   // Emit top-level description of module, including target triple, inline asm,
3165   // descriptors for global variables, and function prototype info.
3166   uint64_t VSTOffsetPlaceholder = WriteModuleInfo(M, VE, Stream);
3167 
3168   // Emit constants.
3169   WriteModuleConstants(VE, Stream);
3170 
3171   // Emit metadata.
3172   writeModuleMetadata(*M, VE, Stream);
3173 
3174   // Emit metadata.
3175   WriteModuleMetadataStore(M, Stream);
3176 
3177   // Emit module-level use-lists.
3178   if (VE.shouldPreserveUseListOrder())
3179     WriteUseListBlock(nullptr, VE, Stream);
3180 
3181   WriteOperandBundleTags(M, Stream);
3182 
3183   // Emit function bodies.
3184   DenseMap<const Function *, uint64_t> FunctionToBitcodeIndex;
3185   for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F)
3186     if (!F->isDeclaration())
3187       WriteFunction(*F, M, VE, Stream, FunctionToBitcodeIndex);
3188 
3189   // Need to write after the above call to WriteFunction which populates
3190   // the summary information in the index.
3191   if (Index)
3192     WritePerModuleGlobalValueSummary(M, *Index, VE, Stream);
3193 
3194   WriteValueSymbolTable(M->getValueSymbolTable(), VE, Stream,
3195                         VSTOffsetPlaceholder, BitcodeStartBit,
3196                         &FunctionToBitcodeIndex);
3197 
3198   if (GenerateHash) {
3199     writeModuleHash(Stream, Buffer, BlockStartPos);
3200   }
3201 
3202   Stream.ExitBlock();
3203 }
3204 
3205 /// EmitDarwinBCHeader - If generating a bc file on darwin, we have to emit a
3206 /// header and trailer to make it compatible with the system archiver.  To do
3207 /// this we emit the following header, and then emit a trailer that pads the
3208 /// file out to be a multiple of 16 bytes.
3209 ///
3210 /// struct bc_header {
3211 ///   uint32_t Magic;         // 0x0B17C0DE
3212 ///   uint32_t Version;       // Version, currently always 0.
3213 ///   uint32_t BitcodeOffset; // Offset to traditional bitcode file.
3214 ///   uint32_t BitcodeSize;   // Size of traditional bitcode file.
3215 ///   uint32_t CPUType;       // CPU specifier.
3216 ///   ... potentially more later ...
3217 /// };
3218 
3219 static void WriteInt32ToBuffer(uint32_t Value, SmallVectorImpl<char> &Buffer,
3220                                uint32_t &Position) {
3221   support::endian::write32le(&Buffer[Position], Value);
3222   Position += 4;
3223 }
3224 
3225 static void EmitDarwinBCHeaderAndTrailer(SmallVectorImpl<char> &Buffer,
3226                                          const Triple &TT) {
3227   unsigned CPUType = ~0U;
3228 
3229   // Match x86_64-*, i[3-9]86-*, powerpc-*, powerpc64-*, arm-*, thumb-*,
3230   // armv[0-9]-*, thumbv[0-9]-*, armv5te-*, or armv6t2-*. The CPUType is a magic
3231   // number from /usr/include/mach/machine.h.  It is ok to reproduce the
3232   // specific constants here because they are implicitly part of the Darwin ABI.
3233   enum {
3234     DARWIN_CPU_ARCH_ABI64      = 0x01000000,
3235     DARWIN_CPU_TYPE_X86        = 7,
3236     DARWIN_CPU_TYPE_ARM        = 12,
3237     DARWIN_CPU_TYPE_POWERPC    = 18
3238   };
3239 
3240   Triple::ArchType Arch = TT.getArch();
3241   if (Arch == Triple::x86_64)
3242     CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64;
3243   else if (Arch == Triple::x86)
3244     CPUType = DARWIN_CPU_TYPE_X86;
3245   else if (Arch == Triple::ppc)
3246     CPUType = DARWIN_CPU_TYPE_POWERPC;
3247   else if (Arch == Triple::ppc64)
3248     CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64;
3249   else if (Arch == Triple::arm || Arch == Triple::thumb)
3250     CPUType = DARWIN_CPU_TYPE_ARM;
3251 
3252   // Traditional Bitcode starts after header.
3253   assert(Buffer.size() >= BWH_HeaderSize &&
3254          "Expected header size to be reserved");
3255   unsigned BCOffset = BWH_HeaderSize;
3256   unsigned BCSize = Buffer.size() - BWH_HeaderSize;
3257 
3258   // Write the magic and version.
3259   unsigned Position = 0;
3260   WriteInt32ToBuffer(0x0B17C0DE , Buffer, Position);
3261   WriteInt32ToBuffer(0          , Buffer, Position); // Version.
3262   WriteInt32ToBuffer(BCOffset   , Buffer, Position);
3263   WriteInt32ToBuffer(BCSize     , Buffer, Position);
3264   WriteInt32ToBuffer(CPUType    , Buffer, Position);
3265 
3266   // If the file is not a multiple of 16 bytes, insert dummy padding.
3267   while (Buffer.size() & 15)
3268     Buffer.push_back(0);
3269 }
3270 
3271 /// Helper to write the header common to all bitcode files.
3272 static void WriteBitcodeHeader(BitstreamWriter &Stream) {
3273   // Emit the file header.
3274   Stream.Emit((unsigned)'B', 8);
3275   Stream.Emit((unsigned)'C', 8);
3276   Stream.Emit(0x0, 4);
3277   Stream.Emit(0xC, 4);
3278   Stream.Emit(0xE, 4);
3279   Stream.Emit(0xD, 4);
3280 }
3281 
3282 /// WriteBitcodeToFile - Write the specified module to the specified output
3283 /// stream.
3284 void llvm::WriteBitcodeToFile(const Module *M, raw_ostream &Out,
3285                               bool ShouldPreserveUseListOrder,
3286                               const ModuleSummaryIndex *Index,
3287                               bool GenerateHash) {
3288   SmallVector<char, 0> Buffer;
3289   Buffer.reserve(256*1024);
3290 
3291   // If this is darwin or another generic macho target, reserve space for the
3292   // header.
3293   Triple TT(M->getTargetTriple());
3294   if (TT.isOSDarwin() || TT.isOSBinFormatMachO())
3295     Buffer.insert(Buffer.begin(), BWH_HeaderSize, 0);
3296 
3297   // Emit the module into the buffer.
3298   {
3299     BitstreamWriter Stream(Buffer);
3300     // Save the start bit of the actual bitcode, in case there is space
3301     // saved at the start for the darwin header above. The reader stream
3302     // will start at the bitcode, and we need the offset of the VST
3303     // to line up.
3304     uint64_t BitcodeStartBit = Stream.GetCurrentBitNo();
3305 
3306     // Emit the file header.
3307     WriteBitcodeHeader(Stream);
3308 
3309     WriteIdentificationBlock(M, Stream);
3310 
3311     // Emit the module.
3312     WriteModule(M, Stream, ShouldPreserveUseListOrder, BitcodeStartBit, Index,
3313                 GenerateHash, Buffer);
3314   }
3315 
3316   if (TT.isOSDarwin() || TT.isOSBinFormatMachO())
3317     EmitDarwinBCHeaderAndTrailer(Buffer, TT);
3318 
3319   // Write the generated bitstream to "Out".
3320   Out.write((char*)&Buffer.front(), Buffer.size());
3321 }
3322 
3323 // Write the specified module summary index to the given raw output stream,
3324 // where it will be written in a new bitcode block. This is used when
3325 // writing the combined index file for ThinLTO.
3326 void llvm::WriteIndexToFile(const ModuleSummaryIndex &Index, raw_ostream &Out) {
3327   SmallVector<char, 0> Buffer;
3328   Buffer.reserve(256 * 1024);
3329 
3330   BitstreamWriter Stream(Buffer);
3331 
3332   // Emit the bitcode header.
3333   WriteBitcodeHeader(Stream);
3334 
3335   Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
3336 
3337   SmallVector<unsigned, 1> Vals;
3338   unsigned CurVersion = 1;
3339   Vals.push_back(CurVersion);
3340   Stream.EmitRecord(bitc::MODULE_CODE_VERSION, Vals);
3341 
3342   // If we have a VST, write the VSTOFFSET record placeholder and record
3343   // its offset.
3344   uint64_t VSTOffsetPlaceholder = WriteValueSymbolTableForwardDecl(Stream);
3345 
3346   // Write the module paths in the combined index.
3347   WriteModStrings(Index, Stream);
3348 
3349   // Assign unique value ids to all functions in the index for use
3350   // in writing out the call graph edges. Save the mapping from GUID
3351   // to the new global value id to use when writing those edges, which
3352   // are currently saved in the index in terms of GUID.
3353   std::map<GlobalValue::GUID, unsigned> GUIDToValueIdMap;
3354   unsigned GlobalValueId = 0;
3355   for (auto &II : Index)
3356     GUIDToValueIdMap[II.first] = ++GlobalValueId;
3357 
3358   // Write the summary combined index records.
3359   WriteCombinedGlobalValueSummary(Index, Stream, GUIDToValueIdMap,
3360                                   GlobalValueId);
3361 
3362   // Need a special VST writer for the combined index (we don't have a
3363   // real VST and real values when this is invoked).
3364   WriteCombinedValueSymbolTable(Index, Stream, GUIDToValueIdMap,
3365                                 VSTOffsetPlaceholder);
3366 
3367   Stream.ExitBlock();
3368 
3369   Out.write((char *)&Buffer.front(), Buffer.size());
3370 }
3371