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