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