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