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