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