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