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