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