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