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