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