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