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