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