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