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