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