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