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