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