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