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