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