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