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