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