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