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