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