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