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