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