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