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