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