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