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