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