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