xref: /llvm-project/llvm/lib/Bitcode/Writer/BitcodeWriter.cpp (revision dde589389fcb8b5098f7a47f1b781b27d29a0cac)
1 //===- Bitcode/Writer/BitcodeWriter.cpp - Bitcode Writer ------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // Bitcode writer implementation.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm/Bitcode/BitcodeWriter.h"
14 #include "ValueEnumerator.h"
15 #include "llvm/ADT/APFloat.h"
16 #include "llvm/ADT/APInt.h"
17 #include "llvm/ADT/ArrayRef.h"
18 #include "llvm/ADT/DenseMap.h"
19 #include "llvm/ADT/None.h"
20 #include "llvm/ADT/Optional.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/ADT/SmallString.h"
23 #include "llvm/ADT/SmallVector.h"
24 #include "llvm/ADT/StringMap.h"
25 #include "llvm/ADT/StringRef.h"
26 #include "llvm/ADT/Triple.h"
27 #include "llvm/Bitstream/BitCodes.h"
28 #include "llvm/Bitstream/BitstreamWriter.h"
29 #include "llvm/Bitcode/LLVMBitCodes.h"
30 #include "llvm/Config/llvm-config.h"
31 #include "llvm/IR/Attributes.h"
32 #include "llvm/IR/BasicBlock.h"
33 #include "llvm/IR/CallSite.h"
34 #include "llvm/IR/Comdat.h"
35 #include "llvm/IR/Constant.h"
36 #include "llvm/IR/Constants.h"
37 #include "llvm/IR/DebugInfoMetadata.h"
38 #include "llvm/IR/DebugLoc.h"
39 #include "llvm/IR/DerivedTypes.h"
40 #include "llvm/IR/Function.h"
41 #include "llvm/IR/GlobalAlias.h"
42 #include "llvm/IR/GlobalIFunc.h"
43 #include "llvm/IR/GlobalObject.h"
44 #include "llvm/IR/GlobalValue.h"
45 #include "llvm/IR/GlobalVariable.h"
46 #include "llvm/IR/InlineAsm.h"
47 #include "llvm/IR/InstrTypes.h"
48 #include "llvm/IR/Instruction.h"
49 #include "llvm/IR/Instructions.h"
50 #include "llvm/IR/LLVMContext.h"
51 #include "llvm/IR/Metadata.h"
52 #include "llvm/IR/Module.h"
53 #include "llvm/IR/ModuleSummaryIndex.h"
54 #include "llvm/IR/Operator.h"
55 #include "llvm/IR/Type.h"
56 #include "llvm/IR/UseListOrder.h"
57 #include "llvm/IR/Value.h"
58 #include "llvm/IR/ValueSymbolTable.h"
59 #include "llvm/MC/StringTableBuilder.h"
60 #include "llvm/Object/IRSymtab.h"
61 #include "llvm/Support/AtomicOrdering.h"
62 #include "llvm/Support/Casting.h"
63 #include "llvm/Support/CommandLine.h"
64 #include "llvm/Support/Endian.h"
65 #include "llvm/Support/Error.h"
66 #include "llvm/Support/ErrorHandling.h"
67 #include "llvm/Support/MathExtras.h"
68 #include "llvm/Support/SHA1.h"
69 #include "llvm/Support/TargetRegistry.h"
70 #include "llvm/Support/raw_ostream.h"
71 #include <algorithm>
72 #include <cassert>
73 #include <cstddef>
74 #include <cstdint>
75 #include <iterator>
76 #include <map>
77 #include <memory>
78 #include <string>
79 #include <utility>
80 #include <vector>
81 
82 using namespace llvm;
83 
84 static cl::opt<unsigned>
85     IndexThreshold("bitcode-mdindex-threshold", cl::Hidden, cl::init(25),
86                    cl::desc("Number of metadatas above which we emit an index "
87                             "to enable lazy-loading"));
88 
89 static cl::opt<bool> WriteRelBFToSummary(
90     "write-relbf-to-summary", cl::Hidden, cl::init(false),
91     cl::desc("Write relative block frequency to function summary "));
92 
93 extern FunctionSummary::ForceSummaryHotnessType ForceSummaryEdgesCold;
94 
95 namespace {
96 
97 /// These are manifest constants used by the bitcode writer. They do not need to
98 /// be kept in sync with the reader, but need to be consistent within this file.
99 enum {
100   // VALUE_SYMTAB_BLOCK abbrev id's.
101   VST_ENTRY_8_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
102   VST_ENTRY_7_ABBREV,
103   VST_ENTRY_6_ABBREV,
104   VST_BBENTRY_6_ABBREV,
105 
106   // CONSTANTS_BLOCK abbrev id's.
107   CONSTANTS_SETTYPE_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
108   CONSTANTS_INTEGER_ABBREV,
109   CONSTANTS_CE_CAST_Abbrev,
110   CONSTANTS_NULL_Abbrev,
111 
112   // FUNCTION_BLOCK abbrev id's.
113   FUNCTION_INST_LOAD_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
114   FUNCTION_INST_UNOP_ABBREV,
115   FUNCTION_INST_UNOP_FLAGS_ABBREV,
116   FUNCTION_INST_BINOP_ABBREV,
117   FUNCTION_INST_BINOP_FLAGS_ABBREV,
118   FUNCTION_INST_CAST_ABBREV,
119   FUNCTION_INST_RET_VOID_ABBREV,
120   FUNCTION_INST_RET_VAL_ABBREV,
121   FUNCTION_INST_UNREACHABLE_ABBREV,
122   FUNCTION_INST_GEP_ABBREV,
123 };
124 
125 /// Abstract class to manage the bitcode writing, subclassed for each bitcode
126 /// file type.
127 class BitcodeWriterBase {
128 protected:
129   /// The stream created and owned by the client.
130   BitstreamWriter &Stream;
131 
132   StringTableBuilder &StrtabBuilder;
133 
134 public:
135   /// Constructs a BitcodeWriterBase object that writes to the provided
136   /// \p Stream.
137   BitcodeWriterBase(BitstreamWriter &Stream, StringTableBuilder &StrtabBuilder)
138       : Stream(Stream), StrtabBuilder(StrtabBuilder) {}
139 
140 protected:
141   void writeBitcodeHeader();
142   void writeModuleVersion();
143 };
144 
145 void BitcodeWriterBase::writeModuleVersion() {
146   // VERSION: [version#]
147   Stream.EmitRecord(bitc::MODULE_CODE_VERSION, ArrayRef<uint64_t>{2});
148 }
149 
150 /// Base class to manage the module bitcode writing, currently subclassed for
151 /// ModuleBitcodeWriter and ThinLinkBitcodeWriter.
152 class ModuleBitcodeWriterBase : public BitcodeWriterBase {
153 protected:
154   /// The Module to write to bitcode.
155   const Module &M;
156 
157   /// Enumerates ids for all values in the module.
158   ValueEnumerator VE;
159 
160   /// Optional per-module index to write for ThinLTO.
161   const ModuleSummaryIndex *Index;
162 
163   /// Map that holds the correspondence between GUIDs in the summary index,
164   /// that came from indirect call profiles, and a value id generated by this
165   /// class to use in the VST and summary block records.
166   std::map<GlobalValue::GUID, unsigned> GUIDToValueIdMap;
167 
168   /// Tracks the last value id recorded in the GUIDToValueMap.
169   unsigned GlobalValueId;
170 
171   /// Saves the offset of the VSTOffset record that must eventually be
172   /// backpatched with the offset of the actual VST.
173   uint64_t VSTOffsetPlaceholder = 0;
174 
175 public:
176   /// Constructs a ModuleBitcodeWriterBase object for the given Module,
177   /// writing to the provided \p Buffer.
178   ModuleBitcodeWriterBase(const Module &M, StringTableBuilder &StrtabBuilder,
179                           BitstreamWriter &Stream,
180                           bool ShouldPreserveUseListOrder,
181                           const ModuleSummaryIndex *Index)
182       : BitcodeWriterBase(Stream, StrtabBuilder), M(M),
183         VE(M, ShouldPreserveUseListOrder), Index(Index) {
184     // Assign ValueIds to any callee values in the index that came from
185     // indirect call profiles and were recorded as a GUID not a Value*
186     // (which would have been assigned an ID by the ValueEnumerator).
187     // The starting ValueId is just after the number of values in the
188     // ValueEnumerator, so that they can be emitted in the VST.
189     GlobalValueId = VE.getValues().size();
190     if (!Index)
191       return;
192     for (const auto &GUIDSummaryLists : *Index)
193       // Examine all summaries for this GUID.
194       for (auto &Summary : GUIDSummaryLists.second.SummaryList)
195         if (auto FS = dyn_cast<FunctionSummary>(Summary.get()))
196           // For each call in the function summary, see if the call
197           // is to a GUID (which means it is for an indirect call,
198           // otherwise we would have a Value for it). If so, synthesize
199           // a value id.
200           for (auto &CallEdge : FS->calls())
201             if (!CallEdge.first.haveGVs() || !CallEdge.first.getValue())
202               assignValueId(CallEdge.first.getGUID());
203   }
204 
205 protected:
206   void writePerModuleGlobalValueSummary();
207 
208 private:
209   void writePerModuleFunctionSummaryRecord(SmallVector<uint64_t, 64> &NameVals,
210                                            GlobalValueSummary *Summary,
211                                            unsigned ValueID,
212                                            unsigned FSCallsAbbrev,
213                                            unsigned FSCallsProfileAbbrev,
214                                            const Function &F);
215   void writeModuleLevelReferences(const GlobalVariable &V,
216                                   SmallVector<uint64_t, 64> &NameVals,
217                                   unsigned FSModRefsAbbrev,
218                                   unsigned FSModVTableRefsAbbrev);
219 
220   void assignValueId(GlobalValue::GUID ValGUID) {
221     GUIDToValueIdMap[ValGUID] = ++GlobalValueId;
222   }
223 
224   unsigned getValueId(GlobalValue::GUID ValGUID) {
225     const auto &VMI = GUIDToValueIdMap.find(ValGUID);
226     // Expect that any GUID value had a value Id assigned by an
227     // earlier call to assignValueId.
228     assert(VMI != GUIDToValueIdMap.end() &&
229            "GUID does not have assigned value Id");
230     return VMI->second;
231   }
232 
233   // Helper to get the valueId for the type of value recorded in VI.
234   unsigned getValueId(ValueInfo VI) {
235     if (!VI.haveGVs() || !VI.getValue())
236       return getValueId(VI.getGUID());
237     return VE.getValueID(VI.getValue());
238   }
239 
240   std::map<GlobalValue::GUID, unsigned> &valueIds() { return GUIDToValueIdMap; }
241 };
242 
243 /// Class to manage the bitcode writing for a module.
244 class ModuleBitcodeWriter : public ModuleBitcodeWriterBase {
245   /// Pointer to the buffer allocated by caller for bitcode writing.
246   const SmallVectorImpl<char> &Buffer;
247 
248   /// True if a module hash record should be written.
249   bool GenerateHash;
250 
251   /// If non-null, when GenerateHash is true, the resulting hash is written
252   /// into ModHash.
253   ModuleHash *ModHash;
254 
255   SHA1 Hasher;
256 
257   /// The start bit of the identification block.
258   uint64_t BitcodeStartBit;
259 
260 public:
261   /// Constructs a ModuleBitcodeWriter object for the given Module,
262   /// writing to the provided \p Buffer.
263   ModuleBitcodeWriter(const Module &M, SmallVectorImpl<char> &Buffer,
264                       StringTableBuilder &StrtabBuilder,
265                       BitstreamWriter &Stream, bool ShouldPreserveUseListOrder,
266                       const ModuleSummaryIndex *Index, bool GenerateHash,
267                       ModuleHash *ModHash = nullptr)
268       : ModuleBitcodeWriterBase(M, StrtabBuilder, Stream,
269                                 ShouldPreserveUseListOrder, Index),
270         Buffer(Buffer), GenerateHash(GenerateHash), ModHash(ModHash),
271         BitcodeStartBit(Stream.GetCurrentBitNo()) {}
272 
273   /// Emit the current module to the bitstream.
274   void write();
275 
276 private:
277   uint64_t bitcodeStartBit() { return BitcodeStartBit; }
278 
279   size_t addToStrtab(StringRef Str);
280 
281   void writeAttributeGroupTable();
282   void writeAttributeTable();
283   void writeTypeTable();
284   void writeComdats();
285   void writeValueSymbolTableForwardDecl();
286   void writeModuleInfo();
287   void writeValueAsMetadata(const ValueAsMetadata *MD,
288                             SmallVectorImpl<uint64_t> &Record);
289   void writeMDTuple(const MDTuple *N, SmallVectorImpl<uint64_t> &Record,
290                     unsigned Abbrev);
291   unsigned createDILocationAbbrev();
292   void writeDILocation(const DILocation *N, SmallVectorImpl<uint64_t> &Record,
293                        unsigned &Abbrev);
294   unsigned createGenericDINodeAbbrev();
295   void writeGenericDINode(const GenericDINode *N,
296                           SmallVectorImpl<uint64_t> &Record, unsigned &Abbrev);
297   void writeDISubrange(const DISubrange *N, SmallVectorImpl<uint64_t> &Record,
298                        unsigned Abbrev);
299   void writeDIEnumerator(const DIEnumerator *N,
300                          SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
301   void writeDIBasicType(const DIBasicType *N, SmallVectorImpl<uint64_t> &Record,
302                         unsigned Abbrev);
303   void writeDIDerivedType(const DIDerivedType *N,
304                           SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
305   void writeDICompositeType(const DICompositeType *N,
306                             SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
307   void writeDISubroutineType(const DISubroutineType *N,
308                              SmallVectorImpl<uint64_t> &Record,
309                              unsigned Abbrev);
310   void writeDIFile(const DIFile *N, SmallVectorImpl<uint64_t> &Record,
311                    unsigned Abbrev);
312   void writeDICompileUnit(const DICompileUnit *N,
313                           SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
314   void writeDISubprogram(const DISubprogram *N,
315                          SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
316   void writeDILexicalBlock(const DILexicalBlock *N,
317                            SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
318   void writeDILexicalBlockFile(const DILexicalBlockFile *N,
319                                SmallVectorImpl<uint64_t> &Record,
320                                unsigned Abbrev);
321   void writeDICommonBlock(const DICommonBlock *N,
322                           SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
323   void writeDINamespace(const DINamespace *N, SmallVectorImpl<uint64_t> &Record,
324                         unsigned Abbrev);
325   void writeDIMacro(const DIMacro *N, SmallVectorImpl<uint64_t> &Record,
326                     unsigned Abbrev);
327   void writeDIMacroFile(const DIMacroFile *N, SmallVectorImpl<uint64_t> &Record,
328                         unsigned Abbrev);
329   void writeDIModule(const DIModule *N, SmallVectorImpl<uint64_t> &Record,
330                      unsigned Abbrev);
331   void writeDITemplateTypeParameter(const DITemplateTypeParameter *N,
332                                     SmallVectorImpl<uint64_t> &Record,
333                                     unsigned Abbrev);
334   void writeDITemplateValueParameter(const DITemplateValueParameter *N,
335                                      SmallVectorImpl<uint64_t> &Record,
336                                      unsigned Abbrev);
337   void writeDIGlobalVariable(const DIGlobalVariable *N,
338                              SmallVectorImpl<uint64_t> &Record,
339                              unsigned Abbrev);
340   void writeDILocalVariable(const DILocalVariable *N,
341                             SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
342   void writeDILabel(const DILabel *N,
343                     SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
344   void writeDIExpression(const DIExpression *N,
345                          SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
346   void writeDIGlobalVariableExpression(const DIGlobalVariableExpression *N,
347                                        SmallVectorImpl<uint64_t> &Record,
348                                        unsigned Abbrev);
349   void writeDIObjCProperty(const DIObjCProperty *N,
350                            SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
351   void writeDIImportedEntity(const DIImportedEntity *N,
352                              SmallVectorImpl<uint64_t> &Record,
353                              unsigned Abbrev);
354   unsigned createNamedMetadataAbbrev();
355   void writeNamedMetadata(SmallVectorImpl<uint64_t> &Record);
356   unsigned createMetadataStringsAbbrev();
357   void writeMetadataStrings(ArrayRef<const Metadata *> Strings,
358                             SmallVectorImpl<uint64_t> &Record);
359   void writeMetadataRecords(ArrayRef<const Metadata *> MDs,
360                             SmallVectorImpl<uint64_t> &Record,
361                             std::vector<unsigned> *MDAbbrevs = nullptr,
362                             std::vector<uint64_t> *IndexPos = nullptr);
363   void writeModuleMetadata();
364   void writeFunctionMetadata(const Function &F);
365   void writeFunctionMetadataAttachment(const Function &F);
366   void writeGlobalVariableMetadataAttachment(const GlobalVariable &GV);
367   void pushGlobalMetadataAttachment(SmallVectorImpl<uint64_t> &Record,
368                                     const GlobalObject &GO);
369   void writeModuleMetadataKinds();
370   void writeOperandBundleTags();
371   void writeSyncScopeNames();
372   void writeConstants(unsigned FirstVal, unsigned LastVal, bool isGlobal);
373   void writeModuleConstants();
374   bool pushValueAndType(const Value *V, unsigned InstID,
375                         SmallVectorImpl<unsigned> &Vals);
376   void writeOperandBundles(ImmutableCallSite CS, unsigned InstID);
377   void pushValue(const Value *V, unsigned InstID,
378                  SmallVectorImpl<unsigned> &Vals);
379   void pushValueSigned(const Value *V, unsigned InstID,
380                        SmallVectorImpl<uint64_t> &Vals);
381   void writeInstruction(const Instruction &I, unsigned InstID,
382                         SmallVectorImpl<unsigned> &Vals);
383   void writeFunctionLevelValueSymbolTable(const ValueSymbolTable &VST);
384   void writeGlobalValueSymbolTable(
385       DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex);
386   void writeUseList(UseListOrder &&Order);
387   void writeUseListBlock(const Function *F);
388   void
389   writeFunction(const Function &F,
390                 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex);
391   void writeBlockInfo();
392   void writeModuleHash(size_t BlockStartPos);
393 
394   unsigned getEncodedSyncScopeID(SyncScope::ID SSID) {
395     return unsigned(SSID);
396   }
397 };
398 
399 /// Class to manage the bitcode writing for a combined index.
400 class IndexBitcodeWriter : public BitcodeWriterBase {
401   /// The combined index to write to bitcode.
402   const ModuleSummaryIndex &Index;
403 
404   /// When writing a subset of the index for distributed backends, client
405   /// provides a map of modules to the corresponding GUIDs/summaries to write.
406   const std::map<std::string, GVSummaryMapTy> *ModuleToSummariesForIndex;
407 
408   /// Map that holds the correspondence between the GUID used in the combined
409   /// index and a value id generated by this class to use in references.
410   std::map<GlobalValue::GUID, unsigned> GUIDToValueIdMap;
411 
412   /// Tracks the last value id recorded in the GUIDToValueMap.
413   unsigned GlobalValueId = 0;
414 
415 public:
416   /// Constructs a IndexBitcodeWriter object for the given combined index,
417   /// writing to the provided \p Buffer. When writing a subset of the index
418   /// for a distributed backend, provide a \p ModuleToSummariesForIndex map.
419   IndexBitcodeWriter(BitstreamWriter &Stream, StringTableBuilder &StrtabBuilder,
420                      const ModuleSummaryIndex &Index,
421                      const std::map<std::string, GVSummaryMapTy>
422                          *ModuleToSummariesForIndex = nullptr)
423       : BitcodeWriterBase(Stream, StrtabBuilder), Index(Index),
424         ModuleToSummariesForIndex(ModuleToSummariesForIndex) {
425     // Assign unique value ids to all summaries to be written, for use
426     // in writing out the call graph edges. Save the mapping from GUID
427     // to the new global value id to use when writing those edges, which
428     // are currently saved in the index in terms of GUID.
429     forEachSummary([&](GVInfo I, bool) {
430       GUIDToValueIdMap[I.first] = ++GlobalValueId;
431     });
432   }
433 
434   /// The below iterator returns the GUID and associated summary.
435   using GVInfo = std::pair<GlobalValue::GUID, GlobalValueSummary *>;
436 
437   /// Calls the callback for each value GUID and summary to be written to
438   /// bitcode. This hides the details of whether they are being pulled from the
439   /// entire index or just those in a provided ModuleToSummariesForIndex map.
440   template<typename Functor>
441   void forEachSummary(Functor Callback) {
442     if (ModuleToSummariesForIndex) {
443       for (auto &M : *ModuleToSummariesForIndex)
444         for (auto &Summary : M.second) {
445           Callback(Summary, false);
446           // Ensure aliasee is handled, e.g. for assigning a valueId,
447           // even if we are not importing the aliasee directly (the
448           // imported alias will contain a copy of aliasee).
449           if (auto *AS = dyn_cast<AliasSummary>(Summary.getSecond()))
450             Callback({AS->getAliaseeGUID(), &AS->getAliasee()}, true);
451         }
452     } else {
453       for (auto &Summaries : Index)
454         for (auto &Summary : Summaries.second.SummaryList)
455           Callback({Summaries.first, Summary.get()}, false);
456     }
457   }
458 
459   /// Calls the callback for each entry in the modulePaths StringMap that
460   /// should be written to the module path string table. This hides the details
461   /// of whether they are being pulled from the entire index or just those in a
462   /// provided ModuleToSummariesForIndex map.
463   template <typename Functor> void forEachModule(Functor Callback) {
464     if (ModuleToSummariesForIndex) {
465       for (const auto &M : *ModuleToSummariesForIndex) {
466         const auto &MPI = Index.modulePaths().find(M.first);
467         if (MPI == Index.modulePaths().end()) {
468           // This should only happen if the bitcode file was empty, in which
469           // case we shouldn't be importing (the ModuleToSummariesForIndex
470           // would only include the module we are writing and index for).
471           assert(ModuleToSummariesForIndex->size() == 1);
472           continue;
473         }
474         Callback(*MPI);
475       }
476     } else {
477       for (const auto &MPSE : Index.modulePaths())
478         Callback(MPSE);
479     }
480   }
481 
482   /// Main entry point for writing a combined index to bitcode.
483   void write();
484 
485 private:
486   void writeModStrings();
487   void writeCombinedGlobalValueSummary();
488 
489   Optional<unsigned> getValueId(GlobalValue::GUID ValGUID) {
490     auto VMI = GUIDToValueIdMap.find(ValGUID);
491     if (VMI == GUIDToValueIdMap.end())
492       return None;
493     return VMI->second;
494   }
495 
496   std::map<GlobalValue::GUID, unsigned> &valueIds() { return GUIDToValueIdMap; }
497 };
498 
499 } // end anonymous namespace
500 
501 static unsigned getEncodedCastOpcode(unsigned Opcode) {
502   switch (Opcode) {
503   default: llvm_unreachable("Unknown cast instruction!");
504   case Instruction::Trunc   : return bitc::CAST_TRUNC;
505   case Instruction::ZExt    : return bitc::CAST_ZEXT;
506   case Instruction::SExt    : return bitc::CAST_SEXT;
507   case Instruction::FPToUI  : return bitc::CAST_FPTOUI;
508   case Instruction::FPToSI  : return bitc::CAST_FPTOSI;
509   case Instruction::UIToFP  : return bitc::CAST_UITOFP;
510   case Instruction::SIToFP  : return bitc::CAST_SITOFP;
511   case Instruction::FPTrunc : return bitc::CAST_FPTRUNC;
512   case Instruction::FPExt   : return bitc::CAST_FPEXT;
513   case Instruction::PtrToInt: return bitc::CAST_PTRTOINT;
514   case Instruction::IntToPtr: return bitc::CAST_INTTOPTR;
515   case Instruction::BitCast : return bitc::CAST_BITCAST;
516   case Instruction::AddrSpaceCast: return bitc::CAST_ADDRSPACECAST;
517   }
518 }
519 
520 static unsigned getEncodedUnaryOpcode(unsigned Opcode) {
521   switch (Opcode) {
522   default: llvm_unreachable("Unknown binary instruction!");
523   case Instruction::FNeg: return bitc::UNOP_FNEG;
524   case Instruction::Freeze: return bitc::UNOP_FREEZE;
525   }
526 }
527 
528 static unsigned getEncodedBinaryOpcode(unsigned Opcode) {
529   switch (Opcode) {
530   default: llvm_unreachable("Unknown binary instruction!");
531   case Instruction::Add:
532   case Instruction::FAdd: return bitc::BINOP_ADD;
533   case Instruction::Sub:
534   case Instruction::FSub: return bitc::BINOP_SUB;
535   case Instruction::Mul:
536   case Instruction::FMul: return bitc::BINOP_MUL;
537   case Instruction::UDiv: return bitc::BINOP_UDIV;
538   case Instruction::FDiv:
539   case Instruction::SDiv: return bitc::BINOP_SDIV;
540   case Instruction::URem: return bitc::BINOP_UREM;
541   case Instruction::FRem:
542   case Instruction::SRem: return bitc::BINOP_SREM;
543   case Instruction::Shl:  return bitc::BINOP_SHL;
544   case Instruction::LShr: return bitc::BINOP_LSHR;
545   case Instruction::AShr: return bitc::BINOP_ASHR;
546   case Instruction::And:  return bitc::BINOP_AND;
547   case Instruction::Or:   return bitc::BINOP_OR;
548   case Instruction::Xor:  return bitc::BINOP_XOR;
549   }
550 }
551 
552 static unsigned getEncodedRMWOperation(AtomicRMWInst::BinOp Op) {
553   switch (Op) {
554   default: llvm_unreachable("Unknown RMW operation!");
555   case AtomicRMWInst::Xchg: return bitc::RMW_XCHG;
556   case AtomicRMWInst::Add: return bitc::RMW_ADD;
557   case AtomicRMWInst::Sub: return bitc::RMW_SUB;
558   case AtomicRMWInst::And: return bitc::RMW_AND;
559   case AtomicRMWInst::Nand: return bitc::RMW_NAND;
560   case AtomicRMWInst::Or: return bitc::RMW_OR;
561   case AtomicRMWInst::Xor: return bitc::RMW_XOR;
562   case AtomicRMWInst::Max: return bitc::RMW_MAX;
563   case AtomicRMWInst::Min: return bitc::RMW_MIN;
564   case AtomicRMWInst::UMax: return bitc::RMW_UMAX;
565   case AtomicRMWInst::UMin: return bitc::RMW_UMIN;
566   case AtomicRMWInst::FAdd: return bitc::RMW_FADD;
567   case AtomicRMWInst::FSub: return bitc::RMW_FSUB;
568   }
569 }
570 
571 static unsigned getEncodedOrdering(AtomicOrdering Ordering) {
572   switch (Ordering) {
573   case AtomicOrdering::NotAtomic: return bitc::ORDERING_NOTATOMIC;
574   case AtomicOrdering::Unordered: return bitc::ORDERING_UNORDERED;
575   case AtomicOrdering::Monotonic: return bitc::ORDERING_MONOTONIC;
576   case AtomicOrdering::Acquire: return bitc::ORDERING_ACQUIRE;
577   case AtomicOrdering::Release: return bitc::ORDERING_RELEASE;
578   case AtomicOrdering::AcquireRelease: return bitc::ORDERING_ACQREL;
579   case AtomicOrdering::SequentiallyConsistent: return bitc::ORDERING_SEQCST;
580   }
581   llvm_unreachable("Invalid ordering");
582 }
583 
584 static void writeStringRecord(BitstreamWriter &Stream, unsigned Code,
585                               StringRef Str, unsigned AbbrevToUse) {
586   SmallVector<unsigned, 64> Vals;
587 
588   // Code: [strchar x N]
589   for (unsigned i = 0, e = Str.size(); i != e; ++i) {
590     if (AbbrevToUse && !BitCodeAbbrevOp::isChar6(Str[i]))
591       AbbrevToUse = 0;
592     Vals.push_back(Str[i]);
593   }
594 
595   // Emit the finished record.
596   Stream.EmitRecord(Code, Vals, AbbrevToUse);
597 }
598 
599 static uint64_t getAttrKindEncoding(Attribute::AttrKind Kind) {
600   switch (Kind) {
601   case Attribute::Alignment:
602     return bitc::ATTR_KIND_ALIGNMENT;
603   case Attribute::AllocSize:
604     return bitc::ATTR_KIND_ALLOC_SIZE;
605   case Attribute::AlwaysInline:
606     return bitc::ATTR_KIND_ALWAYS_INLINE;
607   case Attribute::ArgMemOnly:
608     return bitc::ATTR_KIND_ARGMEMONLY;
609   case Attribute::Builtin:
610     return bitc::ATTR_KIND_BUILTIN;
611   case Attribute::ByVal:
612     return bitc::ATTR_KIND_BY_VAL;
613   case Attribute::Convergent:
614     return bitc::ATTR_KIND_CONVERGENT;
615   case Attribute::InAlloca:
616     return bitc::ATTR_KIND_IN_ALLOCA;
617   case Attribute::Cold:
618     return bitc::ATTR_KIND_COLD;
619   case Attribute::InaccessibleMemOnly:
620     return bitc::ATTR_KIND_INACCESSIBLEMEM_ONLY;
621   case Attribute::InaccessibleMemOrArgMemOnly:
622     return bitc::ATTR_KIND_INACCESSIBLEMEM_OR_ARGMEMONLY;
623   case Attribute::InlineHint:
624     return bitc::ATTR_KIND_INLINE_HINT;
625   case Attribute::InReg:
626     return bitc::ATTR_KIND_IN_REG;
627   case Attribute::JumpTable:
628     return bitc::ATTR_KIND_JUMP_TABLE;
629   case Attribute::MinSize:
630     return bitc::ATTR_KIND_MIN_SIZE;
631   case Attribute::Naked:
632     return bitc::ATTR_KIND_NAKED;
633   case Attribute::Nest:
634     return bitc::ATTR_KIND_NEST;
635   case Attribute::NoAlias:
636     return bitc::ATTR_KIND_NO_ALIAS;
637   case Attribute::NoBuiltin:
638     return bitc::ATTR_KIND_NO_BUILTIN;
639   case Attribute::NoCapture:
640     return bitc::ATTR_KIND_NO_CAPTURE;
641   case Attribute::NoDuplicate:
642     return bitc::ATTR_KIND_NO_DUPLICATE;
643   case Attribute::NoFree:
644     return bitc::ATTR_KIND_NOFREE;
645   case Attribute::NoImplicitFloat:
646     return bitc::ATTR_KIND_NO_IMPLICIT_FLOAT;
647   case Attribute::NoInline:
648     return bitc::ATTR_KIND_NO_INLINE;
649   case Attribute::NoRecurse:
650     return bitc::ATTR_KIND_NO_RECURSE;
651   case Attribute::NonLazyBind:
652     return bitc::ATTR_KIND_NON_LAZY_BIND;
653   case Attribute::NonNull:
654     return bitc::ATTR_KIND_NON_NULL;
655   case Attribute::Dereferenceable:
656     return bitc::ATTR_KIND_DEREFERENCEABLE;
657   case Attribute::DereferenceableOrNull:
658     return bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL;
659   case Attribute::NoRedZone:
660     return bitc::ATTR_KIND_NO_RED_ZONE;
661   case Attribute::NoReturn:
662     return bitc::ATTR_KIND_NO_RETURN;
663   case Attribute::NoSync:
664     return bitc::ATTR_KIND_NOSYNC;
665   case Attribute::NoCfCheck:
666     return bitc::ATTR_KIND_NOCF_CHECK;
667   case Attribute::NoUnwind:
668     return bitc::ATTR_KIND_NO_UNWIND;
669   case Attribute::OptForFuzzing:
670     return bitc::ATTR_KIND_OPT_FOR_FUZZING;
671   case Attribute::OptimizeForSize:
672     return bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE;
673   case Attribute::OptimizeNone:
674     return bitc::ATTR_KIND_OPTIMIZE_NONE;
675   case Attribute::ReadNone:
676     return bitc::ATTR_KIND_READ_NONE;
677   case Attribute::ReadOnly:
678     return bitc::ATTR_KIND_READ_ONLY;
679   case Attribute::Returned:
680     return bitc::ATTR_KIND_RETURNED;
681   case Attribute::ReturnsTwice:
682     return bitc::ATTR_KIND_RETURNS_TWICE;
683   case Attribute::SExt:
684     return bitc::ATTR_KIND_S_EXT;
685   case Attribute::Speculatable:
686     return bitc::ATTR_KIND_SPECULATABLE;
687   case Attribute::StackAlignment:
688     return bitc::ATTR_KIND_STACK_ALIGNMENT;
689   case Attribute::StackProtect:
690     return bitc::ATTR_KIND_STACK_PROTECT;
691   case Attribute::StackProtectReq:
692     return bitc::ATTR_KIND_STACK_PROTECT_REQ;
693   case Attribute::StackProtectStrong:
694     return bitc::ATTR_KIND_STACK_PROTECT_STRONG;
695   case Attribute::SafeStack:
696     return bitc::ATTR_KIND_SAFESTACK;
697   case Attribute::ShadowCallStack:
698     return bitc::ATTR_KIND_SHADOWCALLSTACK;
699   case Attribute::StrictFP:
700     return bitc::ATTR_KIND_STRICT_FP;
701   case Attribute::StructRet:
702     return bitc::ATTR_KIND_STRUCT_RET;
703   case Attribute::SanitizeAddress:
704     return bitc::ATTR_KIND_SANITIZE_ADDRESS;
705   case Attribute::SanitizeHWAddress:
706     return bitc::ATTR_KIND_SANITIZE_HWADDRESS;
707   case Attribute::SanitizeThread:
708     return bitc::ATTR_KIND_SANITIZE_THREAD;
709   case Attribute::SanitizeMemory:
710     return bitc::ATTR_KIND_SANITIZE_MEMORY;
711   case Attribute::SpeculativeLoadHardening:
712     return bitc::ATTR_KIND_SPECULATIVE_LOAD_HARDENING;
713   case Attribute::SwiftError:
714     return bitc::ATTR_KIND_SWIFT_ERROR;
715   case Attribute::SwiftSelf:
716     return bitc::ATTR_KIND_SWIFT_SELF;
717   case Attribute::UWTable:
718     return bitc::ATTR_KIND_UW_TABLE;
719   case Attribute::WillReturn:
720     return bitc::ATTR_KIND_WILLRETURN;
721   case Attribute::WriteOnly:
722     return bitc::ATTR_KIND_WRITEONLY;
723   case Attribute::ZExt:
724     return bitc::ATTR_KIND_Z_EXT;
725   case Attribute::ImmArg:
726     return bitc::ATTR_KIND_IMMARG;
727   case Attribute::SanitizeMemTag:
728     return bitc::ATTR_KIND_SANITIZE_MEMTAG;
729   case Attribute::EndAttrKinds:
730     llvm_unreachable("Can not encode end-attribute kinds marker.");
731   case Attribute::None:
732     llvm_unreachable("Can not encode none-attribute.");
733   }
734 
735   llvm_unreachable("Trying to encode unknown attribute");
736 }
737 
738 void ModuleBitcodeWriter::writeAttributeGroupTable() {
739   const std::vector<ValueEnumerator::IndexAndAttrSet> &AttrGrps =
740       VE.getAttributeGroups();
741   if (AttrGrps.empty()) return;
742 
743   Stream.EnterSubblock(bitc::PARAMATTR_GROUP_BLOCK_ID, 3);
744 
745   SmallVector<uint64_t, 64> Record;
746   for (ValueEnumerator::IndexAndAttrSet Pair : AttrGrps) {
747     unsigned AttrListIndex = Pair.first;
748     AttributeSet AS = Pair.second;
749     Record.push_back(VE.getAttributeGroupID(Pair));
750     Record.push_back(AttrListIndex);
751 
752     for (Attribute Attr : AS) {
753       if (Attr.isEnumAttribute()) {
754         Record.push_back(0);
755         Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
756       } else if (Attr.isIntAttribute()) {
757         Record.push_back(1);
758         Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
759         Record.push_back(Attr.getValueAsInt());
760       } else if (Attr.isStringAttribute()) {
761         StringRef Kind = Attr.getKindAsString();
762         StringRef Val = Attr.getValueAsString();
763 
764         Record.push_back(Val.empty() ? 3 : 4);
765         Record.append(Kind.begin(), Kind.end());
766         Record.push_back(0);
767         if (!Val.empty()) {
768           Record.append(Val.begin(), Val.end());
769           Record.push_back(0);
770         }
771       } else {
772         assert(Attr.isTypeAttribute());
773         Type *Ty = Attr.getValueAsType();
774         Record.push_back(Ty ? 6 : 5);
775         Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
776         if (Ty)
777           Record.push_back(VE.getTypeID(Attr.getValueAsType()));
778       }
779     }
780 
781     Stream.EmitRecord(bitc::PARAMATTR_GRP_CODE_ENTRY, Record);
782     Record.clear();
783   }
784 
785   Stream.ExitBlock();
786 }
787 
788 void ModuleBitcodeWriter::writeAttributeTable() {
789   const std::vector<AttributeList> &Attrs = VE.getAttributeLists();
790   if (Attrs.empty()) return;
791 
792   Stream.EnterSubblock(bitc::PARAMATTR_BLOCK_ID, 3);
793 
794   SmallVector<uint64_t, 64> Record;
795   for (unsigned i = 0, e = Attrs.size(); i != e; ++i) {
796     AttributeList AL = Attrs[i];
797     for (unsigned i = AL.index_begin(), e = AL.index_end(); i != e; ++i) {
798       AttributeSet AS = AL.getAttributes(i);
799       if (AS.hasAttributes())
800         Record.push_back(VE.getAttributeGroupID({i, AS}));
801     }
802 
803     Stream.EmitRecord(bitc::PARAMATTR_CODE_ENTRY, Record);
804     Record.clear();
805   }
806 
807   Stream.ExitBlock();
808 }
809 
810 /// WriteTypeTable - Write out the type table for a module.
811 void ModuleBitcodeWriter::writeTypeTable() {
812   const ValueEnumerator::TypeList &TypeList = VE.getTypes();
813 
814   Stream.EnterSubblock(bitc::TYPE_BLOCK_ID_NEW, 4 /*count from # abbrevs */);
815   SmallVector<uint64_t, 64> TypeVals;
816 
817   uint64_t NumBits = VE.computeBitsRequiredForTypeIndicies();
818 
819   // Abbrev for TYPE_CODE_POINTER.
820   auto Abbv = std::make_shared<BitCodeAbbrev>();
821   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_POINTER));
822   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
823   Abbv->Add(BitCodeAbbrevOp(0));  // Addrspace = 0
824   unsigned PtrAbbrev = Stream.EmitAbbrev(std::move(Abbv));
825 
826   // Abbrev for TYPE_CODE_FUNCTION.
827   Abbv = std::make_shared<BitCodeAbbrev>();
828   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_FUNCTION));
829   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));  // isvararg
830   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
831   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
832   unsigned FunctionAbbrev = Stream.EmitAbbrev(std::move(Abbv));
833 
834   // Abbrev for TYPE_CODE_STRUCT_ANON.
835   Abbv = std::make_shared<BitCodeAbbrev>();
836   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_ANON));
837   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));  // ispacked
838   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
839   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
840   unsigned StructAnonAbbrev = Stream.EmitAbbrev(std::move(Abbv));
841 
842   // Abbrev for TYPE_CODE_STRUCT_NAME.
843   Abbv = std::make_shared<BitCodeAbbrev>();
844   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAME));
845   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
846   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
847   unsigned StructNameAbbrev = Stream.EmitAbbrev(std::move(Abbv));
848 
849   // Abbrev for TYPE_CODE_STRUCT_NAMED.
850   Abbv = std::make_shared<BitCodeAbbrev>();
851   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAMED));
852   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));  // ispacked
853   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
854   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
855   unsigned StructNamedAbbrev = Stream.EmitAbbrev(std::move(Abbv));
856 
857   // Abbrev for TYPE_CODE_ARRAY.
858   Abbv = std::make_shared<BitCodeAbbrev>();
859   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_ARRAY));
860   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // size
861   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
862   unsigned ArrayAbbrev = Stream.EmitAbbrev(std::move(Abbv));
863 
864   // Emit an entry count so the reader can reserve space.
865   TypeVals.push_back(TypeList.size());
866   Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals);
867   TypeVals.clear();
868 
869   // Loop over all of the types, emitting each in turn.
870   for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
871     Type *T = TypeList[i];
872     int AbbrevToUse = 0;
873     unsigned Code = 0;
874 
875     switch (T->getTypeID()) {
876     case Type::VoidTyID:      Code = bitc::TYPE_CODE_VOID;      break;
877     case Type::HalfTyID:      Code = bitc::TYPE_CODE_HALF;      break;
878     case Type::FloatTyID:     Code = bitc::TYPE_CODE_FLOAT;     break;
879     case Type::DoubleTyID:    Code = bitc::TYPE_CODE_DOUBLE;    break;
880     case Type::X86_FP80TyID:  Code = bitc::TYPE_CODE_X86_FP80;  break;
881     case Type::FP128TyID:     Code = bitc::TYPE_CODE_FP128;     break;
882     case Type::PPC_FP128TyID: Code = bitc::TYPE_CODE_PPC_FP128; break;
883     case Type::LabelTyID:     Code = bitc::TYPE_CODE_LABEL;     break;
884     case Type::MetadataTyID:  Code = bitc::TYPE_CODE_METADATA;  break;
885     case Type::X86_MMXTyID:   Code = bitc::TYPE_CODE_X86_MMX;   break;
886     case Type::TokenTyID:     Code = bitc::TYPE_CODE_TOKEN;     break;
887     case Type::IntegerTyID:
888       // INTEGER: [width]
889       Code = bitc::TYPE_CODE_INTEGER;
890       TypeVals.push_back(cast<IntegerType>(T)->getBitWidth());
891       break;
892     case Type::PointerTyID: {
893       PointerType *PTy = cast<PointerType>(T);
894       // POINTER: [pointee type, address space]
895       Code = bitc::TYPE_CODE_POINTER;
896       TypeVals.push_back(VE.getTypeID(PTy->getElementType()));
897       unsigned AddressSpace = PTy->getAddressSpace();
898       TypeVals.push_back(AddressSpace);
899       if (AddressSpace == 0) AbbrevToUse = PtrAbbrev;
900       break;
901     }
902     case Type::FunctionTyID: {
903       FunctionType *FT = cast<FunctionType>(T);
904       // FUNCTION: [isvararg, retty, paramty x N]
905       Code = bitc::TYPE_CODE_FUNCTION;
906       TypeVals.push_back(FT->isVarArg());
907       TypeVals.push_back(VE.getTypeID(FT->getReturnType()));
908       for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
909         TypeVals.push_back(VE.getTypeID(FT->getParamType(i)));
910       AbbrevToUse = FunctionAbbrev;
911       break;
912     }
913     case Type::StructTyID: {
914       StructType *ST = cast<StructType>(T);
915       // STRUCT: [ispacked, eltty x N]
916       TypeVals.push_back(ST->isPacked());
917       // Output all of the element types.
918       for (StructType::element_iterator I = ST->element_begin(),
919            E = ST->element_end(); I != E; ++I)
920         TypeVals.push_back(VE.getTypeID(*I));
921 
922       if (ST->isLiteral()) {
923         Code = bitc::TYPE_CODE_STRUCT_ANON;
924         AbbrevToUse = StructAnonAbbrev;
925       } else {
926         if (ST->isOpaque()) {
927           Code = bitc::TYPE_CODE_OPAQUE;
928         } else {
929           Code = bitc::TYPE_CODE_STRUCT_NAMED;
930           AbbrevToUse = StructNamedAbbrev;
931         }
932 
933         // Emit the name if it is present.
934         if (!ST->getName().empty())
935           writeStringRecord(Stream, bitc::TYPE_CODE_STRUCT_NAME, ST->getName(),
936                             StructNameAbbrev);
937       }
938       break;
939     }
940     case Type::ArrayTyID: {
941       ArrayType *AT = cast<ArrayType>(T);
942       // ARRAY: [numelts, eltty]
943       Code = bitc::TYPE_CODE_ARRAY;
944       TypeVals.push_back(AT->getNumElements());
945       TypeVals.push_back(VE.getTypeID(AT->getElementType()));
946       AbbrevToUse = ArrayAbbrev;
947       break;
948     }
949     case Type::VectorTyID: {
950       VectorType *VT = cast<VectorType>(T);
951       // VECTOR [numelts, eltty] or
952       //        [numelts, eltty, scalable]
953       Code = bitc::TYPE_CODE_VECTOR;
954       TypeVals.push_back(VT->getNumElements());
955       TypeVals.push_back(VE.getTypeID(VT->getElementType()));
956       if (VT->isScalable())
957         TypeVals.push_back(VT->isScalable());
958       break;
959     }
960     }
961 
962     // Emit the finished record.
963     Stream.EmitRecord(Code, TypeVals, AbbrevToUse);
964     TypeVals.clear();
965   }
966 
967   Stream.ExitBlock();
968 }
969 
970 static unsigned getEncodedLinkage(const GlobalValue::LinkageTypes Linkage) {
971   switch (Linkage) {
972   case GlobalValue::ExternalLinkage:
973     return 0;
974   case GlobalValue::WeakAnyLinkage:
975     return 16;
976   case GlobalValue::AppendingLinkage:
977     return 2;
978   case GlobalValue::InternalLinkage:
979     return 3;
980   case GlobalValue::LinkOnceAnyLinkage:
981     return 18;
982   case GlobalValue::ExternalWeakLinkage:
983     return 7;
984   case GlobalValue::CommonLinkage:
985     return 8;
986   case GlobalValue::PrivateLinkage:
987     return 9;
988   case GlobalValue::WeakODRLinkage:
989     return 17;
990   case GlobalValue::LinkOnceODRLinkage:
991     return 19;
992   case GlobalValue::AvailableExternallyLinkage:
993     return 12;
994   }
995   llvm_unreachable("Invalid linkage");
996 }
997 
998 static unsigned getEncodedLinkage(const GlobalValue &GV) {
999   return getEncodedLinkage(GV.getLinkage());
1000 }
1001 
1002 static uint64_t getEncodedFFlags(FunctionSummary::FFlags Flags) {
1003   uint64_t RawFlags = 0;
1004   RawFlags |= Flags.ReadNone;
1005   RawFlags |= (Flags.ReadOnly << 1);
1006   RawFlags |= (Flags.NoRecurse << 2);
1007   RawFlags |= (Flags.ReturnDoesNotAlias << 3);
1008   RawFlags |= (Flags.NoInline << 4);
1009   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 if (Instruction::isUnaryOp(CE->getOpcode())) {
2438           assert(CE->getNumOperands() == 1 && "Unknown constant expr!");
2439           Code = bitc::CST_CODE_CE_UNOP;
2440           Record.push_back(getEncodedUnaryOpcode(CE->getOpcode()));
2441           Record.push_back(VE.getValueID(C->getOperand(0)));
2442           uint64_t Flags = getOptimizationFlags(CE);
2443           if (Flags != 0) {
2444             assert(CE->getOpcode() == Instruction::FNeg);
2445             Record.push_back(Flags);
2446           }
2447           break;
2448         } else {
2449           assert(CE->getNumOperands() == 2 && "Unknown constant expr!");
2450           Code = bitc::CST_CODE_CE_BINOP;
2451           Record.push_back(getEncodedBinaryOpcode(CE->getOpcode()));
2452           Record.push_back(VE.getValueID(C->getOperand(0)));
2453           Record.push_back(VE.getValueID(C->getOperand(1)));
2454           uint64_t Flags = getOptimizationFlags(CE);
2455           if (Flags != 0)
2456             Record.push_back(Flags);
2457         }
2458         break;
2459       case Instruction::GetElementPtr: {
2460         Code = bitc::CST_CODE_CE_GEP;
2461         const auto *GO = cast<GEPOperator>(C);
2462         Record.push_back(VE.getTypeID(GO->getSourceElementType()));
2463         if (Optional<unsigned> Idx = GO->getInRangeIndex()) {
2464           Code = bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX;
2465           Record.push_back((*Idx << 1) | GO->isInBounds());
2466         } else if (GO->isInBounds())
2467           Code = bitc::CST_CODE_CE_INBOUNDS_GEP;
2468         for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
2469           Record.push_back(VE.getTypeID(C->getOperand(i)->getType()));
2470           Record.push_back(VE.getValueID(C->getOperand(i)));
2471         }
2472         break;
2473       }
2474       case Instruction::Select:
2475         Code = bitc::CST_CODE_CE_SELECT;
2476         Record.push_back(VE.getValueID(C->getOperand(0)));
2477         Record.push_back(VE.getValueID(C->getOperand(1)));
2478         Record.push_back(VE.getValueID(C->getOperand(2)));
2479         break;
2480       case Instruction::ExtractElement:
2481         Code = bitc::CST_CODE_CE_EXTRACTELT;
2482         Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2483         Record.push_back(VE.getValueID(C->getOperand(0)));
2484         Record.push_back(VE.getTypeID(C->getOperand(1)->getType()));
2485         Record.push_back(VE.getValueID(C->getOperand(1)));
2486         break;
2487       case Instruction::InsertElement:
2488         Code = bitc::CST_CODE_CE_INSERTELT;
2489         Record.push_back(VE.getValueID(C->getOperand(0)));
2490         Record.push_back(VE.getValueID(C->getOperand(1)));
2491         Record.push_back(VE.getTypeID(C->getOperand(2)->getType()));
2492         Record.push_back(VE.getValueID(C->getOperand(2)));
2493         break;
2494       case Instruction::ShuffleVector:
2495         // If the return type and argument types are the same, this is a
2496         // standard shufflevector instruction.  If the types are different,
2497         // then the shuffle is widening or truncating the input vectors, and
2498         // the argument type must also be encoded.
2499         if (C->getType() == C->getOperand(0)->getType()) {
2500           Code = bitc::CST_CODE_CE_SHUFFLEVEC;
2501         } else {
2502           Code = bitc::CST_CODE_CE_SHUFVEC_EX;
2503           Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2504         }
2505         Record.push_back(VE.getValueID(C->getOperand(0)));
2506         Record.push_back(VE.getValueID(C->getOperand(1)));
2507         Record.push_back(VE.getValueID(C->getOperand(2)));
2508         break;
2509       case Instruction::ICmp:
2510       case Instruction::FCmp:
2511         Code = bitc::CST_CODE_CE_CMP;
2512         Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2513         Record.push_back(VE.getValueID(C->getOperand(0)));
2514         Record.push_back(VE.getValueID(C->getOperand(1)));
2515         Record.push_back(CE->getPredicate());
2516         break;
2517       }
2518     } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) {
2519       Code = bitc::CST_CODE_BLOCKADDRESS;
2520       Record.push_back(VE.getTypeID(BA->getFunction()->getType()));
2521       Record.push_back(VE.getValueID(BA->getFunction()));
2522       Record.push_back(VE.getGlobalBasicBlockID(BA->getBasicBlock()));
2523     } else {
2524 #ifndef NDEBUG
2525       C->dump();
2526 #endif
2527       llvm_unreachable("Unknown constant!");
2528     }
2529     Stream.EmitRecord(Code, Record, AbbrevToUse);
2530     Record.clear();
2531   }
2532 
2533   Stream.ExitBlock();
2534 }
2535 
2536 void ModuleBitcodeWriter::writeModuleConstants() {
2537   const ValueEnumerator::ValueList &Vals = VE.getValues();
2538 
2539   // Find the first constant to emit, which is the first non-globalvalue value.
2540   // We know globalvalues have been emitted by WriteModuleInfo.
2541   for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
2542     if (!isa<GlobalValue>(Vals[i].first)) {
2543       writeConstants(i, Vals.size(), true);
2544       return;
2545     }
2546   }
2547 }
2548 
2549 /// pushValueAndType - The file has to encode both the value and type id for
2550 /// many values, because we need to know what type to create for forward
2551 /// references.  However, most operands are not forward references, so this type
2552 /// field is not needed.
2553 ///
2554 /// This function adds V's value ID to Vals.  If the value ID is higher than the
2555 /// instruction ID, then it is a forward reference, and it also includes the
2556 /// type ID.  The value ID that is written is encoded relative to the InstID.
2557 bool ModuleBitcodeWriter::pushValueAndType(const Value *V, unsigned InstID,
2558                                            SmallVectorImpl<unsigned> &Vals) {
2559   unsigned ValID = VE.getValueID(V);
2560   // Make encoding relative to the InstID.
2561   Vals.push_back(InstID - ValID);
2562   if (ValID >= InstID) {
2563     Vals.push_back(VE.getTypeID(V->getType()));
2564     return true;
2565   }
2566   return false;
2567 }
2568 
2569 void ModuleBitcodeWriter::writeOperandBundles(ImmutableCallSite CS,
2570                                               unsigned InstID) {
2571   SmallVector<unsigned, 64> Record;
2572   LLVMContext &C = CS.getInstruction()->getContext();
2573 
2574   for (unsigned i = 0, e = CS.getNumOperandBundles(); i != e; ++i) {
2575     const auto &Bundle = CS.getOperandBundleAt(i);
2576     Record.push_back(C.getOperandBundleTagID(Bundle.getTagName()));
2577 
2578     for (auto &Input : Bundle.Inputs)
2579       pushValueAndType(Input, InstID, Record);
2580 
2581     Stream.EmitRecord(bitc::FUNC_CODE_OPERAND_BUNDLE, Record);
2582     Record.clear();
2583   }
2584 }
2585 
2586 /// pushValue - Like pushValueAndType, but where the type of the value is
2587 /// omitted (perhaps it was already encoded in an earlier operand).
2588 void ModuleBitcodeWriter::pushValue(const Value *V, unsigned InstID,
2589                                     SmallVectorImpl<unsigned> &Vals) {
2590   unsigned ValID = VE.getValueID(V);
2591   Vals.push_back(InstID - ValID);
2592 }
2593 
2594 void ModuleBitcodeWriter::pushValueSigned(const Value *V, unsigned InstID,
2595                                           SmallVectorImpl<uint64_t> &Vals) {
2596   unsigned ValID = VE.getValueID(V);
2597   int64_t diff = ((int32_t)InstID - (int32_t)ValID);
2598   emitSignedInt64(Vals, diff);
2599 }
2600 
2601 /// WriteInstruction - Emit an instruction to the specified stream.
2602 void ModuleBitcodeWriter::writeInstruction(const Instruction &I,
2603                                            unsigned InstID,
2604                                            SmallVectorImpl<unsigned> &Vals) {
2605   unsigned Code = 0;
2606   unsigned AbbrevToUse = 0;
2607   VE.setInstructionID(&I);
2608   switch (I.getOpcode()) {
2609   default:
2610     if (Instruction::isCast(I.getOpcode())) {
2611       Code = bitc::FUNC_CODE_INST_CAST;
2612       if (!pushValueAndType(I.getOperand(0), InstID, Vals))
2613         AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
2614       Vals.push_back(VE.getTypeID(I.getType()));
2615       Vals.push_back(getEncodedCastOpcode(I.getOpcode()));
2616     } else if (isa<UnaryOperator>(I)) {
2617       Code = bitc::FUNC_CODE_INST_UNOP;
2618       if (!pushValueAndType(I.getOperand(0), InstID, Vals))
2619         AbbrevToUse = FUNCTION_INST_UNOP_ABBREV;
2620       Vals.push_back(getEncodedUnaryOpcode(I.getOpcode()));
2621       uint64_t Flags = getOptimizationFlags(&I);
2622       if (Flags != 0) {
2623         if (AbbrevToUse == FUNCTION_INST_UNOP_ABBREV)
2624           AbbrevToUse = FUNCTION_INST_UNOP_FLAGS_ABBREV;
2625         Vals.push_back(Flags);
2626       }
2627     } else {
2628       assert(isa<BinaryOperator>(I) && "Unknown instruction!");
2629       Code = bitc::FUNC_CODE_INST_BINOP;
2630       if (!pushValueAndType(I.getOperand(0), InstID, Vals))
2631         AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
2632       pushValue(I.getOperand(1), InstID, Vals);
2633       Vals.push_back(getEncodedBinaryOpcode(I.getOpcode()));
2634       uint64_t Flags = getOptimizationFlags(&I);
2635       if (Flags != 0) {
2636         if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV)
2637           AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV;
2638         Vals.push_back(Flags);
2639       }
2640     }
2641     break;
2642   case Instruction::GetElementPtr: {
2643     Code = bitc::FUNC_CODE_INST_GEP;
2644     AbbrevToUse = FUNCTION_INST_GEP_ABBREV;
2645     auto &GEPInst = cast<GetElementPtrInst>(I);
2646     Vals.push_back(GEPInst.isInBounds());
2647     Vals.push_back(VE.getTypeID(GEPInst.getSourceElementType()));
2648     for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
2649       pushValueAndType(I.getOperand(i), InstID, Vals);
2650     break;
2651   }
2652   case Instruction::ExtractValue: {
2653     Code = bitc::FUNC_CODE_INST_EXTRACTVAL;
2654     pushValueAndType(I.getOperand(0), InstID, Vals);
2655     const ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
2656     Vals.append(EVI->idx_begin(), EVI->idx_end());
2657     break;
2658   }
2659   case Instruction::InsertValue: {
2660     Code = bitc::FUNC_CODE_INST_INSERTVAL;
2661     pushValueAndType(I.getOperand(0), InstID, Vals);
2662     pushValueAndType(I.getOperand(1), InstID, Vals);
2663     const InsertValueInst *IVI = cast<InsertValueInst>(&I);
2664     Vals.append(IVI->idx_begin(), IVI->idx_end());
2665     break;
2666   }
2667   case Instruction::Select: {
2668     Code = bitc::FUNC_CODE_INST_VSELECT;
2669     pushValueAndType(I.getOperand(1), InstID, Vals);
2670     pushValue(I.getOperand(2), InstID, Vals);
2671     pushValueAndType(I.getOperand(0), InstID, Vals);
2672     uint64_t Flags = getOptimizationFlags(&I);
2673     if (Flags != 0)
2674       Vals.push_back(Flags);
2675     break;
2676   }
2677   case Instruction::ExtractElement:
2678     Code = bitc::FUNC_CODE_INST_EXTRACTELT;
2679     pushValueAndType(I.getOperand(0), InstID, Vals);
2680     pushValueAndType(I.getOperand(1), InstID, Vals);
2681     break;
2682   case Instruction::InsertElement:
2683     Code = bitc::FUNC_CODE_INST_INSERTELT;
2684     pushValueAndType(I.getOperand(0), InstID, Vals);
2685     pushValue(I.getOperand(1), InstID, Vals);
2686     pushValueAndType(I.getOperand(2), InstID, Vals);
2687     break;
2688   case Instruction::ShuffleVector:
2689     Code = bitc::FUNC_CODE_INST_SHUFFLEVEC;
2690     pushValueAndType(I.getOperand(0), InstID, Vals);
2691     pushValue(I.getOperand(1), InstID, Vals);
2692     pushValue(I.getOperand(2), InstID, Vals);
2693     break;
2694   case Instruction::ICmp:
2695   case Instruction::FCmp: {
2696     // compare returning Int1Ty or vector of Int1Ty
2697     Code = bitc::FUNC_CODE_INST_CMP2;
2698     pushValueAndType(I.getOperand(0), InstID, Vals);
2699     pushValue(I.getOperand(1), InstID, Vals);
2700     Vals.push_back(cast<CmpInst>(I).getPredicate());
2701     uint64_t Flags = getOptimizationFlags(&I);
2702     if (Flags != 0)
2703       Vals.push_back(Flags);
2704     break;
2705   }
2706 
2707   case Instruction::Ret:
2708     {
2709       Code = bitc::FUNC_CODE_INST_RET;
2710       unsigned NumOperands = I.getNumOperands();
2711       if (NumOperands == 0)
2712         AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
2713       else if (NumOperands == 1) {
2714         if (!pushValueAndType(I.getOperand(0), InstID, Vals))
2715           AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
2716       } else {
2717         for (unsigned i = 0, e = NumOperands; i != e; ++i)
2718           pushValueAndType(I.getOperand(i), InstID, Vals);
2719       }
2720     }
2721     break;
2722   case Instruction::Br:
2723     {
2724       Code = bitc::FUNC_CODE_INST_BR;
2725       const BranchInst &II = cast<BranchInst>(I);
2726       Vals.push_back(VE.getValueID(II.getSuccessor(0)));
2727       if (II.isConditional()) {
2728         Vals.push_back(VE.getValueID(II.getSuccessor(1)));
2729         pushValue(II.getCondition(), InstID, Vals);
2730       }
2731     }
2732     break;
2733   case Instruction::Switch:
2734     {
2735       Code = bitc::FUNC_CODE_INST_SWITCH;
2736       const SwitchInst &SI = cast<SwitchInst>(I);
2737       Vals.push_back(VE.getTypeID(SI.getCondition()->getType()));
2738       pushValue(SI.getCondition(), InstID, Vals);
2739       Vals.push_back(VE.getValueID(SI.getDefaultDest()));
2740       for (auto Case : SI.cases()) {
2741         Vals.push_back(VE.getValueID(Case.getCaseValue()));
2742         Vals.push_back(VE.getValueID(Case.getCaseSuccessor()));
2743       }
2744     }
2745     break;
2746   case Instruction::IndirectBr:
2747     Code = bitc::FUNC_CODE_INST_INDIRECTBR;
2748     Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
2749     // Encode the address operand as relative, but not the basic blocks.
2750     pushValue(I.getOperand(0), InstID, Vals);
2751     for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i)
2752       Vals.push_back(VE.getValueID(I.getOperand(i)));
2753     break;
2754 
2755   case Instruction::Invoke: {
2756     const InvokeInst *II = cast<InvokeInst>(&I);
2757     const Value *Callee = II->getCalledValue();
2758     FunctionType *FTy = II->getFunctionType();
2759 
2760     if (II->hasOperandBundles())
2761       writeOperandBundles(II, InstID);
2762 
2763     Code = bitc::FUNC_CODE_INST_INVOKE;
2764 
2765     Vals.push_back(VE.getAttributeListID(II->getAttributes()));
2766     Vals.push_back(II->getCallingConv() | 1 << 13);
2767     Vals.push_back(VE.getValueID(II->getNormalDest()));
2768     Vals.push_back(VE.getValueID(II->getUnwindDest()));
2769     Vals.push_back(VE.getTypeID(FTy));
2770     pushValueAndType(Callee, InstID, Vals);
2771 
2772     // Emit value #'s for the fixed parameters.
2773     for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
2774       pushValue(I.getOperand(i), InstID, Vals); // fixed param.
2775 
2776     // Emit type/value pairs for varargs params.
2777     if (FTy->isVarArg()) {
2778       for (unsigned i = FTy->getNumParams(), e = II->getNumArgOperands();
2779            i != e; ++i)
2780         pushValueAndType(I.getOperand(i), InstID, Vals); // vararg
2781     }
2782     break;
2783   }
2784   case Instruction::Resume:
2785     Code = bitc::FUNC_CODE_INST_RESUME;
2786     pushValueAndType(I.getOperand(0), InstID, Vals);
2787     break;
2788   case Instruction::CleanupRet: {
2789     Code = bitc::FUNC_CODE_INST_CLEANUPRET;
2790     const auto &CRI = cast<CleanupReturnInst>(I);
2791     pushValue(CRI.getCleanupPad(), InstID, Vals);
2792     if (CRI.hasUnwindDest())
2793       Vals.push_back(VE.getValueID(CRI.getUnwindDest()));
2794     break;
2795   }
2796   case Instruction::CatchRet: {
2797     Code = bitc::FUNC_CODE_INST_CATCHRET;
2798     const auto &CRI = cast<CatchReturnInst>(I);
2799     pushValue(CRI.getCatchPad(), InstID, Vals);
2800     Vals.push_back(VE.getValueID(CRI.getSuccessor()));
2801     break;
2802   }
2803   case Instruction::CleanupPad:
2804   case Instruction::CatchPad: {
2805     const auto &FuncletPad = cast<FuncletPadInst>(I);
2806     Code = isa<CatchPadInst>(FuncletPad) ? bitc::FUNC_CODE_INST_CATCHPAD
2807                                          : bitc::FUNC_CODE_INST_CLEANUPPAD;
2808     pushValue(FuncletPad.getParentPad(), InstID, Vals);
2809 
2810     unsigned NumArgOperands = FuncletPad.getNumArgOperands();
2811     Vals.push_back(NumArgOperands);
2812     for (unsigned Op = 0; Op != NumArgOperands; ++Op)
2813       pushValueAndType(FuncletPad.getArgOperand(Op), InstID, Vals);
2814     break;
2815   }
2816   case Instruction::CatchSwitch: {
2817     Code = bitc::FUNC_CODE_INST_CATCHSWITCH;
2818     const auto &CatchSwitch = cast<CatchSwitchInst>(I);
2819 
2820     pushValue(CatchSwitch.getParentPad(), InstID, Vals);
2821 
2822     unsigned NumHandlers = CatchSwitch.getNumHandlers();
2823     Vals.push_back(NumHandlers);
2824     for (const BasicBlock *CatchPadBB : CatchSwitch.handlers())
2825       Vals.push_back(VE.getValueID(CatchPadBB));
2826 
2827     if (CatchSwitch.hasUnwindDest())
2828       Vals.push_back(VE.getValueID(CatchSwitch.getUnwindDest()));
2829     break;
2830   }
2831   case Instruction::CallBr: {
2832     const CallBrInst *CBI = cast<CallBrInst>(&I);
2833     const Value *Callee = CBI->getCalledValue();
2834     FunctionType *FTy = CBI->getFunctionType();
2835 
2836     if (CBI->hasOperandBundles())
2837       writeOperandBundles(CBI, InstID);
2838 
2839     Code = bitc::FUNC_CODE_INST_CALLBR;
2840 
2841     Vals.push_back(VE.getAttributeListID(CBI->getAttributes()));
2842 
2843     Vals.push_back(CBI->getCallingConv() << bitc::CALL_CCONV |
2844                    1 << bitc::CALL_EXPLICIT_TYPE);
2845 
2846     Vals.push_back(VE.getValueID(CBI->getDefaultDest()));
2847     Vals.push_back(CBI->getNumIndirectDests());
2848     for (unsigned i = 0, e = CBI->getNumIndirectDests(); i != e; ++i)
2849       Vals.push_back(VE.getValueID(CBI->getIndirectDest(i)));
2850 
2851     Vals.push_back(VE.getTypeID(FTy));
2852     pushValueAndType(Callee, InstID, Vals);
2853 
2854     // Emit value #'s for the fixed parameters.
2855     for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
2856       pushValue(I.getOperand(i), InstID, Vals); // fixed param.
2857 
2858     // Emit type/value pairs for varargs params.
2859     if (FTy->isVarArg()) {
2860       for (unsigned i = FTy->getNumParams(), e = CBI->getNumArgOperands();
2861            i != e; ++i)
2862         pushValueAndType(I.getOperand(i), InstID, Vals); // vararg
2863     }
2864     break;
2865   }
2866   case Instruction::Unreachable:
2867     Code = bitc::FUNC_CODE_INST_UNREACHABLE;
2868     AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
2869     break;
2870 
2871   case Instruction::PHI: {
2872     const PHINode &PN = cast<PHINode>(I);
2873     Code = bitc::FUNC_CODE_INST_PHI;
2874     // With the newer instruction encoding, forward references could give
2875     // negative valued IDs.  This is most common for PHIs, so we use
2876     // signed VBRs.
2877     SmallVector<uint64_t, 128> Vals64;
2878     Vals64.push_back(VE.getTypeID(PN.getType()));
2879     for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
2880       pushValueSigned(PN.getIncomingValue(i), InstID, Vals64);
2881       Vals64.push_back(VE.getValueID(PN.getIncomingBlock(i)));
2882     }
2883 
2884     uint64_t Flags = getOptimizationFlags(&I);
2885     if (Flags != 0)
2886       Vals64.push_back(Flags);
2887 
2888     // Emit a Vals64 vector and exit.
2889     Stream.EmitRecord(Code, Vals64, AbbrevToUse);
2890     Vals64.clear();
2891     return;
2892   }
2893 
2894   case Instruction::LandingPad: {
2895     const LandingPadInst &LP = cast<LandingPadInst>(I);
2896     Code = bitc::FUNC_CODE_INST_LANDINGPAD;
2897     Vals.push_back(VE.getTypeID(LP.getType()));
2898     Vals.push_back(LP.isCleanup());
2899     Vals.push_back(LP.getNumClauses());
2900     for (unsigned I = 0, E = LP.getNumClauses(); I != E; ++I) {
2901       if (LP.isCatch(I))
2902         Vals.push_back(LandingPadInst::Catch);
2903       else
2904         Vals.push_back(LandingPadInst::Filter);
2905       pushValueAndType(LP.getClause(I), InstID, Vals);
2906     }
2907     break;
2908   }
2909 
2910   case Instruction::Alloca: {
2911     Code = bitc::FUNC_CODE_INST_ALLOCA;
2912     const AllocaInst &AI = cast<AllocaInst>(I);
2913     Vals.push_back(VE.getTypeID(AI.getAllocatedType()));
2914     Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
2915     Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
2916     unsigned AlignRecord = Log2_32(AI.getAlignment()) + 1;
2917     assert(Log2_32(Value::MaximumAlignment) + 1 < 1 << 5 &&
2918            "not enough bits for maximum alignment");
2919     assert(AlignRecord < 1 << 5 && "alignment greater than 1 << 64");
2920     AlignRecord |= AI.isUsedWithInAlloca() << 5;
2921     AlignRecord |= 1 << 6;
2922     AlignRecord |= AI.isSwiftError() << 7;
2923     Vals.push_back(AlignRecord);
2924     break;
2925   }
2926 
2927   case Instruction::Load:
2928     if (cast<LoadInst>(I).isAtomic()) {
2929       Code = bitc::FUNC_CODE_INST_LOADATOMIC;
2930       pushValueAndType(I.getOperand(0), InstID, Vals);
2931     } else {
2932       Code = bitc::FUNC_CODE_INST_LOAD;
2933       if (!pushValueAndType(I.getOperand(0), InstID, Vals)) // ptr
2934         AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
2935     }
2936     Vals.push_back(VE.getTypeID(I.getType()));
2937     Vals.push_back(Log2_32(cast<LoadInst>(I).getAlignment())+1);
2938     Vals.push_back(cast<LoadInst>(I).isVolatile());
2939     if (cast<LoadInst>(I).isAtomic()) {
2940       Vals.push_back(getEncodedOrdering(cast<LoadInst>(I).getOrdering()));
2941       Vals.push_back(getEncodedSyncScopeID(cast<LoadInst>(I).getSyncScopeID()));
2942     }
2943     break;
2944   case Instruction::Store:
2945     if (cast<StoreInst>(I).isAtomic())
2946       Code = bitc::FUNC_CODE_INST_STOREATOMIC;
2947     else
2948       Code = bitc::FUNC_CODE_INST_STORE;
2949     pushValueAndType(I.getOperand(1), InstID, Vals); // ptrty + ptr
2950     pushValueAndType(I.getOperand(0), InstID, Vals); // valty + val
2951     Vals.push_back(Log2_32(cast<StoreInst>(I).getAlignment())+1);
2952     Vals.push_back(cast<StoreInst>(I).isVolatile());
2953     if (cast<StoreInst>(I).isAtomic()) {
2954       Vals.push_back(getEncodedOrdering(cast<StoreInst>(I).getOrdering()));
2955       Vals.push_back(
2956           getEncodedSyncScopeID(cast<StoreInst>(I).getSyncScopeID()));
2957     }
2958     break;
2959   case Instruction::AtomicCmpXchg:
2960     Code = bitc::FUNC_CODE_INST_CMPXCHG;
2961     pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr
2962     pushValueAndType(I.getOperand(1), InstID, Vals); // cmp.
2963     pushValue(I.getOperand(2), InstID, Vals);        // newval.
2964     Vals.push_back(cast<AtomicCmpXchgInst>(I).isVolatile());
2965     Vals.push_back(
2966         getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getSuccessOrdering()));
2967     Vals.push_back(
2968         getEncodedSyncScopeID(cast<AtomicCmpXchgInst>(I).getSyncScopeID()));
2969     Vals.push_back(
2970         getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getFailureOrdering()));
2971     Vals.push_back(cast<AtomicCmpXchgInst>(I).isWeak());
2972     break;
2973   case Instruction::AtomicRMW:
2974     Code = bitc::FUNC_CODE_INST_ATOMICRMW;
2975     pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr
2976     pushValue(I.getOperand(1), InstID, Vals);        // val.
2977     Vals.push_back(
2978         getEncodedRMWOperation(cast<AtomicRMWInst>(I).getOperation()));
2979     Vals.push_back(cast<AtomicRMWInst>(I).isVolatile());
2980     Vals.push_back(getEncodedOrdering(cast<AtomicRMWInst>(I).getOrdering()));
2981     Vals.push_back(
2982         getEncodedSyncScopeID(cast<AtomicRMWInst>(I).getSyncScopeID()));
2983     break;
2984   case Instruction::Fence:
2985     Code = bitc::FUNC_CODE_INST_FENCE;
2986     Vals.push_back(getEncodedOrdering(cast<FenceInst>(I).getOrdering()));
2987     Vals.push_back(getEncodedSyncScopeID(cast<FenceInst>(I).getSyncScopeID()));
2988     break;
2989   case Instruction::Call: {
2990     const CallInst &CI = cast<CallInst>(I);
2991     FunctionType *FTy = CI.getFunctionType();
2992 
2993     if (CI.hasOperandBundles())
2994       writeOperandBundles(&CI, InstID);
2995 
2996     Code = bitc::FUNC_CODE_INST_CALL;
2997 
2998     Vals.push_back(VE.getAttributeListID(CI.getAttributes()));
2999 
3000     unsigned Flags = getOptimizationFlags(&I);
3001     Vals.push_back(CI.getCallingConv() << bitc::CALL_CCONV |
3002                    unsigned(CI.isTailCall()) << bitc::CALL_TAIL |
3003                    unsigned(CI.isMustTailCall()) << bitc::CALL_MUSTTAIL |
3004                    1 << bitc::CALL_EXPLICIT_TYPE |
3005                    unsigned(CI.isNoTailCall()) << bitc::CALL_NOTAIL |
3006                    unsigned(Flags != 0) << bitc::CALL_FMF);
3007     if (Flags != 0)
3008       Vals.push_back(Flags);
3009 
3010     Vals.push_back(VE.getTypeID(FTy));
3011     pushValueAndType(CI.getCalledValue(), InstID, Vals); // Callee
3012 
3013     // Emit value #'s for the fixed parameters.
3014     for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
3015       // Check for labels (can happen with asm labels).
3016       if (FTy->getParamType(i)->isLabelTy())
3017         Vals.push_back(VE.getValueID(CI.getArgOperand(i)));
3018       else
3019         pushValue(CI.getArgOperand(i), InstID, Vals); // fixed param.
3020     }
3021 
3022     // Emit type/value pairs for varargs params.
3023     if (FTy->isVarArg()) {
3024       for (unsigned i = FTy->getNumParams(), e = CI.getNumArgOperands();
3025            i != e; ++i)
3026         pushValueAndType(CI.getArgOperand(i), InstID, Vals); // varargs
3027     }
3028     break;
3029   }
3030   case Instruction::VAArg:
3031     Code = bitc::FUNC_CODE_INST_VAARG;
3032     Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));   // valistty
3033     pushValue(I.getOperand(0), InstID, Vals);                   // valist.
3034     Vals.push_back(VE.getTypeID(I.getType())); // restype.
3035     break;
3036   }
3037 
3038   Stream.EmitRecord(Code, Vals, AbbrevToUse);
3039   Vals.clear();
3040 }
3041 
3042 /// Write a GlobalValue VST to the module. The purpose of this data structure is
3043 /// to allow clients to efficiently find the function body.
3044 void ModuleBitcodeWriter::writeGlobalValueSymbolTable(
3045   DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) {
3046   // Get the offset of the VST we are writing, and backpatch it into
3047   // the VST forward declaration record.
3048   uint64_t VSTOffset = Stream.GetCurrentBitNo();
3049   // The BitcodeStartBit was the stream offset of the identification block.
3050   VSTOffset -= bitcodeStartBit();
3051   assert((VSTOffset & 31) == 0 && "VST block not 32-bit aligned");
3052   // Note that we add 1 here because the offset is relative to one word
3053   // before the start of the identification block, which was historically
3054   // always the start of the regular bitcode header.
3055   Stream.BackpatchWord(VSTOffsetPlaceholder, VSTOffset / 32 + 1);
3056 
3057   Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
3058 
3059   auto Abbv = std::make_shared<BitCodeAbbrev>();
3060   Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_FNENTRY));
3061   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
3062   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // funcoffset
3063   unsigned FnEntryAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3064 
3065   for (const Function &F : M) {
3066     uint64_t Record[2];
3067 
3068     if (F.isDeclaration())
3069       continue;
3070 
3071     Record[0] = VE.getValueID(&F);
3072 
3073     // Save the word offset of the function (from the start of the
3074     // actual bitcode written to the stream).
3075     uint64_t BitcodeIndex = FunctionToBitcodeIndex[&F] - bitcodeStartBit();
3076     assert((BitcodeIndex & 31) == 0 && "function block not 32-bit aligned");
3077     // Note that we add 1 here because the offset is relative to one word
3078     // before the start of the identification block, which was historically
3079     // always the start of the regular bitcode header.
3080     Record[1] = BitcodeIndex / 32 + 1;
3081 
3082     Stream.EmitRecord(bitc::VST_CODE_FNENTRY, Record, FnEntryAbbrev);
3083   }
3084 
3085   Stream.ExitBlock();
3086 }
3087 
3088 /// Emit names for arguments, instructions and basic blocks in a function.
3089 void ModuleBitcodeWriter::writeFunctionLevelValueSymbolTable(
3090     const ValueSymbolTable &VST) {
3091   if (VST.empty())
3092     return;
3093 
3094   Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
3095 
3096   // FIXME: Set up the abbrev, we know how many values there are!
3097   // FIXME: We know if the type names can use 7-bit ascii.
3098   SmallVector<uint64_t, 64> NameVals;
3099 
3100   for (const ValueName &Name : VST) {
3101     // Figure out the encoding to use for the name.
3102     StringEncoding Bits = getStringEncoding(Name.getKey());
3103 
3104     unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
3105     NameVals.push_back(VE.getValueID(Name.getValue()));
3106 
3107     // VST_CODE_ENTRY:   [valueid, namechar x N]
3108     // VST_CODE_BBENTRY: [bbid, namechar x N]
3109     unsigned Code;
3110     if (isa<BasicBlock>(Name.getValue())) {
3111       Code = bitc::VST_CODE_BBENTRY;
3112       if (Bits == SE_Char6)
3113         AbbrevToUse = VST_BBENTRY_6_ABBREV;
3114     } else {
3115       Code = bitc::VST_CODE_ENTRY;
3116       if (Bits == SE_Char6)
3117         AbbrevToUse = VST_ENTRY_6_ABBREV;
3118       else if (Bits == SE_Fixed7)
3119         AbbrevToUse = VST_ENTRY_7_ABBREV;
3120     }
3121 
3122     for (const auto P : Name.getKey())
3123       NameVals.push_back((unsigned char)P);
3124 
3125     // Emit the finished record.
3126     Stream.EmitRecord(Code, NameVals, AbbrevToUse);
3127     NameVals.clear();
3128   }
3129 
3130   Stream.ExitBlock();
3131 }
3132 
3133 void ModuleBitcodeWriter::writeUseList(UseListOrder &&Order) {
3134   assert(Order.Shuffle.size() >= 2 && "Shuffle too small");
3135   unsigned Code;
3136   if (isa<BasicBlock>(Order.V))
3137     Code = bitc::USELIST_CODE_BB;
3138   else
3139     Code = bitc::USELIST_CODE_DEFAULT;
3140 
3141   SmallVector<uint64_t, 64> Record(Order.Shuffle.begin(), Order.Shuffle.end());
3142   Record.push_back(VE.getValueID(Order.V));
3143   Stream.EmitRecord(Code, Record);
3144 }
3145 
3146 void ModuleBitcodeWriter::writeUseListBlock(const Function *F) {
3147   assert(VE.shouldPreserveUseListOrder() &&
3148          "Expected to be preserving use-list order");
3149 
3150   auto hasMore = [&]() {
3151     return !VE.UseListOrders.empty() && VE.UseListOrders.back().F == F;
3152   };
3153   if (!hasMore())
3154     // Nothing to do.
3155     return;
3156 
3157   Stream.EnterSubblock(bitc::USELIST_BLOCK_ID, 3);
3158   while (hasMore()) {
3159     writeUseList(std::move(VE.UseListOrders.back()));
3160     VE.UseListOrders.pop_back();
3161   }
3162   Stream.ExitBlock();
3163 }
3164 
3165 /// Emit a function body to the module stream.
3166 void ModuleBitcodeWriter::writeFunction(
3167     const Function &F,
3168     DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) {
3169   // Save the bitcode index of the start of this function block for recording
3170   // in the VST.
3171   FunctionToBitcodeIndex[&F] = Stream.GetCurrentBitNo();
3172 
3173   Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 4);
3174   VE.incorporateFunction(F);
3175 
3176   SmallVector<unsigned, 64> Vals;
3177 
3178   // Emit the number of basic blocks, so the reader can create them ahead of
3179   // time.
3180   Vals.push_back(VE.getBasicBlocks().size());
3181   Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals);
3182   Vals.clear();
3183 
3184   // If there are function-local constants, emit them now.
3185   unsigned CstStart, CstEnd;
3186   VE.getFunctionConstantRange(CstStart, CstEnd);
3187   writeConstants(CstStart, CstEnd, false);
3188 
3189   // If there is function-local metadata, emit it now.
3190   writeFunctionMetadata(F);
3191 
3192   // Keep a running idea of what the instruction ID is.
3193   unsigned InstID = CstEnd;
3194 
3195   bool NeedsMetadataAttachment = F.hasMetadata();
3196 
3197   DILocation *LastDL = nullptr;
3198   // Finally, emit all the instructions, in order.
3199   for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
3200     for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
3201          I != E; ++I) {
3202       writeInstruction(*I, InstID, Vals);
3203 
3204       if (!I->getType()->isVoidTy())
3205         ++InstID;
3206 
3207       // If the instruction has metadata, write a metadata attachment later.
3208       NeedsMetadataAttachment |= I->hasMetadataOtherThanDebugLoc();
3209 
3210       // If the instruction has a debug location, emit it.
3211       DILocation *DL = I->getDebugLoc();
3212       if (!DL)
3213         continue;
3214 
3215       if (DL == LastDL) {
3216         // Just repeat the same debug loc as last time.
3217         Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC_AGAIN, Vals);
3218         continue;
3219       }
3220 
3221       Vals.push_back(DL->getLine());
3222       Vals.push_back(DL->getColumn());
3223       Vals.push_back(VE.getMetadataOrNullID(DL->getScope()));
3224       Vals.push_back(VE.getMetadataOrNullID(DL->getInlinedAt()));
3225       Vals.push_back(DL->isImplicitCode());
3226       Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC, Vals);
3227       Vals.clear();
3228 
3229       LastDL = DL;
3230     }
3231 
3232   // Emit names for all the instructions etc.
3233   if (auto *Symtab = F.getValueSymbolTable())
3234     writeFunctionLevelValueSymbolTable(*Symtab);
3235 
3236   if (NeedsMetadataAttachment)
3237     writeFunctionMetadataAttachment(F);
3238   if (VE.shouldPreserveUseListOrder())
3239     writeUseListBlock(&F);
3240   VE.purgeFunction();
3241   Stream.ExitBlock();
3242 }
3243 
3244 // Emit blockinfo, which defines the standard abbreviations etc.
3245 void ModuleBitcodeWriter::writeBlockInfo() {
3246   // We only want to emit block info records for blocks that have multiple
3247   // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK.
3248   // Other blocks can define their abbrevs inline.
3249   Stream.EnterBlockInfoBlock();
3250 
3251   { // 8-bit fixed-width VST_CODE_ENTRY/VST_CODE_BBENTRY strings.
3252     auto Abbv = std::make_shared<BitCodeAbbrev>();
3253     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3));
3254     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3255     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3256     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
3257     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
3258         VST_ENTRY_8_ABBREV)
3259       llvm_unreachable("Unexpected abbrev ordering!");
3260   }
3261 
3262   { // 7-bit fixed width VST_CODE_ENTRY strings.
3263     auto Abbv = std::make_shared<BitCodeAbbrev>();
3264     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
3265     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3266     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3267     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
3268     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
3269         VST_ENTRY_7_ABBREV)
3270       llvm_unreachable("Unexpected abbrev ordering!");
3271   }
3272   { // 6-bit char6 VST_CODE_ENTRY strings.
3273     auto Abbv = std::make_shared<BitCodeAbbrev>();
3274     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
3275     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3276     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3277     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
3278     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
3279         VST_ENTRY_6_ABBREV)
3280       llvm_unreachable("Unexpected abbrev ordering!");
3281   }
3282   { // 6-bit char6 VST_CODE_BBENTRY strings.
3283     auto Abbv = std::make_shared<BitCodeAbbrev>();
3284     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY));
3285     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3286     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3287     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
3288     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
3289         VST_BBENTRY_6_ABBREV)
3290       llvm_unreachable("Unexpected abbrev ordering!");
3291   }
3292 
3293   { // SETTYPE abbrev for CONSTANTS_BLOCK.
3294     auto Abbv = std::make_shared<BitCodeAbbrev>();
3295     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_SETTYPE));
3296     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
3297                               VE.computeBitsRequiredForTypeIndicies()));
3298     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
3299         CONSTANTS_SETTYPE_ABBREV)
3300       llvm_unreachable("Unexpected abbrev ordering!");
3301   }
3302 
3303   { // INTEGER abbrev for CONSTANTS_BLOCK.
3304     auto Abbv = std::make_shared<BitCodeAbbrev>();
3305     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_INTEGER));
3306     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3307     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
3308         CONSTANTS_INTEGER_ABBREV)
3309       llvm_unreachable("Unexpected abbrev ordering!");
3310   }
3311 
3312   { // CE_CAST abbrev for CONSTANTS_BLOCK.
3313     auto Abbv = std::make_shared<BitCodeAbbrev>();
3314     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CE_CAST));
3315     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4));  // cast opc
3316     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,       // typeid
3317                               VE.computeBitsRequiredForTypeIndicies()));
3318     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));    // value id
3319 
3320     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
3321         CONSTANTS_CE_CAST_Abbrev)
3322       llvm_unreachable("Unexpected abbrev ordering!");
3323   }
3324   { // NULL abbrev for CONSTANTS_BLOCK.
3325     auto Abbv = std::make_shared<BitCodeAbbrev>();
3326     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_NULL));
3327     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
3328         CONSTANTS_NULL_Abbrev)
3329       llvm_unreachable("Unexpected abbrev ordering!");
3330   }
3331 
3332   // FIXME: This should only use space for first class types!
3333 
3334   { // INST_LOAD abbrev for FUNCTION_BLOCK.
3335     auto Abbv = std::make_shared<BitCodeAbbrev>();
3336     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_LOAD));
3337     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Ptr
3338     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,    // dest ty
3339                               VE.computeBitsRequiredForTypeIndicies()));
3340     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align
3341     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile
3342     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3343         FUNCTION_INST_LOAD_ABBREV)
3344       llvm_unreachable("Unexpected abbrev ordering!");
3345   }
3346   { // INST_UNOP abbrev for FUNCTION_BLOCK.
3347     auto Abbv = std::make_shared<BitCodeAbbrev>();
3348     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNOP));
3349     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
3350     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3351     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3352         FUNCTION_INST_UNOP_ABBREV)
3353       llvm_unreachable("Unexpected abbrev ordering!");
3354   }
3355   { // INST_UNOP_FLAGS abbrev for FUNCTION_BLOCK.
3356     auto Abbv = std::make_shared<BitCodeAbbrev>();
3357     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNOP));
3358     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
3359     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3360     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); // flags
3361     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3362         FUNCTION_INST_UNOP_FLAGS_ABBREV)
3363       llvm_unreachable("Unexpected abbrev ordering!");
3364   }
3365   { // INST_BINOP abbrev for FUNCTION_BLOCK.
3366     auto Abbv = std::make_shared<BitCodeAbbrev>();
3367     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
3368     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
3369     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
3370     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3371     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3372         FUNCTION_INST_BINOP_ABBREV)
3373       llvm_unreachable("Unexpected abbrev ordering!");
3374   }
3375   { // INST_BINOP_FLAGS abbrev for FUNCTION_BLOCK.
3376     auto Abbv = std::make_shared<BitCodeAbbrev>();
3377     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
3378     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
3379     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
3380     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3381     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); // flags
3382     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3383         FUNCTION_INST_BINOP_FLAGS_ABBREV)
3384       llvm_unreachable("Unexpected abbrev ordering!");
3385   }
3386   { // INST_CAST abbrev for FUNCTION_BLOCK.
3387     auto Abbv = std::make_shared<BitCodeAbbrev>();
3388     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST));
3389     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));    // OpVal
3390     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,       // dest ty
3391                               VE.computeBitsRequiredForTypeIndicies()));
3392     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4));  // opc
3393     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3394         FUNCTION_INST_CAST_ABBREV)
3395       llvm_unreachable("Unexpected abbrev ordering!");
3396   }
3397 
3398   { // INST_RET abbrev for FUNCTION_BLOCK.
3399     auto Abbv = std::make_shared<BitCodeAbbrev>();
3400     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
3401     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3402         FUNCTION_INST_RET_VOID_ABBREV)
3403       llvm_unreachable("Unexpected abbrev ordering!");
3404   }
3405   { // INST_RET abbrev for FUNCTION_BLOCK.
3406     auto Abbv = std::make_shared<BitCodeAbbrev>();
3407     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
3408     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ValID
3409     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3410         FUNCTION_INST_RET_VAL_ABBREV)
3411       llvm_unreachable("Unexpected abbrev ordering!");
3412   }
3413   { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK.
3414     auto Abbv = std::make_shared<BitCodeAbbrev>();
3415     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNREACHABLE));
3416     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3417         FUNCTION_INST_UNREACHABLE_ABBREV)
3418       llvm_unreachable("Unexpected abbrev ordering!");
3419   }
3420   {
3421     auto Abbv = std::make_shared<BitCodeAbbrev>();
3422     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_GEP));
3423     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
3424     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
3425                               Log2_32_Ceil(VE.getTypes().size() + 1)));
3426     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3427     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
3428     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3429         FUNCTION_INST_GEP_ABBREV)
3430       llvm_unreachable("Unexpected abbrev ordering!");
3431   }
3432 
3433   Stream.ExitBlock();
3434 }
3435 
3436 /// Write the module path strings, currently only used when generating
3437 /// a combined index file.
3438 void IndexBitcodeWriter::writeModStrings() {
3439   Stream.EnterSubblock(bitc::MODULE_STRTAB_BLOCK_ID, 3);
3440 
3441   // TODO: See which abbrev sizes we actually need to emit
3442 
3443   // 8-bit fixed-width MST_ENTRY strings.
3444   auto Abbv = std::make_shared<BitCodeAbbrev>();
3445   Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
3446   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3447   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3448   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
3449   unsigned Abbrev8Bit = Stream.EmitAbbrev(std::move(Abbv));
3450 
3451   // 7-bit fixed width MST_ENTRY strings.
3452   Abbv = std::make_shared<BitCodeAbbrev>();
3453   Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
3454   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3455   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3456   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
3457   unsigned Abbrev7Bit = Stream.EmitAbbrev(std::move(Abbv));
3458 
3459   // 6-bit char6 MST_ENTRY strings.
3460   Abbv = std::make_shared<BitCodeAbbrev>();
3461   Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
3462   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3463   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3464   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
3465   unsigned Abbrev6Bit = Stream.EmitAbbrev(std::move(Abbv));
3466 
3467   // Module Hash, 160 bits SHA1. Optionally, emitted after each MST_CODE_ENTRY.
3468   Abbv = std::make_shared<BitCodeAbbrev>();
3469   Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_HASH));
3470   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3471   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3472   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3473   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3474   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3475   unsigned AbbrevHash = Stream.EmitAbbrev(std::move(Abbv));
3476 
3477   SmallVector<unsigned, 64> Vals;
3478   forEachModule(
3479       [&](const StringMapEntry<std::pair<uint64_t, ModuleHash>> &MPSE) {
3480         StringRef Key = MPSE.getKey();
3481         const auto &Value = MPSE.getValue();
3482         StringEncoding Bits = getStringEncoding(Key);
3483         unsigned AbbrevToUse = Abbrev8Bit;
3484         if (Bits == SE_Char6)
3485           AbbrevToUse = Abbrev6Bit;
3486         else if (Bits == SE_Fixed7)
3487           AbbrevToUse = Abbrev7Bit;
3488 
3489         Vals.push_back(Value.first);
3490         Vals.append(Key.begin(), Key.end());
3491 
3492         // Emit the finished record.
3493         Stream.EmitRecord(bitc::MST_CODE_ENTRY, Vals, AbbrevToUse);
3494 
3495         // Emit an optional hash for the module now
3496         const auto &Hash = Value.second;
3497         if (llvm::any_of(Hash, [](uint32_t H) { return H; })) {
3498           Vals.assign(Hash.begin(), Hash.end());
3499           // Emit the hash record.
3500           Stream.EmitRecord(bitc::MST_CODE_HASH, Vals, AbbrevHash);
3501         }
3502 
3503         Vals.clear();
3504       });
3505   Stream.ExitBlock();
3506 }
3507 
3508 /// Write the function type metadata related records that need to appear before
3509 /// a function summary entry (whether per-module or combined).
3510 static void writeFunctionTypeMetadataRecords(BitstreamWriter &Stream,
3511                                              FunctionSummary *FS) {
3512   if (!FS->type_tests().empty())
3513     Stream.EmitRecord(bitc::FS_TYPE_TESTS, FS->type_tests());
3514 
3515   SmallVector<uint64_t, 64> Record;
3516 
3517   auto WriteVFuncIdVec = [&](uint64_t Ty,
3518                              ArrayRef<FunctionSummary::VFuncId> VFs) {
3519     if (VFs.empty())
3520       return;
3521     Record.clear();
3522     for (auto &VF : VFs) {
3523       Record.push_back(VF.GUID);
3524       Record.push_back(VF.Offset);
3525     }
3526     Stream.EmitRecord(Ty, Record);
3527   };
3528 
3529   WriteVFuncIdVec(bitc::FS_TYPE_TEST_ASSUME_VCALLS,
3530                   FS->type_test_assume_vcalls());
3531   WriteVFuncIdVec(bitc::FS_TYPE_CHECKED_LOAD_VCALLS,
3532                   FS->type_checked_load_vcalls());
3533 
3534   auto WriteConstVCallVec = [&](uint64_t Ty,
3535                                 ArrayRef<FunctionSummary::ConstVCall> VCs) {
3536     for (auto &VC : VCs) {
3537       Record.clear();
3538       Record.push_back(VC.VFunc.GUID);
3539       Record.push_back(VC.VFunc.Offset);
3540       Record.insert(Record.end(), VC.Args.begin(), VC.Args.end());
3541       Stream.EmitRecord(Ty, Record);
3542     }
3543   };
3544 
3545   WriteConstVCallVec(bitc::FS_TYPE_TEST_ASSUME_CONST_VCALL,
3546                      FS->type_test_assume_const_vcalls());
3547   WriteConstVCallVec(bitc::FS_TYPE_CHECKED_LOAD_CONST_VCALL,
3548                      FS->type_checked_load_const_vcalls());
3549 }
3550 
3551 /// Collect type IDs from type tests used by function.
3552 static void
3553 getReferencedTypeIds(FunctionSummary *FS,
3554                      std::set<GlobalValue::GUID> &ReferencedTypeIds) {
3555   if (!FS->type_tests().empty())
3556     for (auto &TT : FS->type_tests())
3557       ReferencedTypeIds.insert(TT);
3558 
3559   auto GetReferencedTypesFromVFuncIdVec =
3560       [&](ArrayRef<FunctionSummary::VFuncId> VFs) {
3561         for (auto &VF : VFs)
3562           ReferencedTypeIds.insert(VF.GUID);
3563       };
3564 
3565   GetReferencedTypesFromVFuncIdVec(FS->type_test_assume_vcalls());
3566   GetReferencedTypesFromVFuncIdVec(FS->type_checked_load_vcalls());
3567 
3568   auto GetReferencedTypesFromConstVCallVec =
3569       [&](ArrayRef<FunctionSummary::ConstVCall> VCs) {
3570         for (auto &VC : VCs)
3571           ReferencedTypeIds.insert(VC.VFunc.GUID);
3572       };
3573 
3574   GetReferencedTypesFromConstVCallVec(FS->type_test_assume_const_vcalls());
3575   GetReferencedTypesFromConstVCallVec(FS->type_checked_load_const_vcalls());
3576 }
3577 
3578 static void writeWholeProgramDevirtResolutionByArg(
3579     SmallVector<uint64_t, 64> &NameVals, const std::vector<uint64_t> &args,
3580     const WholeProgramDevirtResolution::ByArg &ByArg) {
3581   NameVals.push_back(args.size());
3582   NameVals.insert(NameVals.end(), args.begin(), args.end());
3583 
3584   NameVals.push_back(ByArg.TheKind);
3585   NameVals.push_back(ByArg.Info);
3586   NameVals.push_back(ByArg.Byte);
3587   NameVals.push_back(ByArg.Bit);
3588 }
3589 
3590 static void writeWholeProgramDevirtResolution(
3591     SmallVector<uint64_t, 64> &NameVals, StringTableBuilder &StrtabBuilder,
3592     uint64_t Id, const WholeProgramDevirtResolution &Wpd) {
3593   NameVals.push_back(Id);
3594 
3595   NameVals.push_back(Wpd.TheKind);
3596   NameVals.push_back(StrtabBuilder.add(Wpd.SingleImplName));
3597   NameVals.push_back(Wpd.SingleImplName.size());
3598 
3599   NameVals.push_back(Wpd.ResByArg.size());
3600   for (auto &A : Wpd.ResByArg)
3601     writeWholeProgramDevirtResolutionByArg(NameVals, A.first, A.second);
3602 }
3603 
3604 static void writeTypeIdSummaryRecord(SmallVector<uint64_t, 64> &NameVals,
3605                                      StringTableBuilder &StrtabBuilder,
3606                                      const std::string &Id,
3607                                      const TypeIdSummary &Summary) {
3608   NameVals.push_back(StrtabBuilder.add(Id));
3609   NameVals.push_back(Id.size());
3610 
3611   NameVals.push_back(Summary.TTRes.TheKind);
3612   NameVals.push_back(Summary.TTRes.SizeM1BitWidth);
3613   NameVals.push_back(Summary.TTRes.AlignLog2);
3614   NameVals.push_back(Summary.TTRes.SizeM1);
3615   NameVals.push_back(Summary.TTRes.BitMask);
3616   NameVals.push_back(Summary.TTRes.InlineBits);
3617 
3618   for (auto &W : Summary.WPDRes)
3619     writeWholeProgramDevirtResolution(NameVals, StrtabBuilder, W.first,
3620                                       W.second);
3621 }
3622 
3623 static void writeTypeIdCompatibleVtableSummaryRecord(
3624     SmallVector<uint64_t, 64> &NameVals, StringTableBuilder &StrtabBuilder,
3625     const std::string &Id, const TypeIdCompatibleVtableInfo &Summary,
3626     ValueEnumerator &VE) {
3627   NameVals.push_back(StrtabBuilder.add(Id));
3628   NameVals.push_back(Id.size());
3629 
3630   for (auto &P : Summary) {
3631     NameVals.push_back(P.AddressPointOffset);
3632     NameVals.push_back(VE.getValueID(P.VTableVI.getValue()));
3633   }
3634 }
3635 
3636 // Helper to emit a single function summary record.
3637 void ModuleBitcodeWriterBase::writePerModuleFunctionSummaryRecord(
3638     SmallVector<uint64_t, 64> &NameVals, GlobalValueSummary *Summary,
3639     unsigned ValueID, unsigned FSCallsAbbrev, unsigned FSCallsProfileAbbrev,
3640     const Function &F) {
3641   NameVals.push_back(ValueID);
3642 
3643   FunctionSummary *FS = cast<FunctionSummary>(Summary);
3644   writeFunctionTypeMetadataRecords(Stream, FS);
3645 
3646   auto SpecialRefCnts = FS->specialRefCounts();
3647   NameVals.push_back(getEncodedGVSummaryFlags(FS->flags()));
3648   NameVals.push_back(FS->instCount());
3649   NameVals.push_back(getEncodedFFlags(FS->fflags()));
3650   NameVals.push_back(FS->refs().size());
3651   NameVals.push_back(SpecialRefCnts.first);  // rorefcnt
3652   NameVals.push_back(SpecialRefCnts.second); // worefcnt
3653 
3654   for (auto &RI : FS->refs())
3655     NameVals.push_back(VE.getValueID(RI.getValue()));
3656 
3657   bool HasProfileData =
3658       F.hasProfileData() || ForceSummaryEdgesCold != FunctionSummary::FSHT_None;
3659   for (auto &ECI : FS->calls()) {
3660     NameVals.push_back(getValueId(ECI.first));
3661     if (HasProfileData)
3662       NameVals.push_back(static_cast<uint8_t>(ECI.second.Hotness));
3663     else if (WriteRelBFToSummary)
3664       NameVals.push_back(ECI.second.RelBlockFreq);
3665   }
3666 
3667   unsigned FSAbbrev = (HasProfileData ? FSCallsProfileAbbrev : FSCallsAbbrev);
3668   unsigned Code =
3669       (HasProfileData ? bitc::FS_PERMODULE_PROFILE
3670                       : (WriteRelBFToSummary ? bitc::FS_PERMODULE_RELBF
3671                                              : bitc::FS_PERMODULE));
3672 
3673   // Emit the finished record.
3674   Stream.EmitRecord(Code, NameVals, FSAbbrev);
3675   NameVals.clear();
3676 }
3677 
3678 // Collect the global value references in the given variable's initializer,
3679 // and emit them in a summary record.
3680 void ModuleBitcodeWriterBase::writeModuleLevelReferences(
3681     const GlobalVariable &V, SmallVector<uint64_t, 64> &NameVals,
3682     unsigned FSModRefsAbbrev, unsigned FSModVTableRefsAbbrev) {
3683   auto VI = Index->getValueInfo(V.getGUID());
3684   if (!VI || VI.getSummaryList().empty()) {
3685     // Only declarations should not have a summary (a declaration might however
3686     // have a summary if the def was in module level asm).
3687     assert(V.isDeclaration());
3688     return;
3689   }
3690   auto *Summary = VI.getSummaryList()[0].get();
3691   NameVals.push_back(VE.getValueID(&V));
3692   GlobalVarSummary *VS = cast<GlobalVarSummary>(Summary);
3693   NameVals.push_back(getEncodedGVSummaryFlags(VS->flags()));
3694   NameVals.push_back(getEncodedGVarFlags(VS->varflags()));
3695 
3696   auto VTableFuncs = VS->vTableFuncs();
3697   if (!VTableFuncs.empty())
3698     NameVals.push_back(VS->refs().size());
3699 
3700   unsigned SizeBeforeRefs = NameVals.size();
3701   for (auto &RI : VS->refs())
3702     NameVals.push_back(VE.getValueID(RI.getValue()));
3703   // Sort the refs for determinism output, the vector returned by FS->refs() has
3704   // been initialized from a DenseSet.
3705   llvm::sort(NameVals.begin() + SizeBeforeRefs, NameVals.end());
3706 
3707   if (VTableFuncs.empty())
3708     Stream.EmitRecord(bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS, NameVals,
3709                       FSModRefsAbbrev);
3710   else {
3711     // VTableFuncs pairs should already be sorted by offset.
3712     for (auto &P : VTableFuncs) {
3713       NameVals.push_back(VE.getValueID(P.FuncVI.getValue()));
3714       NameVals.push_back(P.VTableOffset);
3715     }
3716 
3717     Stream.EmitRecord(bitc::FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS, NameVals,
3718                       FSModVTableRefsAbbrev);
3719   }
3720   NameVals.clear();
3721 }
3722 
3723 // Current version for the summary.
3724 // This is bumped whenever we introduce changes in the way some record are
3725 // interpreted, like flags for instance.
3726 static const uint64_t INDEX_VERSION = 8;
3727 
3728 /// Emit the per-module summary section alongside the rest of
3729 /// the module's bitcode.
3730 void ModuleBitcodeWriterBase::writePerModuleGlobalValueSummary() {
3731   // By default we compile with ThinLTO if the module has a summary, but the
3732   // client can request full LTO with a module flag.
3733   bool IsThinLTO = true;
3734   if (auto *MD =
3735           mdconst::extract_or_null<ConstantInt>(M.getModuleFlag("ThinLTO")))
3736     IsThinLTO = MD->getZExtValue();
3737   Stream.EnterSubblock(IsThinLTO ? bitc::GLOBALVAL_SUMMARY_BLOCK_ID
3738                                  : bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID,
3739                        4);
3740 
3741   Stream.EmitRecord(bitc::FS_VERSION, ArrayRef<uint64_t>{INDEX_VERSION});
3742 
3743   // Write the index flags.
3744   uint64_t Flags = 0;
3745   // Bits 1-3 are set only in the combined index, skip them.
3746   if (Index->enableSplitLTOUnit())
3747     Flags |= 0x8;
3748   Stream.EmitRecord(bitc::FS_FLAGS, ArrayRef<uint64_t>{Flags});
3749 
3750   if (Index->begin() == Index->end()) {
3751     Stream.ExitBlock();
3752     return;
3753   }
3754 
3755   for (const auto &GVI : valueIds()) {
3756     Stream.EmitRecord(bitc::FS_VALUE_GUID,
3757                       ArrayRef<uint64_t>{GVI.second, GVI.first});
3758   }
3759 
3760   // Abbrev for FS_PERMODULE_PROFILE.
3761   auto Abbv = std::make_shared<BitCodeAbbrev>();
3762   Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_PROFILE));
3763   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // valueid
3764   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // flags
3765   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // instcount
3766   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // fflags
3767   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // numrefs
3768   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // rorefcnt
3769   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // worefcnt
3770   // numrefs x valueid, n x (valueid, hotness)
3771   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3772   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3773   unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3774 
3775   // Abbrev for FS_PERMODULE or FS_PERMODULE_RELBF.
3776   Abbv = std::make_shared<BitCodeAbbrev>();
3777   if (WriteRelBFToSummary)
3778     Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_RELBF));
3779   else
3780     Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE));
3781   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // valueid
3782   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // flags
3783   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // instcount
3784   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // fflags
3785   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // numrefs
3786   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // rorefcnt
3787   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // worefcnt
3788   // numrefs x valueid, n x (valueid [, rel_block_freq])
3789   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3790   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3791   unsigned FSCallsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3792 
3793   // Abbrev for FS_PERMODULE_GLOBALVAR_INIT_REFS.
3794   Abbv = std::make_shared<BitCodeAbbrev>();
3795   Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS));
3796   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
3797   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
3798   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));  // valueids
3799   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3800   unsigned FSModRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3801 
3802   // Abbrev for FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS.
3803   Abbv = std::make_shared<BitCodeAbbrev>();
3804   Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS));
3805   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
3806   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
3807   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
3808   // numrefs x valueid, n x (valueid , offset)
3809   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3810   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3811   unsigned FSModVTableRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3812 
3813   // Abbrev for FS_ALIAS.
3814   Abbv = std::make_shared<BitCodeAbbrev>();
3815   Abbv->Add(BitCodeAbbrevOp(bitc::FS_ALIAS));
3816   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // valueid
3817   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // flags
3818   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // valueid
3819   unsigned FSAliasAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3820 
3821   // Abbrev for FS_TYPE_ID_METADATA
3822   Abbv = std::make_shared<BitCodeAbbrev>();
3823   Abbv->Add(BitCodeAbbrevOp(bitc::FS_TYPE_ID_METADATA));
3824   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // typeid strtab index
3825   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // typeid length
3826   // n x (valueid , offset)
3827   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3828   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3829   unsigned TypeIdCompatibleVtableAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3830 
3831   SmallVector<uint64_t, 64> NameVals;
3832   // Iterate over the list of functions instead of the Index to
3833   // ensure the ordering is stable.
3834   for (const Function &F : M) {
3835     // Summary emission does not support anonymous functions, they have to
3836     // renamed using the anonymous function renaming pass.
3837     if (!F.hasName())
3838       report_fatal_error("Unexpected anonymous function when writing summary");
3839 
3840     ValueInfo VI = Index->getValueInfo(F.getGUID());
3841     if (!VI || VI.getSummaryList().empty()) {
3842       // Only declarations should not have a summary (a declaration might
3843       // however have a summary if the def was in module level asm).
3844       assert(F.isDeclaration());
3845       continue;
3846     }
3847     auto *Summary = VI.getSummaryList()[0].get();
3848     writePerModuleFunctionSummaryRecord(NameVals, Summary, VE.getValueID(&F),
3849                                         FSCallsAbbrev, FSCallsProfileAbbrev, F);
3850   }
3851 
3852   // Capture references from GlobalVariable initializers, which are outside
3853   // of a function scope.
3854   for (const GlobalVariable &G : M.globals())
3855     writeModuleLevelReferences(G, NameVals, FSModRefsAbbrev,
3856                                FSModVTableRefsAbbrev);
3857 
3858   for (const GlobalAlias &A : M.aliases()) {
3859     auto *Aliasee = A.getBaseObject();
3860     if (!Aliasee->hasName())
3861       // Nameless function don't have an entry in the summary, skip it.
3862       continue;
3863     auto AliasId = VE.getValueID(&A);
3864     auto AliaseeId = VE.getValueID(Aliasee);
3865     NameVals.push_back(AliasId);
3866     auto *Summary = Index->getGlobalValueSummary(A);
3867     AliasSummary *AS = cast<AliasSummary>(Summary);
3868     NameVals.push_back(getEncodedGVSummaryFlags(AS->flags()));
3869     NameVals.push_back(AliaseeId);
3870     Stream.EmitRecord(bitc::FS_ALIAS, NameVals, FSAliasAbbrev);
3871     NameVals.clear();
3872   }
3873 
3874   for (auto &S : Index->typeIdCompatibleVtableMap()) {
3875     writeTypeIdCompatibleVtableSummaryRecord(NameVals, StrtabBuilder, S.first,
3876                                              S.second, VE);
3877     Stream.EmitRecord(bitc::FS_TYPE_ID_METADATA, NameVals,
3878                       TypeIdCompatibleVtableAbbrev);
3879     NameVals.clear();
3880   }
3881 
3882   Stream.ExitBlock();
3883 }
3884 
3885 /// Emit the combined summary section into the combined index file.
3886 void IndexBitcodeWriter::writeCombinedGlobalValueSummary() {
3887   Stream.EnterSubblock(bitc::GLOBALVAL_SUMMARY_BLOCK_ID, 3);
3888   Stream.EmitRecord(bitc::FS_VERSION, ArrayRef<uint64_t>{INDEX_VERSION});
3889 
3890   // Write the index flags.
3891   uint64_t Flags = 0;
3892   if (Index.withGlobalValueDeadStripping())
3893     Flags |= 0x1;
3894   if (Index.skipModuleByDistributedBackend())
3895     Flags |= 0x2;
3896   if (Index.hasSyntheticEntryCounts())
3897     Flags |= 0x4;
3898   if (Index.enableSplitLTOUnit())
3899     Flags |= 0x8;
3900   if (Index.partiallySplitLTOUnits())
3901     Flags |= 0x10;
3902   if (Index.withAttributePropagation())
3903     Flags |= 0x20;
3904   Stream.EmitRecord(bitc::FS_FLAGS, ArrayRef<uint64_t>{Flags});
3905 
3906   for (const auto &GVI : valueIds()) {
3907     Stream.EmitRecord(bitc::FS_VALUE_GUID,
3908                       ArrayRef<uint64_t>{GVI.second, GVI.first});
3909   }
3910 
3911   // Abbrev for FS_COMBINED.
3912   auto Abbv = std::make_shared<BitCodeAbbrev>();
3913   Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED));
3914   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // valueid
3915   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // modid
3916   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // flags
3917   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // instcount
3918   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // fflags
3919   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // entrycount
3920   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // numrefs
3921   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // rorefcnt
3922   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // worefcnt
3923   // numrefs x valueid, n x (valueid)
3924   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3925   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3926   unsigned FSCallsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3927 
3928   // Abbrev for FS_COMBINED_PROFILE.
3929   Abbv = std::make_shared<BitCodeAbbrev>();
3930   Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_PROFILE));
3931   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // valueid
3932   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // modid
3933   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // flags
3934   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // instcount
3935   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // fflags
3936   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // entrycount
3937   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // numrefs
3938   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // rorefcnt
3939   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // worefcnt
3940   // numrefs x valueid, n x (valueid, hotness)
3941   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3942   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3943   unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3944 
3945   // Abbrev for FS_COMBINED_GLOBALVAR_INIT_REFS.
3946   Abbv = std::make_shared<BitCodeAbbrev>();
3947   Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_GLOBALVAR_INIT_REFS));
3948   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // valueid
3949   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // modid
3950   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // flags
3951   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));    // valueids
3952   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3953   unsigned FSModRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3954 
3955   // Abbrev for FS_COMBINED_ALIAS.
3956   Abbv = std::make_shared<BitCodeAbbrev>();
3957   Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_ALIAS));
3958   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // valueid
3959   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // modid
3960   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // flags
3961   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // valueid
3962   unsigned FSAliasAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3963 
3964   // The aliases are emitted as a post-pass, and will point to the value
3965   // id of the aliasee. Save them in a vector for post-processing.
3966   SmallVector<AliasSummary *, 64> Aliases;
3967 
3968   // Save the value id for each summary for alias emission.
3969   DenseMap<const GlobalValueSummary *, unsigned> SummaryToValueIdMap;
3970 
3971   SmallVector<uint64_t, 64> NameVals;
3972 
3973   // Set that will be populated during call to writeFunctionTypeMetadataRecords
3974   // with the type ids referenced by this index file.
3975   std::set<GlobalValue::GUID> ReferencedTypeIds;
3976 
3977   // For local linkage, we also emit the original name separately
3978   // immediately after the record.
3979   auto MaybeEmitOriginalName = [&](GlobalValueSummary &S) {
3980     if (!GlobalValue::isLocalLinkage(S.linkage()))
3981       return;
3982     NameVals.push_back(S.getOriginalName());
3983     Stream.EmitRecord(bitc::FS_COMBINED_ORIGINAL_NAME, NameVals);
3984     NameVals.clear();
3985   };
3986 
3987   std::set<GlobalValue::GUID> DefOrUseGUIDs;
3988   forEachSummary([&](GVInfo I, bool IsAliasee) {
3989     GlobalValueSummary *S = I.second;
3990     assert(S);
3991     DefOrUseGUIDs.insert(I.first);
3992     for (const ValueInfo &VI : S->refs())
3993       DefOrUseGUIDs.insert(VI.getGUID());
3994 
3995     auto ValueId = getValueId(I.first);
3996     assert(ValueId);
3997     SummaryToValueIdMap[S] = *ValueId;
3998 
3999     // If this is invoked for an aliasee, we want to record the above
4000     // mapping, but then not emit a summary entry (if the aliasee is
4001     // to be imported, we will invoke this separately with IsAliasee=false).
4002     if (IsAliasee)
4003       return;
4004 
4005     if (auto *AS = dyn_cast<AliasSummary>(S)) {
4006       // Will process aliases as a post-pass because the reader wants all
4007       // global to be loaded first.
4008       Aliases.push_back(AS);
4009       return;
4010     }
4011 
4012     if (auto *VS = dyn_cast<GlobalVarSummary>(S)) {
4013       NameVals.push_back(*ValueId);
4014       NameVals.push_back(Index.getModuleId(VS->modulePath()));
4015       NameVals.push_back(getEncodedGVSummaryFlags(VS->flags()));
4016       NameVals.push_back(getEncodedGVarFlags(VS->varflags()));
4017       for (auto &RI : VS->refs()) {
4018         auto RefValueId = getValueId(RI.getGUID());
4019         if (!RefValueId)
4020           continue;
4021         NameVals.push_back(*RefValueId);
4022       }
4023 
4024       // Emit the finished record.
4025       Stream.EmitRecord(bitc::FS_COMBINED_GLOBALVAR_INIT_REFS, NameVals,
4026                         FSModRefsAbbrev);
4027       NameVals.clear();
4028       MaybeEmitOriginalName(*S);
4029       return;
4030     }
4031 
4032     auto *FS = cast<FunctionSummary>(S);
4033     writeFunctionTypeMetadataRecords(Stream, FS);
4034     getReferencedTypeIds(FS, ReferencedTypeIds);
4035 
4036     NameVals.push_back(*ValueId);
4037     NameVals.push_back(Index.getModuleId(FS->modulePath()));
4038     NameVals.push_back(getEncodedGVSummaryFlags(FS->flags()));
4039     NameVals.push_back(FS->instCount());
4040     NameVals.push_back(getEncodedFFlags(FS->fflags()));
4041     NameVals.push_back(FS->entryCount());
4042 
4043     // Fill in below
4044     NameVals.push_back(0); // numrefs
4045     NameVals.push_back(0); // rorefcnt
4046     NameVals.push_back(0); // worefcnt
4047 
4048     unsigned Count = 0, RORefCnt = 0, WORefCnt = 0;
4049     for (auto &RI : FS->refs()) {
4050       auto RefValueId = getValueId(RI.getGUID());
4051       if (!RefValueId)
4052         continue;
4053       NameVals.push_back(*RefValueId);
4054       if (RI.isReadOnly())
4055         RORefCnt++;
4056       else if (RI.isWriteOnly())
4057         WORefCnt++;
4058       Count++;
4059     }
4060     NameVals[6] = Count;
4061     NameVals[7] = RORefCnt;
4062     NameVals[8] = WORefCnt;
4063 
4064     bool HasProfileData = false;
4065     for (auto &EI : FS->calls()) {
4066       HasProfileData |=
4067           EI.second.getHotness() != CalleeInfo::HotnessType::Unknown;
4068       if (HasProfileData)
4069         break;
4070     }
4071 
4072     for (auto &EI : FS->calls()) {
4073       // If this GUID doesn't have a value id, it doesn't have a function
4074       // summary and we don't need to record any calls to it.
4075       GlobalValue::GUID GUID = EI.first.getGUID();
4076       auto CallValueId = getValueId(GUID);
4077       if (!CallValueId) {
4078         // For SamplePGO, the indirect call targets for local functions will
4079         // have its original name annotated in profile. We try to find the
4080         // corresponding PGOFuncName as the GUID.
4081         GUID = Index.getGUIDFromOriginalID(GUID);
4082         if (GUID == 0)
4083           continue;
4084         CallValueId = getValueId(GUID);
4085         if (!CallValueId)
4086           continue;
4087         // The mapping from OriginalId to GUID may return a GUID
4088         // that corresponds to a static variable. Filter it out here.
4089         // This can happen when
4090         // 1) There is a call to a library function which does not have
4091         // a CallValidId;
4092         // 2) There is a static variable with the  OriginalGUID identical
4093         // to the GUID of the library function in 1);
4094         // When this happens, the logic for SamplePGO kicks in and
4095         // the static variable in 2) will be found, which needs to be
4096         // filtered out.
4097         auto *GVSum = Index.getGlobalValueSummary(GUID, false);
4098         if (GVSum &&
4099             GVSum->getSummaryKind() == GlobalValueSummary::GlobalVarKind)
4100           continue;
4101       }
4102       NameVals.push_back(*CallValueId);
4103       if (HasProfileData)
4104         NameVals.push_back(static_cast<uint8_t>(EI.second.Hotness));
4105     }
4106 
4107     unsigned FSAbbrev = (HasProfileData ? FSCallsProfileAbbrev : FSCallsAbbrev);
4108     unsigned Code =
4109         (HasProfileData ? bitc::FS_COMBINED_PROFILE : bitc::FS_COMBINED);
4110 
4111     // Emit the finished record.
4112     Stream.EmitRecord(Code, NameVals, FSAbbrev);
4113     NameVals.clear();
4114     MaybeEmitOriginalName(*S);
4115   });
4116 
4117   for (auto *AS : Aliases) {
4118     auto AliasValueId = SummaryToValueIdMap[AS];
4119     assert(AliasValueId);
4120     NameVals.push_back(AliasValueId);
4121     NameVals.push_back(Index.getModuleId(AS->modulePath()));
4122     NameVals.push_back(getEncodedGVSummaryFlags(AS->flags()));
4123     auto AliaseeValueId = SummaryToValueIdMap[&AS->getAliasee()];
4124     assert(AliaseeValueId);
4125     NameVals.push_back(AliaseeValueId);
4126 
4127     // Emit the finished record.
4128     Stream.EmitRecord(bitc::FS_COMBINED_ALIAS, NameVals, FSAliasAbbrev);
4129     NameVals.clear();
4130     MaybeEmitOriginalName(*AS);
4131 
4132     if (auto *FS = dyn_cast<FunctionSummary>(&AS->getAliasee()))
4133       getReferencedTypeIds(FS, ReferencedTypeIds);
4134   }
4135 
4136   if (!Index.cfiFunctionDefs().empty()) {
4137     for (auto &S : Index.cfiFunctionDefs()) {
4138       if (DefOrUseGUIDs.count(
4139               GlobalValue::getGUID(GlobalValue::dropLLVMManglingEscape(S)))) {
4140         NameVals.push_back(StrtabBuilder.add(S));
4141         NameVals.push_back(S.size());
4142       }
4143     }
4144     if (!NameVals.empty()) {
4145       Stream.EmitRecord(bitc::FS_CFI_FUNCTION_DEFS, NameVals);
4146       NameVals.clear();
4147     }
4148   }
4149 
4150   if (!Index.cfiFunctionDecls().empty()) {
4151     for (auto &S : Index.cfiFunctionDecls()) {
4152       if (DefOrUseGUIDs.count(
4153               GlobalValue::getGUID(GlobalValue::dropLLVMManglingEscape(S)))) {
4154         NameVals.push_back(StrtabBuilder.add(S));
4155         NameVals.push_back(S.size());
4156       }
4157     }
4158     if (!NameVals.empty()) {
4159       Stream.EmitRecord(bitc::FS_CFI_FUNCTION_DECLS, NameVals);
4160       NameVals.clear();
4161     }
4162   }
4163 
4164   // Walk the GUIDs that were referenced, and write the
4165   // corresponding type id records.
4166   for (auto &T : ReferencedTypeIds) {
4167     auto TidIter = Index.typeIds().equal_range(T);
4168     for (auto It = TidIter.first; It != TidIter.second; ++It) {
4169       writeTypeIdSummaryRecord(NameVals, StrtabBuilder, It->second.first,
4170                                It->second.second);
4171       Stream.EmitRecord(bitc::FS_TYPE_ID, NameVals);
4172       NameVals.clear();
4173     }
4174   }
4175 
4176   Stream.ExitBlock();
4177 }
4178 
4179 /// Create the "IDENTIFICATION_BLOCK_ID" containing a single string with the
4180 /// current llvm version, and a record for the epoch number.
4181 static void writeIdentificationBlock(BitstreamWriter &Stream) {
4182   Stream.EnterSubblock(bitc::IDENTIFICATION_BLOCK_ID, 5);
4183 
4184   // Write the "user readable" string identifying the bitcode producer
4185   auto Abbv = std::make_shared<BitCodeAbbrev>();
4186   Abbv->Add(BitCodeAbbrevOp(bitc::IDENTIFICATION_CODE_STRING));
4187   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4188   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
4189   auto StringAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4190   writeStringRecord(Stream, bitc::IDENTIFICATION_CODE_STRING,
4191                     "LLVM" LLVM_VERSION_STRING, StringAbbrev);
4192 
4193   // Write the epoch version
4194   Abbv = std::make_shared<BitCodeAbbrev>();
4195   Abbv->Add(BitCodeAbbrevOp(bitc::IDENTIFICATION_CODE_EPOCH));
4196   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
4197   auto EpochAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4198   SmallVector<unsigned, 1> Vals = {bitc::BITCODE_CURRENT_EPOCH};
4199   Stream.EmitRecord(bitc::IDENTIFICATION_CODE_EPOCH, Vals, EpochAbbrev);
4200   Stream.ExitBlock();
4201 }
4202 
4203 void ModuleBitcodeWriter::writeModuleHash(size_t BlockStartPos) {
4204   // Emit the module's hash.
4205   // MODULE_CODE_HASH: [5*i32]
4206   if (GenerateHash) {
4207     uint32_t Vals[5];
4208     Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&(Buffer)[BlockStartPos],
4209                                     Buffer.size() - BlockStartPos));
4210     StringRef Hash = Hasher.result();
4211     for (int Pos = 0; Pos < 20; Pos += 4) {
4212       Vals[Pos / 4] = support::endian::read32be(Hash.data() + Pos);
4213     }
4214 
4215     // Emit the finished record.
4216     Stream.EmitRecord(bitc::MODULE_CODE_HASH, Vals);
4217 
4218     if (ModHash)
4219       // Save the written hash value.
4220       llvm::copy(Vals, std::begin(*ModHash));
4221   }
4222 }
4223 
4224 void ModuleBitcodeWriter::write() {
4225   writeIdentificationBlock(Stream);
4226 
4227   Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
4228   size_t BlockStartPos = Buffer.size();
4229 
4230   writeModuleVersion();
4231 
4232   // Emit blockinfo, which defines the standard abbreviations etc.
4233   writeBlockInfo();
4234 
4235   // Emit information describing all of the types in the module.
4236   writeTypeTable();
4237 
4238   // Emit information about attribute groups.
4239   writeAttributeGroupTable();
4240 
4241   // Emit information about parameter attributes.
4242   writeAttributeTable();
4243 
4244   writeComdats();
4245 
4246   // Emit top-level description of module, including target triple, inline asm,
4247   // descriptors for global variables, and function prototype info.
4248   writeModuleInfo();
4249 
4250   // Emit constants.
4251   writeModuleConstants();
4252 
4253   // Emit metadata kind names.
4254   writeModuleMetadataKinds();
4255 
4256   // Emit metadata.
4257   writeModuleMetadata();
4258 
4259   // Emit module-level use-lists.
4260   if (VE.shouldPreserveUseListOrder())
4261     writeUseListBlock(nullptr);
4262 
4263   writeOperandBundleTags();
4264   writeSyncScopeNames();
4265 
4266   // Emit function bodies.
4267   DenseMap<const Function *, uint64_t> FunctionToBitcodeIndex;
4268   for (Module::const_iterator F = M.begin(), E = M.end(); F != E; ++F)
4269     if (!F->isDeclaration())
4270       writeFunction(*F, FunctionToBitcodeIndex);
4271 
4272   // Need to write after the above call to WriteFunction which populates
4273   // the summary information in the index.
4274   if (Index)
4275     writePerModuleGlobalValueSummary();
4276 
4277   writeGlobalValueSymbolTable(FunctionToBitcodeIndex);
4278 
4279   writeModuleHash(BlockStartPos);
4280 
4281   Stream.ExitBlock();
4282 }
4283 
4284 static void writeInt32ToBuffer(uint32_t Value, SmallVectorImpl<char> &Buffer,
4285                                uint32_t &Position) {
4286   support::endian::write32le(&Buffer[Position], Value);
4287   Position += 4;
4288 }
4289 
4290 /// If generating a bc file on darwin, we have to emit a
4291 /// header and trailer to make it compatible with the system archiver.  To do
4292 /// this we emit the following header, and then emit a trailer that pads the
4293 /// file out to be a multiple of 16 bytes.
4294 ///
4295 /// struct bc_header {
4296 ///   uint32_t Magic;         // 0x0B17C0DE
4297 ///   uint32_t Version;       // Version, currently always 0.
4298 ///   uint32_t BitcodeOffset; // Offset to traditional bitcode file.
4299 ///   uint32_t BitcodeSize;   // Size of traditional bitcode file.
4300 ///   uint32_t CPUType;       // CPU specifier.
4301 ///   ... potentially more later ...
4302 /// };
4303 static void emitDarwinBCHeaderAndTrailer(SmallVectorImpl<char> &Buffer,
4304                                          const Triple &TT) {
4305   unsigned CPUType = ~0U;
4306 
4307   // Match x86_64-*, i[3-9]86-*, powerpc-*, powerpc64-*, arm-*, thumb-*,
4308   // armv[0-9]-*, thumbv[0-9]-*, armv5te-*, or armv6t2-*. The CPUType is a magic
4309   // number from /usr/include/mach/machine.h.  It is ok to reproduce the
4310   // specific constants here because they are implicitly part of the Darwin ABI.
4311   enum {
4312     DARWIN_CPU_ARCH_ABI64      = 0x01000000,
4313     DARWIN_CPU_TYPE_X86        = 7,
4314     DARWIN_CPU_TYPE_ARM        = 12,
4315     DARWIN_CPU_TYPE_POWERPC    = 18
4316   };
4317 
4318   Triple::ArchType Arch = TT.getArch();
4319   if (Arch == Triple::x86_64)
4320     CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64;
4321   else if (Arch == Triple::x86)
4322     CPUType = DARWIN_CPU_TYPE_X86;
4323   else if (Arch == Triple::ppc)
4324     CPUType = DARWIN_CPU_TYPE_POWERPC;
4325   else if (Arch == Triple::ppc64)
4326     CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64;
4327   else if (Arch == Triple::arm || Arch == Triple::thumb)
4328     CPUType = DARWIN_CPU_TYPE_ARM;
4329 
4330   // Traditional Bitcode starts after header.
4331   assert(Buffer.size() >= BWH_HeaderSize &&
4332          "Expected header size to be reserved");
4333   unsigned BCOffset = BWH_HeaderSize;
4334   unsigned BCSize = Buffer.size() - BWH_HeaderSize;
4335 
4336   // Write the magic and version.
4337   unsigned Position = 0;
4338   writeInt32ToBuffer(0x0B17C0DE, Buffer, Position);
4339   writeInt32ToBuffer(0, Buffer, Position); // Version.
4340   writeInt32ToBuffer(BCOffset, Buffer, Position);
4341   writeInt32ToBuffer(BCSize, Buffer, Position);
4342   writeInt32ToBuffer(CPUType, Buffer, Position);
4343 
4344   // If the file is not a multiple of 16 bytes, insert dummy padding.
4345   while (Buffer.size() & 15)
4346     Buffer.push_back(0);
4347 }
4348 
4349 /// Helper to write the header common to all bitcode files.
4350 static void writeBitcodeHeader(BitstreamWriter &Stream) {
4351   // Emit the file header.
4352   Stream.Emit((unsigned)'B', 8);
4353   Stream.Emit((unsigned)'C', 8);
4354   Stream.Emit(0x0, 4);
4355   Stream.Emit(0xC, 4);
4356   Stream.Emit(0xE, 4);
4357   Stream.Emit(0xD, 4);
4358 }
4359 
4360 BitcodeWriter::BitcodeWriter(SmallVectorImpl<char> &Buffer)
4361     : Buffer(Buffer), Stream(new BitstreamWriter(Buffer)) {
4362   writeBitcodeHeader(*Stream);
4363 }
4364 
4365 BitcodeWriter::~BitcodeWriter() { assert(WroteStrtab); }
4366 
4367 void BitcodeWriter::writeBlob(unsigned Block, unsigned Record, StringRef Blob) {
4368   Stream->EnterSubblock(Block, 3);
4369 
4370   auto Abbv = std::make_shared<BitCodeAbbrev>();
4371   Abbv->Add(BitCodeAbbrevOp(Record));
4372   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
4373   auto AbbrevNo = Stream->EmitAbbrev(std::move(Abbv));
4374 
4375   Stream->EmitRecordWithBlob(AbbrevNo, ArrayRef<uint64_t>{Record}, Blob);
4376 
4377   Stream->ExitBlock();
4378 }
4379 
4380 void BitcodeWriter::writeSymtab() {
4381   assert(!WroteStrtab && !WroteSymtab);
4382 
4383   // If any module has module-level inline asm, we will require a registered asm
4384   // parser for the target so that we can create an accurate symbol table for
4385   // the module.
4386   for (Module *M : Mods) {
4387     if (M->getModuleInlineAsm().empty())
4388       continue;
4389 
4390     std::string Err;
4391     const Triple TT(M->getTargetTriple());
4392     const Target *T = TargetRegistry::lookupTarget(TT.str(), Err);
4393     if (!T || !T->hasMCAsmParser())
4394       return;
4395   }
4396 
4397   WroteSymtab = true;
4398   SmallVector<char, 0> Symtab;
4399   // The irsymtab::build function may be unable to create a symbol table if the
4400   // module is malformed (e.g. it contains an invalid alias). Writing a symbol
4401   // table is not required for correctness, but we still want to be able to
4402   // write malformed modules to bitcode files, so swallow the error.
4403   if (Error E = irsymtab::build(Mods, Symtab, StrtabBuilder, Alloc)) {
4404     consumeError(std::move(E));
4405     return;
4406   }
4407 
4408   writeBlob(bitc::SYMTAB_BLOCK_ID, bitc::SYMTAB_BLOB,
4409             {Symtab.data(), Symtab.size()});
4410 }
4411 
4412 void BitcodeWriter::writeStrtab() {
4413   assert(!WroteStrtab);
4414 
4415   std::vector<char> Strtab;
4416   StrtabBuilder.finalizeInOrder();
4417   Strtab.resize(StrtabBuilder.getSize());
4418   StrtabBuilder.write((uint8_t *)Strtab.data());
4419 
4420   writeBlob(bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB,
4421             {Strtab.data(), Strtab.size()});
4422 
4423   WroteStrtab = true;
4424 }
4425 
4426 void BitcodeWriter::copyStrtab(StringRef Strtab) {
4427   writeBlob(bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB, Strtab);
4428   WroteStrtab = true;
4429 }
4430 
4431 void BitcodeWriter::writeModule(const Module &M,
4432                                 bool ShouldPreserveUseListOrder,
4433                                 const ModuleSummaryIndex *Index,
4434                                 bool GenerateHash, ModuleHash *ModHash) {
4435   assert(!WroteStrtab);
4436 
4437   // The Mods vector is used by irsymtab::build, which requires non-const
4438   // Modules in case it needs to materialize metadata. But the bitcode writer
4439   // requires that the module is materialized, so we can cast to non-const here,
4440   // after checking that it is in fact materialized.
4441   assert(M.isMaterialized());
4442   Mods.push_back(const_cast<Module *>(&M));
4443 
4444   ModuleBitcodeWriter ModuleWriter(M, Buffer, StrtabBuilder, *Stream,
4445                                    ShouldPreserveUseListOrder, Index,
4446                                    GenerateHash, ModHash);
4447   ModuleWriter.write();
4448 }
4449 
4450 void BitcodeWriter::writeIndex(
4451     const ModuleSummaryIndex *Index,
4452     const std::map<std::string, GVSummaryMapTy> *ModuleToSummariesForIndex) {
4453   IndexBitcodeWriter IndexWriter(*Stream, StrtabBuilder, *Index,
4454                                  ModuleToSummariesForIndex);
4455   IndexWriter.write();
4456 }
4457 
4458 /// Write the specified module to the specified output stream.
4459 void llvm::WriteBitcodeToFile(const Module &M, raw_ostream &Out,
4460                               bool ShouldPreserveUseListOrder,
4461                               const ModuleSummaryIndex *Index,
4462                               bool GenerateHash, ModuleHash *ModHash) {
4463   SmallVector<char, 0> Buffer;
4464   Buffer.reserve(256*1024);
4465 
4466   // If this is darwin or another generic macho target, reserve space for the
4467   // header.
4468   Triple TT(M.getTargetTriple());
4469   if (TT.isOSDarwin() || TT.isOSBinFormatMachO())
4470     Buffer.insert(Buffer.begin(), BWH_HeaderSize, 0);
4471 
4472   BitcodeWriter Writer(Buffer);
4473   Writer.writeModule(M, ShouldPreserveUseListOrder, Index, GenerateHash,
4474                      ModHash);
4475   Writer.writeSymtab();
4476   Writer.writeStrtab();
4477 
4478   if (TT.isOSDarwin() || TT.isOSBinFormatMachO())
4479     emitDarwinBCHeaderAndTrailer(Buffer, TT);
4480 
4481   // Write the generated bitstream to "Out".
4482   Out.write((char*)&Buffer.front(), Buffer.size());
4483 }
4484 
4485 void IndexBitcodeWriter::write() {
4486   Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
4487 
4488   writeModuleVersion();
4489 
4490   // Write the module paths in the combined index.
4491   writeModStrings();
4492 
4493   // Write the summary combined index records.
4494   writeCombinedGlobalValueSummary();
4495 
4496   Stream.ExitBlock();
4497 }
4498 
4499 // Write the specified module summary index to the given raw output stream,
4500 // where it will be written in a new bitcode block. This is used when
4501 // writing the combined index file for ThinLTO. When writing a subset of the
4502 // index for a distributed backend, provide a \p ModuleToSummariesForIndex map.
4503 void llvm::WriteIndexToFile(
4504     const ModuleSummaryIndex &Index, raw_ostream &Out,
4505     const std::map<std::string, GVSummaryMapTy> *ModuleToSummariesForIndex) {
4506   SmallVector<char, 0> Buffer;
4507   Buffer.reserve(256 * 1024);
4508 
4509   BitcodeWriter Writer(Buffer);
4510   Writer.writeIndex(&Index, ModuleToSummariesForIndex);
4511   Writer.writeStrtab();
4512 
4513   Out.write((char *)&Buffer.front(), Buffer.size());
4514 }
4515 
4516 namespace {
4517 
4518 /// Class to manage the bitcode writing for a thin link bitcode file.
4519 class ThinLinkBitcodeWriter : public ModuleBitcodeWriterBase {
4520   /// ModHash is for use in ThinLTO incremental build, generated while writing
4521   /// the module bitcode file.
4522   const ModuleHash *ModHash;
4523 
4524 public:
4525   ThinLinkBitcodeWriter(const Module &M, StringTableBuilder &StrtabBuilder,
4526                         BitstreamWriter &Stream,
4527                         const ModuleSummaryIndex &Index,
4528                         const ModuleHash &ModHash)
4529       : ModuleBitcodeWriterBase(M, StrtabBuilder, Stream,
4530                                 /*ShouldPreserveUseListOrder=*/false, &Index),
4531         ModHash(&ModHash) {}
4532 
4533   void write();
4534 
4535 private:
4536   void writeSimplifiedModuleInfo();
4537 };
4538 
4539 } // end anonymous namespace
4540 
4541 // This function writes a simpilified module info for thin link bitcode file.
4542 // It only contains the source file name along with the name(the offset and
4543 // size in strtab) and linkage for global values. For the global value info
4544 // entry, in order to keep linkage at offset 5, there are three zeros used
4545 // as padding.
4546 void ThinLinkBitcodeWriter::writeSimplifiedModuleInfo() {
4547   SmallVector<unsigned, 64> Vals;
4548   // Emit the module's source file name.
4549   {
4550     StringEncoding Bits = getStringEncoding(M.getSourceFileName());
4551     BitCodeAbbrevOp AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8);
4552     if (Bits == SE_Char6)
4553       AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Char6);
4554     else if (Bits == SE_Fixed7)
4555       AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7);
4556 
4557     // MODULE_CODE_SOURCE_FILENAME: [namechar x N]
4558     auto Abbv = std::make_shared<BitCodeAbbrev>();
4559     Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_SOURCE_FILENAME));
4560     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4561     Abbv->Add(AbbrevOpToUse);
4562     unsigned FilenameAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4563 
4564     for (const auto P : M.getSourceFileName())
4565       Vals.push_back((unsigned char)P);
4566 
4567     Stream.EmitRecord(bitc::MODULE_CODE_SOURCE_FILENAME, Vals, FilenameAbbrev);
4568     Vals.clear();
4569   }
4570 
4571   // Emit the global variable information.
4572   for (const GlobalVariable &GV : M.globals()) {
4573     // GLOBALVAR: [strtab offset, strtab size, 0, 0, 0, linkage]
4574     Vals.push_back(StrtabBuilder.add(GV.getName()));
4575     Vals.push_back(GV.getName().size());
4576     Vals.push_back(0);
4577     Vals.push_back(0);
4578     Vals.push_back(0);
4579     Vals.push_back(getEncodedLinkage(GV));
4580 
4581     Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals);
4582     Vals.clear();
4583   }
4584 
4585   // Emit the function proto information.
4586   for (const Function &F : M) {
4587     // FUNCTION:  [strtab offset, strtab size, 0, 0, 0, linkage]
4588     Vals.push_back(StrtabBuilder.add(F.getName()));
4589     Vals.push_back(F.getName().size());
4590     Vals.push_back(0);
4591     Vals.push_back(0);
4592     Vals.push_back(0);
4593     Vals.push_back(getEncodedLinkage(F));
4594 
4595     Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals);
4596     Vals.clear();
4597   }
4598 
4599   // Emit the alias information.
4600   for (const GlobalAlias &A : M.aliases()) {
4601     // ALIAS: [strtab offset, strtab size, 0, 0, 0, linkage]
4602     Vals.push_back(StrtabBuilder.add(A.getName()));
4603     Vals.push_back(A.getName().size());
4604     Vals.push_back(0);
4605     Vals.push_back(0);
4606     Vals.push_back(0);
4607     Vals.push_back(getEncodedLinkage(A));
4608 
4609     Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals);
4610     Vals.clear();
4611   }
4612 
4613   // Emit the ifunc information.
4614   for (const GlobalIFunc &I : M.ifuncs()) {
4615     // IFUNC: [strtab offset, strtab size, 0, 0, 0, linkage]
4616     Vals.push_back(StrtabBuilder.add(I.getName()));
4617     Vals.push_back(I.getName().size());
4618     Vals.push_back(0);
4619     Vals.push_back(0);
4620     Vals.push_back(0);
4621     Vals.push_back(getEncodedLinkage(I));
4622 
4623     Stream.EmitRecord(bitc::MODULE_CODE_IFUNC, Vals);
4624     Vals.clear();
4625   }
4626 }
4627 
4628 void ThinLinkBitcodeWriter::write() {
4629   Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
4630 
4631   writeModuleVersion();
4632 
4633   writeSimplifiedModuleInfo();
4634 
4635   writePerModuleGlobalValueSummary();
4636 
4637   // Write module hash.
4638   Stream.EmitRecord(bitc::MODULE_CODE_HASH, ArrayRef<uint32_t>(*ModHash));
4639 
4640   Stream.ExitBlock();
4641 }
4642 
4643 void BitcodeWriter::writeThinLinkBitcode(const Module &M,
4644                                          const ModuleSummaryIndex &Index,
4645                                          const ModuleHash &ModHash) {
4646   assert(!WroteStrtab);
4647 
4648   // The Mods vector is used by irsymtab::build, which requires non-const
4649   // Modules in case it needs to materialize metadata. But the bitcode writer
4650   // requires that the module is materialized, so we can cast to non-const here,
4651   // after checking that it is in fact materialized.
4652   assert(M.isMaterialized());
4653   Mods.push_back(const_cast<Module *>(&M));
4654 
4655   ThinLinkBitcodeWriter ThinLinkWriter(M, StrtabBuilder, *Stream, Index,
4656                                        ModHash);
4657   ThinLinkWriter.write();
4658 }
4659 
4660 // Write the specified thin link bitcode file to the given raw output stream,
4661 // where it will be written in a new bitcode block. This is used when
4662 // writing the per-module index file for ThinLTO.
4663 void llvm::WriteThinLinkBitcodeToFile(const Module &M, raw_ostream &Out,
4664                                       const ModuleSummaryIndex &Index,
4665                                       const ModuleHash &ModHash) {
4666   SmallVector<char, 0> Buffer;
4667   Buffer.reserve(256 * 1024);
4668 
4669   BitcodeWriter Writer(Buffer);
4670   Writer.writeThinLinkBitcode(M, Index, ModHash);
4671   Writer.writeSymtab();
4672   Writer.writeStrtab();
4673 
4674   Out.write((char *)&Buffer.front(), Buffer.size());
4675 }
4676