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