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