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