xref: /freebsd/contrib/llvm-project/llvm/lib/Bitcode/Writer/BitcodeWriter.cpp (revision 8ddb146abcdf061be9f2c0db7e391697dafad85c)
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->getNonOpaquePointerElementType()));
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(VE.getMetadataOrNullID(N->getStringLocationExp()));
1661   Record.push_back(N->getSizeInBits());
1662   Record.push_back(N->getAlignInBits());
1663   Record.push_back(N->getEncoding());
1664 
1665   Stream.EmitRecord(bitc::METADATA_STRING_TYPE, Record, Abbrev);
1666   Record.clear();
1667 }
1668 
1669 void ModuleBitcodeWriter::writeDIDerivedType(const DIDerivedType *N,
1670                                              SmallVectorImpl<uint64_t> &Record,
1671                                              unsigned Abbrev) {
1672   Record.push_back(N->isDistinct());
1673   Record.push_back(N->getTag());
1674   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1675   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1676   Record.push_back(N->getLine());
1677   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1678   Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
1679   Record.push_back(N->getSizeInBits());
1680   Record.push_back(N->getAlignInBits());
1681   Record.push_back(N->getOffsetInBits());
1682   Record.push_back(N->getFlags());
1683   Record.push_back(VE.getMetadataOrNullID(N->getExtraData()));
1684 
1685   // DWARF address space is encoded as N->getDWARFAddressSpace() + 1. 0 means
1686   // that there is no DWARF address space associated with DIDerivedType.
1687   if (const auto &DWARFAddressSpace = N->getDWARFAddressSpace())
1688     Record.push_back(*DWARFAddressSpace + 1);
1689   else
1690     Record.push_back(0);
1691 
1692   Record.push_back(VE.getMetadataOrNullID(N->getAnnotations().get()));
1693 
1694   Stream.EmitRecord(bitc::METADATA_DERIVED_TYPE, Record, Abbrev);
1695   Record.clear();
1696 }
1697 
1698 void ModuleBitcodeWriter::writeDICompositeType(
1699     const DICompositeType *N, SmallVectorImpl<uint64_t> &Record,
1700     unsigned Abbrev) {
1701   const unsigned IsNotUsedInOldTypeRef = 0x2;
1702   Record.push_back(IsNotUsedInOldTypeRef | (unsigned)N->isDistinct());
1703   Record.push_back(N->getTag());
1704   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1705   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1706   Record.push_back(N->getLine());
1707   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1708   Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
1709   Record.push_back(N->getSizeInBits());
1710   Record.push_back(N->getAlignInBits());
1711   Record.push_back(N->getOffsetInBits());
1712   Record.push_back(N->getFlags());
1713   Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
1714   Record.push_back(N->getRuntimeLang());
1715   Record.push_back(VE.getMetadataOrNullID(N->getVTableHolder()));
1716   Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
1717   Record.push_back(VE.getMetadataOrNullID(N->getRawIdentifier()));
1718   Record.push_back(VE.getMetadataOrNullID(N->getDiscriminator()));
1719   Record.push_back(VE.getMetadataOrNullID(N->getRawDataLocation()));
1720   Record.push_back(VE.getMetadataOrNullID(N->getRawAssociated()));
1721   Record.push_back(VE.getMetadataOrNullID(N->getRawAllocated()));
1722   Record.push_back(VE.getMetadataOrNullID(N->getRawRank()));
1723   Record.push_back(VE.getMetadataOrNullID(N->getAnnotations().get()));
1724 
1725   Stream.EmitRecord(bitc::METADATA_COMPOSITE_TYPE, Record, Abbrev);
1726   Record.clear();
1727 }
1728 
1729 void ModuleBitcodeWriter::writeDISubroutineType(
1730     const DISubroutineType *N, SmallVectorImpl<uint64_t> &Record,
1731     unsigned Abbrev) {
1732   const unsigned HasNoOldTypeRefs = 0x2;
1733   Record.push_back(HasNoOldTypeRefs | (unsigned)N->isDistinct());
1734   Record.push_back(N->getFlags());
1735   Record.push_back(VE.getMetadataOrNullID(N->getTypeArray().get()));
1736   Record.push_back(N->getCC());
1737 
1738   Stream.EmitRecord(bitc::METADATA_SUBROUTINE_TYPE, Record, Abbrev);
1739   Record.clear();
1740 }
1741 
1742 void ModuleBitcodeWriter::writeDIFile(const DIFile *N,
1743                                       SmallVectorImpl<uint64_t> &Record,
1744                                       unsigned Abbrev) {
1745   Record.push_back(N->isDistinct());
1746   Record.push_back(VE.getMetadataOrNullID(N->getRawFilename()));
1747   Record.push_back(VE.getMetadataOrNullID(N->getRawDirectory()));
1748   if (N->getRawChecksum()) {
1749     Record.push_back(N->getRawChecksum()->Kind);
1750     Record.push_back(VE.getMetadataOrNullID(N->getRawChecksum()->Value));
1751   } else {
1752     // Maintain backwards compatibility with the old internal representation of
1753     // CSK_None in ChecksumKind by writing nulls here when Checksum is None.
1754     Record.push_back(0);
1755     Record.push_back(VE.getMetadataOrNullID(nullptr));
1756   }
1757   auto Source = N->getRawSource();
1758   if (Source)
1759     Record.push_back(VE.getMetadataOrNullID(*Source));
1760 
1761   Stream.EmitRecord(bitc::METADATA_FILE, Record, Abbrev);
1762   Record.clear();
1763 }
1764 
1765 void ModuleBitcodeWriter::writeDICompileUnit(const DICompileUnit *N,
1766                                              SmallVectorImpl<uint64_t> &Record,
1767                                              unsigned Abbrev) {
1768   assert(N->isDistinct() && "Expected distinct compile units");
1769   Record.push_back(/* IsDistinct */ true);
1770   Record.push_back(N->getSourceLanguage());
1771   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1772   Record.push_back(VE.getMetadataOrNullID(N->getRawProducer()));
1773   Record.push_back(N->isOptimized());
1774   Record.push_back(VE.getMetadataOrNullID(N->getRawFlags()));
1775   Record.push_back(N->getRuntimeVersion());
1776   Record.push_back(VE.getMetadataOrNullID(N->getRawSplitDebugFilename()));
1777   Record.push_back(N->getEmissionKind());
1778   Record.push_back(VE.getMetadataOrNullID(N->getEnumTypes().get()));
1779   Record.push_back(VE.getMetadataOrNullID(N->getRetainedTypes().get()));
1780   Record.push_back(/* subprograms */ 0);
1781   Record.push_back(VE.getMetadataOrNullID(N->getGlobalVariables().get()));
1782   Record.push_back(VE.getMetadataOrNullID(N->getImportedEntities().get()));
1783   Record.push_back(N->getDWOId());
1784   Record.push_back(VE.getMetadataOrNullID(N->getMacros().get()));
1785   Record.push_back(N->getSplitDebugInlining());
1786   Record.push_back(N->getDebugInfoForProfiling());
1787   Record.push_back((unsigned)N->getNameTableKind());
1788   Record.push_back(N->getRangesBaseAddress());
1789   Record.push_back(VE.getMetadataOrNullID(N->getRawSysRoot()));
1790   Record.push_back(VE.getMetadataOrNullID(N->getRawSDK()));
1791 
1792   Stream.EmitRecord(bitc::METADATA_COMPILE_UNIT, Record, Abbrev);
1793   Record.clear();
1794 }
1795 
1796 void ModuleBitcodeWriter::writeDISubprogram(const DISubprogram *N,
1797                                             SmallVectorImpl<uint64_t> &Record,
1798                                             unsigned Abbrev) {
1799   const uint64_t HasUnitFlag = 1 << 1;
1800   const uint64_t HasSPFlagsFlag = 1 << 2;
1801   Record.push_back(uint64_t(N->isDistinct()) | HasUnitFlag | HasSPFlagsFlag);
1802   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1803   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1804   Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
1805   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1806   Record.push_back(N->getLine());
1807   Record.push_back(VE.getMetadataOrNullID(N->getType()));
1808   Record.push_back(N->getScopeLine());
1809   Record.push_back(VE.getMetadataOrNullID(N->getContainingType()));
1810   Record.push_back(N->getSPFlags());
1811   Record.push_back(N->getVirtualIndex());
1812   Record.push_back(N->getFlags());
1813   Record.push_back(VE.getMetadataOrNullID(N->getRawUnit()));
1814   Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
1815   Record.push_back(VE.getMetadataOrNullID(N->getDeclaration()));
1816   Record.push_back(VE.getMetadataOrNullID(N->getRetainedNodes().get()));
1817   Record.push_back(N->getThisAdjustment());
1818   Record.push_back(VE.getMetadataOrNullID(N->getThrownTypes().get()));
1819   Record.push_back(VE.getMetadataOrNullID(N->getAnnotations().get()));
1820 
1821   Stream.EmitRecord(bitc::METADATA_SUBPROGRAM, Record, Abbrev);
1822   Record.clear();
1823 }
1824 
1825 void ModuleBitcodeWriter::writeDILexicalBlock(const DILexicalBlock *N,
1826                                               SmallVectorImpl<uint64_t> &Record,
1827                                               unsigned Abbrev) {
1828   Record.push_back(N->isDistinct());
1829   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1830   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1831   Record.push_back(N->getLine());
1832   Record.push_back(N->getColumn());
1833 
1834   Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK, Record, Abbrev);
1835   Record.clear();
1836 }
1837 
1838 void ModuleBitcodeWriter::writeDILexicalBlockFile(
1839     const DILexicalBlockFile *N, SmallVectorImpl<uint64_t> &Record,
1840     unsigned Abbrev) {
1841   Record.push_back(N->isDistinct());
1842   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1843   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1844   Record.push_back(N->getDiscriminator());
1845 
1846   Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK_FILE, Record, Abbrev);
1847   Record.clear();
1848 }
1849 
1850 void ModuleBitcodeWriter::writeDICommonBlock(const DICommonBlock *N,
1851                                              SmallVectorImpl<uint64_t> &Record,
1852                                              unsigned Abbrev) {
1853   Record.push_back(N->isDistinct());
1854   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1855   Record.push_back(VE.getMetadataOrNullID(N->getDecl()));
1856   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1857   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1858   Record.push_back(N->getLineNo());
1859 
1860   Stream.EmitRecord(bitc::METADATA_COMMON_BLOCK, Record, Abbrev);
1861   Record.clear();
1862 }
1863 
1864 void ModuleBitcodeWriter::writeDINamespace(const DINamespace *N,
1865                                            SmallVectorImpl<uint64_t> &Record,
1866                                            unsigned Abbrev) {
1867   Record.push_back(N->isDistinct() | N->getExportSymbols() << 1);
1868   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1869   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1870 
1871   Stream.EmitRecord(bitc::METADATA_NAMESPACE, Record, Abbrev);
1872   Record.clear();
1873 }
1874 
1875 void ModuleBitcodeWriter::writeDIMacro(const DIMacro *N,
1876                                        SmallVectorImpl<uint64_t> &Record,
1877                                        unsigned Abbrev) {
1878   Record.push_back(N->isDistinct());
1879   Record.push_back(N->getMacinfoType());
1880   Record.push_back(N->getLine());
1881   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1882   Record.push_back(VE.getMetadataOrNullID(N->getRawValue()));
1883 
1884   Stream.EmitRecord(bitc::METADATA_MACRO, Record, Abbrev);
1885   Record.clear();
1886 }
1887 
1888 void ModuleBitcodeWriter::writeDIMacroFile(const DIMacroFile *N,
1889                                            SmallVectorImpl<uint64_t> &Record,
1890                                            unsigned Abbrev) {
1891   Record.push_back(N->isDistinct());
1892   Record.push_back(N->getMacinfoType());
1893   Record.push_back(N->getLine());
1894   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1895   Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
1896 
1897   Stream.EmitRecord(bitc::METADATA_MACRO_FILE, Record, Abbrev);
1898   Record.clear();
1899 }
1900 
1901 void ModuleBitcodeWriter::writeDIArgList(const DIArgList *N,
1902                                          SmallVectorImpl<uint64_t> &Record,
1903                                          unsigned Abbrev) {
1904   Record.reserve(N->getArgs().size());
1905   for (ValueAsMetadata *MD : N->getArgs())
1906     Record.push_back(VE.getMetadataID(MD));
1907 
1908   Stream.EmitRecord(bitc::METADATA_ARG_LIST, Record, Abbrev);
1909   Record.clear();
1910 }
1911 
1912 void ModuleBitcodeWriter::writeDIModule(const DIModule *N,
1913                                         SmallVectorImpl<uint64_t> &Record,
1914                                         unsigned Abbrev) {
1915   Record.push_back(N->isDistinct());
1916   for (auto &I : N->operands())
1917     Record.push_back(VE.getMetadataOrNullID(I));
1918   Record.push_back(N->getLineNo());
1919   Record.push_back(N->getIsDecl());
1920 
1921   Stream.EmitRecord(bitc::METADATA_MODULE, Record, Abbrev);
1922   Record.clear();
1923 }
1924 
1925 void ModuleBitcodeWriter::writeDITemplateTypeParameter(
1926     const DITemplateTypeParameter *N, SmallVectorImpl<uint64_t> &Record,
1927     unsigned Abbrev) {
1928   Record.push_back(N->isDistinct());
1929   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1930   Record.push_back(VE.getMetadataOrNullID(N->getType()));
1931   Record.push_back(N->isDefault());
1932 
1933   Stream.EmitRecord(bitc::METADATA_TEMPLATE_TYPE, Record, Abbrev);
1934   Record.clear();
1935 }
1936 
1937 void ModuleBitcodeWriter::writeDITemplateValueParameter(
1938     const DITemplateValueParameter *N, SmallVectorImpl<uint64_t> &Record,
1939     unsigned Abbrev) {
1940   Record.push_back(N->isDistinct());
1941   Record.push_back(N->getTag());
1942   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1943   Record.push_back(VE.getMetadataOrNullID(N->getType()));
1944   Record.push_back(N->isDefault());
1945   Record.push_back(VE.getMetadataOrNullID(N->getValue()));
1946 
1947   Stream.EmitRecord(bitc::METADATA_TEMPLATE_VALUE, Record, Abbrev);
1948   Record.clear();
1949 }
1950 
1951 void ModuleBitcodeWriter::writeDIGlobalVariable(
1952     const DIGlobalVariable *N, SmallVectorImpl<uint64_t> &Record,
1953     unsigned Abbrev) {
1954   const uint64_t Version = 2 << 1;
1955   Record.push_back((uint64_t)N->isDistinct() | Version);
1956   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1957   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1958   Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
1959   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1960   Record.push_back(N->getLine());
1961   Record.push_back(VE.getMetadataOrNullID(N->getType()));
1962   Record.push_back(N->isLocalToUnit());
1963   Record.push_back(N->isDefinition());
1964   Record.push_back(VE.getMetadataOrNullID(N->getStaticDataMemberDeclaration()));
1965   Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams()));
1966   Record.push_back(N->getAlignInBits());
1967   Record.push_back(VE.getMetadataOrNullID(N->getAnnotations().get()));
1968 
1969   Stream.EmitRecord(bitc::METADATA_GLOBAL_VAR, Record, Abbrev);
1970   Record.clear();
1971 }
1972 
1973 void ModuleBitcodeWriter::writeDILocalVariable(
1974     const DILocalVariable *N, SmallVectorImpl<uint64_t> &Record,
1975     unsigned Abbrev) {
1976   // In order to support all possible bitcode formats in BitcodeReader we need
1977   // to distinguish the following cases:
1978   // 1) Record has no artificial tag (Record[1]),
1979   //   has no obsolete inlinedAt field (Record[9]).
1980   //   In this case Record size will be 8, HasAlignment flag is false.
1981   // 2) Record has artificial tag (Record[1]),
1982   //   has no obsolete inlignedAt field (Record[9]).
1983   //   In this case Record size will be 9, HasAlignment flag is false.
1984   // 3) Record has both artificial tag (Record[1]) and
1985   //   obsolete inlignedAt field (Record[9]).
1986   //   In this case Record size will be 10, HasAlignment flag is false.
1987   // 4) Record has neither artificial tag, nor inlignedAt field, but
1988   //   HasAlignment flag is true and Record[8] contains alignment value.
1989   const uint64_t HasAlignmentFlag = 1 << 1;
1990   Record.push_back((uint64_t)N->isDistinct() | HasAlignmentFlag);
1991   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1992   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1993   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1994   Record.push_back(N->getLine());
1995   Record.push_back(VE.getMetadataOrNullID(N->getType()));
1996   Record.push_back(N->getArg());
1997   Record.push_back(N->getFlags());
1998   Record.push_back(N->getAlignInBits());
1999   Record.push_back(VE.getMetadataOrNullID(N->getAnnotations().get()));
2000 
2001   Stream.EmitRecord(bitc::METADATA_LOCAL_VAR, Record, Abbrev);
2002   Record.clear();
2003 }
2004 
2005 void ModuleBitcodeWriter::writeDILabel(
2006     const DILabel *N, SmallVectorImpl<uint64_t> &Record,
2007     unsigned Abbrev) {
2008   Record.push_back((uint64_t)N->isDistinct());
2009   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2010   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2011   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2012   Record.push_back(N->getLine());
2013 
2014   Stream.EmitRecord(bitc::METADATA_LABEL, Record, Abbrev);
2015   Record.clear();
2016 }
2017 
2018 void ModuleBitcodeWriter::writeDIExpression(const DIExpression *N,
2019                                             SmallVectorImpl<uint64_t> &Record,
2020                                             unsigned Abbrev) {
2021   Record.reserve(N->getElements().size() + 1);
2022   const uint64_t Version = 3 << 1;
2023   Record.push_back((uint64_t)N->isDistinct() | Version);
2024   Record.append(N->elements_begin(), N->elements_end());
2025 
2026   Stream.EmitRecord(bitc::METADATA_EXPRESSION, Record, Abbrev);
2027   Record.clear();
2028 }
2029 
2030 void ModuleBitcodeWriter::writeDIGlobalVariableExpression(
2031     const DIGlobalVariableExpression *N, SmallVectorImpl<uint64_t> &Record,
2032     unsigned Abbrev) {
2033   Record.push_back(N->isDistinct());
2034   Record.push_back(VE.getMetadataOrNullID(N->getVariable()));
2035   Record.push_back(VE.getMetadataOrNullID(N->getExpression()));
2036 
2037   Stream.EmitRecord(bitc::METADATA_GLOBAL_VAR_EXPR, Record, Abbrev);
2038   Record.clear();
2039 }
2040 
2041 void ModuleBitcodeWriter::writeDIObjCProperty(const DIObjCProperty *N,
2042                                               SmallVectorImpl<uint64_t> &Record,
2043                                               unsigned Abbrev) {
2044   Record.push_back(N->isDistinct());
2045   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2046   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2047   Record.push_back(N->getLine());
2048   Record.push_back(VE.getMetadataOrNullID(N->getRawSetterName()));
2049   Record.push_back(VE.getMetadataOrNullID(N->getRawGetterName()));
2050   Record.push_back(N->getAttributes());
2051   Record.push_back(VE.getMetadataOrNullID(N->getType()));
2052 
2053   Stream.EmitRecord(bitc::METADATA_OBJC_PROPERTY, Record, Abbrev);
2054   Record.clear();
2055 }
2056 
2057 void ModuleBitcodeWriter::writeDIImportedEntity(
2058     const DIImportedEntity *N, SmallVectorImpl<uint64_t> &Record,
2059     unsigned Abbrev) {
2060   Record.push_back(N->isDistinct());
2061   Record.push_back(N->getTag());
2062   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2063   Record.push_back(VE.getMetadataOrNullID(N->getEntity()));
2064   Record.push_back(N->getLine());
2065   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2066   Record.push_back(VE.getMetadataOrNullID(N->getRawFile()));
2067   Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
2068 
2069   Stream.EmitRecord(bitc::METADATA_IMPORTED_ENTITY, Record, Abbrev);
2070   Record.clear();
2071 }
2072 
2073 unsigned ModuleBitcodeWriter::createNamedMetadataAbbrev() {
2074   auto Abbv = std::make_shared<BitCodeAbbrev>();
2075   Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_NAME));
2076   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2077   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
2078   return Stream.EmitAbbrev(std::move(Abbv));
2079 }
2080 
2081 void ModuleBitcodeWriter::writeNamedMetadata(
2082     SmallVectorImpl<uint64_t> &Record) {
2083   if (M.named_metadata_empty())
2084     return;
2085 
2086   unsigned Abbrev = createNamedMetadataAbbrev();
2087   for (const NamedMDNode &NMD : M.named_metadata()) {
2088     // Write name.
2089     StringRef Str = NMD.getName();
2090     Record.append(Str.bytes_begin(), Str.bytes_end());
2091     Stream.EmitRecord(bitc::METADATA_NAME, Record, Abbrev);
2092     Record.clear();
2093 
2094     // Write named metadata operands.
2095     for (const MDNode *N : NMD.operands())
2096       Record.push_back(VE.getMetadataID(N));
2097     Stream.EmitRecord(bitc::METADATA_NAMED_NODE, Record, 0);
2098     Record.clear();
2099   }
2100 }
2101 
2102 unsigned ModuleBitcodeWriter::createMetadataStringsAbbrev() {
2103   auto Abbv = std::make_shared<BitCodeAbbrev>();
2104   Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_STRINGS));
2105   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of strings
2106   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // offset to chars
2107   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2108   return Stream.EmitAbbrev(std::move(Abbv));
2109 }
2110 
2111 /// Write out a record for MDString.
2112 ///
2113 /// All the metadata strings in a metadata block are emitted in a single
2114 /// record.  The sizes and strings themselves are shoved into a blob.
2115 void ModuleBitcodeWriter::writeMetadataStrings(
2116     ArrayRef<const Metadata *> Strings, SmallVectorImpl<uint64_t> &Record) {
2117   if (Strings.empty())
2118     return;
2119 
2120   // Start the record with the number of strings.
2121   Record.push_back(bitc::METADATA_STRINGS);
2122   Record.push_back(Strings.size());
2123 
2124   // Emit the sizes of the strings in the blob.
2125   SmallString<256> Blob;
2126   {
2127     BitstreamWriter W(Blob);
2128     for (const Metadata *MD : Strings)
2129       W.EmitVBR(cast<MDString>(MD)->getLength(), 6);
2130     W.FlushToWord();
2131   }
2132 
2133   // Add the offset to the strings to the record.
2134   Record.push_back(Blob.size());
2135 
2136   // Add the strings to the blob.
2137   for (const Metadata *MD : Strings)
2138     Blob.append(cast<MDString>(MD)->getString());
2139 
2140   // Emit the final record.
2141   Stream.EmitRecordWithBlob(createMetadataStringsAbbrev(), Record, Blob);
2142   Record.clear();
2143 }
2144 
2145 // Generates an enum to use as an index in the Abbrev array of Metadata record.
2146 enum MetadataAbbrev : unsigned {
2147 #define HANDLE_MDNODE_LEAF(CLASS) CLASS##AbbrevID,
2148 #include "llvm/IR/Metadata.def"
2149   LastPlusOne
2150 };
2151 
2152 void ModuleBitcodeWriter::writeMetadataRecords(
2153     ArrayRef<const Metadata *> MDs, SmallVectorImpl<uint64_t> &Record,
2154     std::vector<unsigned> *MDAbbrevs, std::vector<uint64_t> *IndexPos) {
2155   if (MDs.empty())
2156     return;
2157 
2158   // Initialize MDNode abbreviations.
2159 #define HANDLE_MDNODE_LEAF(CLASS) unsigned CLASS##Abbrev = 0;
2160 #include "llvm/IR/Metadata.def"
2161 
2162   for (const Metadata *MD : MDs) {
2163     if (IndexPos)
2164       IndexPos->push_back(Stream.GetCurrentBitNo());
2165     if (const MDNode *N = dyn_cast<MDNode>(MD)) {
2166       assert(N->isResolved() && "Expected forward references to be resolved");
2167 
2168       switch (N->getMetadataID()) {
2169       default:
2170         llvm_unreachable("Invalid MDNode subclass");
2171 #define HANDLE_MDNODE_LEAF(CLASS)                                              \
2172   case Metadata::CLASS##Kind:                                                  \
2173     if (MDAbbrevs)                                                             \
2174       write##CLASS(cast<CLASS>(N), Record,                                     \
2175                    (*MDAbbrevs)[MetadataAbbrev::CLASS##AbbrevID]);             \
2176     else                                                                       \
2177       write##CLASS(cast<CLASS>(N), Record, CLASS##Abbrev);                     \
2178     continue;
2179 #include "llvm/IR/Metadata.def"
2180       }
2181     }
2182     writeValueAsMetadata(cast<ValueAsMetadata>(MD), Record);
2183   }
2184 }
2185 
2186 void ModuleBitcodeWriter::writeModuleMetadata() {
2187   if (!VE.hasMDs() && M.named_metadata_empty())
2188     return;
2189 
2190   Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 4);
2191   SmallVector<uint64_t, 64> Record;
2192 
2193   // Emit all abbrevs upfront, so that the reader can jump in the middle of the
2194   // block and load any metadata.
2195   std::vector<unsigned> MDAbbrevs;
2196 
2197   MDAbbrevs.resize(MetadataAbbrev::LastPlusOne);
2198   MDAbbrevs[MetadataAbbrev::DILocationAbbrevID] = createDILocationAbbrev();
2199   MDAbbrevs[MetadataAbbrev::GenericDINodeAbbrevID] =
2200       createGenericDINodeAbbrev();
2201 
2202   auto Abbv = std::make_shared<BitCodeAbbrev>();
2203   Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_INDEX_OFFSET));
2204   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
2205   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
2206   unsigned OffsetAbbrev = Stream.EmitAbbrev(std::move(Abbv));
2207 
2208   Abbv = std::make_shared<BitCodeAbbrev>();
2209   Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_INDEX));
2210   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2211   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
2212   unsigned IndexAbbrev = Stream.EmitAbbrev(std::move(Abbv));
2213 
2214   // Emit MDStrings together upfront.
2215   writeMetadataStrings(VE.getMDStrings(), Record);
2216 
2217   // We only emit an index for the metadata record if we have more than a given
2218   // (naive) threshold of metadatas, otherwise it is not worth it.
2219   if (VE.getNonMDStrings().size() > IndexThreshold) {
2220     // Write a placeholder value in for the offset of the metadata index,
2221     // which is written after the records, so that it can include
2222     // the offset of each entry. The placeholder offset will be
2223     // updated after all records are emitted.
2224     uint64_t Vals[] = {0, 0};
2225     Stream.EmitRecord(bitc::METADATA_INDEX_OFFSET, Vals, OffsetAbbrev);
2226   }
2227 
2228   // Compute and save the bit offset to the current position, which will be
2229   // patched when we emit the index later. We can simply subtract the 64-bit
2230   // fixed size from the current bit number to get the location to backpatch.
2231   uint64_t IndexOffsetRecordBitPos = Stream.GetCurrentBitNo();
2232 
2233   // This index will contain the bitpos for each individual record.
2234   std::vector<uint64_t> IndexPos;
2235   IndexPos.reserve(VE.getNonMDStrings().size());
2236 
2237   // Write all the records
2238   writeMetadataRecords(VE.getNonMDStrings(), Record, &MDAbbrevs, &IndexPos);
2239 
2240   if (VE.getNonMDStrings().size() > IndexThreshold) {
2241     // Now that we have emitted all the records we will emit the index. But
2242     // first
2243     // backpatch the forward reference so that the reader can skip the records
2244     // efficiently.
2245     Stream.BackpatchWord64(IndexOffsetRecordBitPos - 64,
2246                            Stream.GetCurrentBitNo() - IndexOffsetRecordBitPos);
2247 
2248     // Delta encode the index.
2249     uint64_t PreviousValue = IndexOffsetRecordBitPos;
2250     for (auto &Elt : IndexPos) {
2251       auto EltDelta = Elt - PreviousValue;
2252       PreviousValue = Elt;
2253       Elt = EltDelta;
2254     }
2255     // Emit the index record.
2256     Stream.EmitRecord(bitc::METADATA_INDEX, IndexPos, IndexAbbrev);
2257     IndexPos.clear();
2258   }
2259 
2260   // Write the named metadata now.
2261   writeNamedMetadata(Record);
2262 
2263   auto AddDeclAttachedMetadata = [&](const GlobalObject &GO) {
2264     SmallVector<uint64_t, 4> Record;
2265     Record.push_back(VE.getValueID(&GO));
2266     pushGlobalMetadataAttachment(Record, GO);
2267     Stream.EmitRecord(bitc::METADATA_GLOBAL_DECL_ATTACHMENT, Record);
2268   };
2269   for (const Function &F : M)
2270     if (F.isDeclaration() && F.hasMetadata())
2271       AddDeclAttachedMetadata(F);
2272   // FIXME: Only store metadata for declarations here, and move data for global
2273   // variable definitions to a separate block (PR28134).
2274   for (const GlobalVariable &GV : M.globals())
2275     if (GV.hasMetadata())
2276       AddDeclAttachedMetadata(GV);
2277 
2278   Stream.ExitBlock();
2279 }
2280 
2281 void ModuleBitcodeWriter::writeFunctionMetadata(const Function &F) {
2282   if (!VE.hasMDs())
2283     return;
2284 
2285   Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
2286   SmallVector<uint64_t, 64> Record;
2287   writeMetadataStrings(VE.getMDStrings(), Record);
2288   writeMetadataRecords(VE.getNonMDStrings(), Record);
2289   Stream.ExitBlock();
2290 }
2291 
2292 void ModuleBitcodeWriter::pushGlobalMetadataAttachment(
2293     SmallVectorImpl<uint64_t> &Record, const GlobalObject &GO) {
2294   // [n x [id, mdnode]]
2295   SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
2296   GO.getAllMetadata(MDs);
2297   for (const auto &I : MDs) {
2298     Record.push_back(I.first);
2299     Record.push_back(VE.getMetadataID(I.second));
2300   }
2301 }
2302 
2303 void ModuleBitcodeWriter::writeFunctionMetadataAttachment(const Function &F) {
2304   Stream.EnterSubblock(bitc::METADATA_ATTACHMENT_ID, 3);
2305 
2306   SmallVector<uint64_t, 64> Record;
2307 
2308   if (F.hasMetadata()) {
2309     pushGlobalMetadataAttachment(Record, F);
2310     Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
2311     Record.clear();
2312   }
2313 
2314   // Write metadata attachments
2315   // METADATA_ATTACHMENT - [m x [value, [n x [id, mdnode]]]
2316   SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
2317   for (const BasicBlock &BB : F)
2318     for (const Instruction &I : BB) {
2319       MDs.clear();
2320       I.getAllMetadataOtherThanDebugLoc(MDs);
2321 
2322       // If no metadata, ignore instruction.
2323       if (MDs.empty()) continue;
2324 
2325       Record.push_back(VE.getInstructionID(&I));
2326 
2327       for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
2328         Record.push_back(MDs[i].first);
2329         Record.push_back(VE.getMetadataID(MDs[i].second));
2330       }
2331       Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
2332       Record.clear();
2333     }
2334 
2335   Stream.ExitBlock();
2336 }
2337 
2338 void ModuleBitcodeWriter::writeModuleMetadataKinds() {
2339   SmallVector<uint64_t, 64> Record;
2340 
2341   // Write metadata kinds
2342   // METADATA_KIND - [n x [id, name]]
2343   SmallVector<StringRef, 8> Names;
2344   M.getMDKindNames(Names);
2345 
2346   if (Names.empty()) return;
2347 
2348   Stream.EnterSubblock(bitc::METADATA_KIND_BLOCK_ID, 3);
2349 
2350   for (unsigned MDKindID = 0, e = Names.size(); MDKindID != e; ++MDKindID) {
2351     Record.push_back(MDKindID);
2352     StringRef KName = Names[MDKindID];
2353     Record.append(KName.begin(), KName.end());
2354 
2355     Stream.EmitRecord(bitc::METADATA_KIND, Record, 0);
2356     Record.clear();
2357   }
2358 
2359   Stream.ExitBlock();
2360 }
2361 
2362 void ModuleBitcodeWriter::writeOperandBundleTags() {
2363   // Write metadata kinds
2364   //
2365   // OPERAND_BUNDLE_TAGS_BLOCK_ID : N x OPERAND_BUNDLE_TAG
2366   //
2367   // OPERAND_BUNDLE_TAG - [strchr x N]
2368 
2369   SmallVector<StringRef, 8> Tags;
2370   M.getOperandBundleTags(Tags);
2371 
2372   if (Tags.empty())
2373     return;
2374 
2375   Stream.EnterSubblock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID, 3);
2376 
2377   SmallVector<uint64_t, 64> Record;
2378 
2379   for (auto Tag : Tags) {
2380     Record.append(Tag.begin(), Tag.end());
2381 
2382     Stream.EmitRecord(bitc::OPERAND_BUNDLE_TAG, Record, 0);
2383     Record.clear();
2384   }
2385 
2386   Stream.ExitBlock();
2387 }
2388 
2389 void ModuleBitcodeWriter::writeSyncScopeNames() {
2390   SmallVector<StringRef, 8> SSNs;
2391   M.getContext().getSyncScopeNames(SSNs);
2392   if (SSNs.empty())
2393     return;
2394 
2395   Stream.EnterSubblock(bitc::SYNC_SCOPE_NAMES_BLOCK_ID, 2);
2396 
2397   SmallVector<uint64_t, 64> Record;
2398   for (auto SSN : SSNs) {
2399     Record.append(SSN.begin(), SSN.end());
2400     Stream.EmitRecord(bitc::SYNC_SCOPE_NAME, Record, 0);
2401     Record.clear();
2402   }
2403 
2404   Stream.ExitBlock();
2405 }
2406 
2407 void ModuleBitcodeWriter::writeConstants(unsigned FirstVal, unsigned LastVal,
2408                                          bool isGlobal) {
2409   if (FirstVal == LastVal) return;
2410 
2411   Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 4);
2412 
2413   unsigned AggregateAbbrev = 0;
2414   unsigned String8Abbrev = 0;
2415   unsigned CString7Abbrev = 0;
2416   unsigned CString6Abbrev = 0;
2417   // If this is a constant pool for the module, emit module-specific abbrevs.
2418   if (isGlobal) {
2419     // Abbrev for CST_CODE_AGGREGATE.
2420     auto Abbv = std::make_shared<BitCodeAbbrev>();
2421     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_AGGREGATE));
2422     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2423     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal+1)));
2424     AggregateAbbrev = Stream.EmitAbbrev(std::move(Abbv));
2425 
2426     // Abbrev for CST_CODE_STRING.
2427     Abbv = std::make_shared<BitCodeAbbrev>();
2428     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_STRING));
2429     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2430     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
2431     String8Abbrev = Stream.EmitAbbrev(std::move(Abbv));
2432     // Abbrev for CST_CODE_CSTRING.
2433     Abbv = std::make_shared<BitCodeAbbrev>();
2434     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
2435     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2436     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
2437     CString7Abbrev = Stream.EmitAbbrev(std::move(Abbv));
2438     // Abbrev for CST_CODE_CSTRING.
2439     Abbv = std::make_shared<BitCodeAbbrev>();
2440     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
2441     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2442     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
2443     CString6Abbrev = Stream.EmitAbbrev(std::move(Abbv));
2444   }
2445 
2446   SmallVector<uint64_t, 64> Record;
2447 
2448   const ValueEnumerator::ValueList &Vals = VE.getValues();
2449   Type *LastTy = nullptr;
2450   for (unsigned i = FirstVal; i != LastVal; ++i) {
2451     const Value *V = Vals[i].first;
2452     // If we need to switch types, do so now.
2453     if (V->getType() != LastTy) {
2454       LastTy = V->getType();
2455       Record.push_back(VE.getTypeID(LastTy));
2456       Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record,
2457                         CONSTANTS_SETTYPE_ABBREV);
2458       Record.clear();
2459     }
2460 
2461     if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
2462       Record.push_back(VE.getTypeID(IA->getFunctionType()));
2463       Record.push_back(
2464           unsigned(IA->hasSideEffects()) | unsigned(IA->isAlignStack()) << 1 |
2465           unsigned(IA->getDialect() & 1) << 2 | unsigned(IA->canThrow()) << 3);
2466 
2467       // Add the asm string.
2468       const std::string &AsmStr = IA->getAsmString();
2469       Record.push_back(AsmStr.size());
2470       Record.append(AsmStr.begin(), AsmStr.end());
2471 
2472       // Add the constraint string.
2473       const std::string &ConstraintStr = IA->getConstraintString();
2474       Record.push_back(ConstraintStr.size());
2475       Record.append(ConstraintStr.begin(), ConstraintStr.end());
2476       Stream.EmitRecord(bitc::CST_CODE_INLINEASM, Record);
2477       Record.clear();
2478       continue;
2479     }
2480     const Constant *C = cast<Constant>(V);
2481     unsigned Code = -1U;
2482     unsigned AbbrevToUse = 0;
2483     if (C->isNullValue()) {
2484       Code = bitc::CST_CODE_NULL;
2485     } else if (isa<PoisonValue>(C)) {
2486       Code = bitc::CST_CODE_POISON;
2487     } else if (isa<UndefValue>(C)) {
2488       Code = bitc::CST_CODE_UNDEF;
2489     } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {
2490       if (IV->getBitWidth() <= 64) {
2491         uint64_t V = IV->getSExtValue();
2492         emitSignedInt64(Record, V);
2493         Code = bitc::CST_CODE_INTEGER;
2494         AbbrevToUse = CONSTANTS_INTEGER_ABBREV;
2495       } else {                             // Wide integers, > 64 bits in size.
2496         emitWideAPInt(Record, IV->getValue());
2497         Code = bitc::CST_CODE_WIDE_INTEGER;
2498       }
2499     } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
2500       Code = bitc::CST_CODE_FLOAT;
2501       Type *Ty = CFP->getType();
2502       if (Ty->isHalfTy() || Ty->isBFloatTy() || Ty->isFloatTy() ||
2503           Ty->isDoubleTy()) {
2504         Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
2505       } else if (Ty->isX86_FP80Ty()) {
2506         // api needed to prevent premature destruction
2507         // bits are not in the same order as a normal i80 APInt, compensate.
2508         APInt api = CFP->getValueAPF().bitcastToAPInt();
2509         const uint64_t *p = api.getRawData();
2510         Record.push_back((p[1] << 48) | (p[0] >> 16));
2511         Record.push_back(p[0] & 0xffffLL);
2512       } else if (Ty->isFP128Ty() || Ty->isPPC_FP128Ty()) {
2513         APInt api = CFP->getValueAPF().bitcastToAPInt();
2514         const uint64_t *p = api.getRawData();
2515         Record.push_back(p[0]);
2516         Record.push_back(p[1]);
2517       } else {
2518         assert(0 && "Unknown FP type!");
2519       }
2520     } else if (isa<ConstantDataSequential>(C) &&
2521                cast<ConstantDataSequential>(C)->isString()) {
2522       const ConstantDataSequential *Str = cast<ConstantDataSequential>(C);
2523       // Emit constant strings specially.
2524       unsigned NumElts = Str->getNumElements();
2525       // If this is a null-terminated string, use the denser CSTRING encoding.
2526       if (Str->isCString()) {
2527         Code = bitc::CST_CODE_CSTRING;
2528         --NumElts;  // Don't encode the null, which isn't allowed by char6.
2529       } else {
2530         Code = bitc::CST_CODE_STRING;
2531         AbbrevToUse = String8Abbrev;
2532       }
2533       bool isCStr7 = Code == bitc::CST_CODE_CSTRING;
2534       bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING;
2535       for (unsigned i = 0; i != NumElts; ++i) {
2536         unsigned char V = Str->getElementAsInteger(i);
2537         Record.push_back(V);
2538         isCStr7 &= (V & 128) == 0;
2539         if (isCStrChar6)
2540           isCStrChar6 = BitCodeAbbrevOp::isChar6(V);
2541       }
2542 
2543       if (isCStrChar6)
2544         AbbrevToUse = CString6Abbrev;
2545       else if (isCStr7)
2546         AbbrevToUse = CString7Abbrev;
2547     } else if (const ConstantDataSequential *CDS =
2548                   dyn_cast<ConstantDataSequential>(C)) {
2549       Code = bitc::CST_CODE_DATA;
2550       Type *EltTy = CDS->getElementType();
2551       if (isa<IntegerType>(EltTy)) {
2552         for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
2553           Record.push_back(CDS->getElementAsInteger(i));
2554       } else {
2555         for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
2556           Record.push_back(
2557               CDS->getElementAsAPFloat(i).bitcastToAPInt().getLimitedValue());
2558       }
2559     } else if (isa<ConstantAggregate>(C)) {
2560       Code = bitc::CST_CODE_AGGREGATE;
2561       for (const Value *Op : C->operands())
2562         Record.push_back(VE.getValueID(Op));
2563       AbbrevToUse = AggregateAbbrev;
2564     } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
2565       switch (CE->getOpcode()) {
2566       default:
2567         if (Instruction::isCast(CE->getOpcode())) {
2568           Code = bitc::CST_CODE_CE_CAST;
2569           Record.push_back(getEncodedCastOpcode(CE->getOpcode()));
2570           Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2571           Record.push_back(VE.getValueID(C->getOperand(0)));
2572           AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;
2573         } else {
2574           assert(CE->getNumOperands() == 2 && "Unknown constant expr!");
2575           Code = bitc::CST_CODE_CE_BINOP;
2576           Record.push_back(getEncodedBinaryOpcode(CE->getOpcode()));
2577           Record.push_back(VE.getValueID(C->getOperand(0)));
2578           Record.push_back(VE.getValueID(C->getOperand(1)));
2579           uint64_t Flags = getOptimizationFlags(CE);
2580           if (Flags != 0)
2581             Record.push_back(Flags);
2582         }
2583         break;
2584       case Instruction::FNeg: {
2585         assert(CE->getNumOperands() == 1 && "Unknown constant expr!");
2586         Code = bitc::CST_CODE_CE_UNOP;
2587         Record.push_back(getEncodedUnaryOpcode(CE->getOpcode()));
2588         Record.push_back(VE.getValueID(C->getOperand(0)));
2589         uint64_t Flags = getOptimizationFlags(CE);
2590         if (Flags != 0)
2591           Record.push_back(Flags);
2592         break;
2593       }
2594       case Instruction::GetElementPtr: {
2595         Code = bitc::CST_CODE_CE_GEP;
2596         const auto *GO = cast<GEPOperator>(C);
2597         Record.push_back(VE.getTypeID(GO->getSourceElementType()));
2598         if (Optional<unsigned> Idx = GO->getInRangeIndex()) {
2599           Code = bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX;
2600           Record.push_back((*Idx << 1) | GO->isInBounds());
2601         } else if (GO->isInBounds())
2602           Code = bitc::CST_CODE_CE_INBOUNDS_GEP;
2603         for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
2604           Record.push_back(VE.getTypeID(C->getOperand(i)->getType()));
2605           Record.push_back(VE.getValueID(C->getOperand(i)));
2606         }
2607         break;
2608       }
2609       case Instruction::Select:
2610         Code = bitc::CST_CODE_CE_SELECT;
2611         Record.push_back(VE.getValueID(C->getOperand(0)));
2612         Record.push_back(VE.getValueID(C->getOperand(1)));
2613         Record.push_back(VE.getValueID(C->getOperand(2)));
2614         break;
2615       case Instruction::ExtractElement:
2616         Code = bitc::CST_CODE_CE_EXTRACTELT;
2617         Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2618         Record.push_back(VE.getValueID(C->getOperand(0)));
2619         Record.push_back(VE.getTypeID(C->getOperand(1)->getType()));
2620         Record.push_back(VE.getValueID(C->getOperand(1)));
2621         break;
2622       case Instruction::InsertElement:
2623         Code = bitc::CST_CODE_CE_INSERTELT;
2624         Record.push_back(VE.getValueID(C->getOperand(0)));
2625         Record.push_back(VE.getValueID(C->getOperand(1)));
2626         Record.push_back(VE.getTypeID(C->getOperand(2)->getType()));
2627         Record.push_back(VE.getValueID(C->getOperand(2)));
2628         break;
2629       case Instruction::ShuffleVector:
2630         // If the return type and argument types are the same, this is a
2631         // standard shufflevector instruction.  If the types are different,
2632         // then the shuffle is widening or truncating the input vectors, and
2633         // the argument type must also be encoded.
2634         if (C->getType() == C->getOperand(0)->getType()) {
2635           Code = bitc::CST_CODE_CE_SHUFFLEVEC;
2636         } else {
2637           Code = bitc::CST_CODE_CE_SHUFVEC_EX;
2638           Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2639         }
2640         Record.push_back(VE.getValueID(C->getOperand(0)));
2641         Record.push_back(VE.getValueID(C->getOperand(1)));
2642         Record.push_back(VE.getValueID(CE->getShuffleMaskForBitcode()));
2643         break;
2644       case Instruction::ICmp:
2645       case Instruction::FCmp:
2646         Code = bitc::CST_CODE_CE_CMP;
2647         Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2648         Record.push_back(VE.getValueID(C->getOperand(0)));
2649         Record.push_back(VE.getValueID(C->getOperand(1)));
2650         Record.push_back(CE->getPredicate());
2651         break;
2652       }
2653     } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) {
2654       Code = bitc::CST_CODE_BLOCKADDRESS;
2655       Record.push_back(VE.getTypeID(BA->getFunction()->getType()));
2656       Record.push_back(VE.getValueID(BA->getFunction()));
2657       Record.push_back(VE.getGlobalBasicBlockID(BA->getBasicBlock()));
2658     } else if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C)) {
2659       Code = bitc::CST_CODE_DSO_LOCAL_EQUIVALENT;
2660       Record.push_back(VE.getTypeID(Equiv->getGlobalValue()->getType()));
2661       Record.push_back(VE.getValueID(Equiv->getGlobalValue()));
2662     } else if (const auto *NC = dyn_cast<NoCFIValue>(C)) {
2663       Code = bitc::CST_CODE_NO_CFI_VALUE;
2664       Record.push_back(VE.getTypeID(NC->getGlobalValue()->getType()));
2665       Record.push_back(VE.getValueID(NC->getGlobalValue()));
2666     } else {
2667 #ifndef NDEBUG
2668       C->dump();
2669 #endif
2670       llvm_unreachable("Unknown constant!");
2671     }
2672     Stream.EmitRecord(Code, Record, AbbrevToUse);
2673     Record.clear();
2674   }
2675 
2676   Stream.ExitBlock();
2677 }
2678 
2679 void ModuleBitcodeWriter::writeModuleConstants() {
2680   const ValueEnumerator::ValueList &Vals = VE.getValues();
2681 
2682   // Find the first constant to emit, which is the first non-globalvalue value.
2683   // We know globalvalues have been emitted by WriteModuleInfo.
2684   for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
2685     if (!isa<GlobalValue>(Vals[i].first)) {
2686       writeConstants(i, Vals.size(), true);
2687       return;
2688     }
2689   }
2690 }
2691 
2692 /// pushValueAndType - The file has to encode both the value and type id for
2693 /// many values, because we need to know what type to create for forward
2694 /// references.  However, most operands are not forward references, so this type
2695 /// field is not needed.
2696 ///
2697 /// This function adds V's value ID to Vals.  If the value ID is higher than the
2698 /// instruction ID, then it is a forward reference, and it also includes the
2699 /// type ID.  The value ID that is written is encoded relative to the InstID.
2700 bool ModuleBitcodeWriter::pushValueAndType(const Value *V, unsigned InstID,
2701                                            SmallVectorImpl<unsigned> &Vals) {
2702   unsigned ValID = VE.getValueID(V);
2703   // Make encoding relative to the InstID.
2704   Vals.push_back(InstID - ValID);
2705   if (ValID >= InstID) {
2706     Vals.push_back(VE.getTypeID(V->getType()));
2707     return true;
2708   }
2709   return false;
2710 }
2711 
2712 void ModuleBitcodeWriter::writeOperandBundles(const CallBase &CS,
2713                                               unsigned InstID) {
2714   SmallVector<unsigned, 64> Record;
2715   LLVMContext &C = CS.getContext();
2716 
2717   for (unsigned i = 0, e = CS.getNumOperandBundles(); i != e; ++i) {
2718     const auto &Bundle = CS.getOperandBundleAt(i);
2719     Record.push_back(C.getOperandBundleTagID(Bundle.getTagName()));
2720 
2721     for (auto &Input : Bundle.Inputs)
2722       pushValueAndType(Input, InstID, Record);
2723 
2724     Stream.EmitRecord(bitc::FUNC_CODE_OPERAND_BUNDLE, Record);
2725     Record.clear();
2726   }
2727 }
2728 
2729 /// pushValue - Like pushValueAndType, but where the type of the value is
2730 /// omitted (perhaps it was already encoded in an earlier operand).
2731 void ModuleBitcodeWriter::pushValue(const Value *V, unsigned InstID,
2732                                     SmallVectorImpl<unsigned> &Vals) {
2733   unsigned ValID = VE.getValueID(V);
2734   Vals.push_back(InstID - ValID);
2735 }
2736 
2737 void ModuleBitcodeWriter::pushValueSigned(const Value *V, unsigned InstID,
2738                                           SmallVectorImpl<uint64_t> &Vals) {
2739   unsigned ValID = VE.getValueID(V);
2740   int64_t diff = ((int32_t)InstID - (int32_t)ValID);
2741   emitSignedInt64(Vals, diff);
2742 }
2743 
2744 /// WriteInstruction - Emit an instruction to the specified stream.
2745 void ModuleBitcodeWriter::writeInstruction(const Instruction &I,
2746                                            unsigned InstID,
2747                                            SmallVectorImpl<unsigned> &Vals) {
2748   unsigned Code = 0;
2749   unsigned AbbrevToUse = 0;
2750   VE.setInstructionID(&I);
2751   switch (I.getOpcode()) {
2752   default:
2753     if (Instruction::isCast(I.getOpcode())) {
2754       Code = bitc::FUNC_CODE_INST_CAST;
2755       if (!pushValueAndType(I.getOperand(0), InstID, Vals))
2756         AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
2757       Vals.push_back(VE.getTypeID(I.getType()));
2758       Vals.push_back(getEncodedCastOpcode(I.getOpcode()));
2759     } else {
2760       assert(isa<BinaryOperator>(I) && "Unknown instruction!");
2761       Code = bitc::FUNC_CODE_INST_BINOP;
2762       if (!pushValueAndType(I.getOperand(0), InstID, Vals))
2763         AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
2764       pushValue(I.getOperand(1), InstID, Vals);
2765       Vals.push_back(getEncodedBinaryOpcode(I.getOpcode()));
2766       uint64_t Flags = getOptimizationFlags(&I);
2767       if (Flags != 0) {
2768         if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV)
2769           AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV;
2770         Vals.push_back(Flags);
2771       }
2772     }
2773     break;
2774   case Instruction::FNeg: {
2775     Code = bitc::FUNC_CODE_INST_UNOP;
2776     if (!pushValueAndType(I.getOperand(0), InstID, Vals))
2777       AbbrevToUse = FUNCTION_INST_UNOP_ABBREV;
2778     Vals.push_back(getEncodedUnaryOpcode(I.getOpcode()));
2779     uint64_t Flags = getOptimizationFlags(&I);
2780     if (Flags != 0) {
2781       if (AbbrevToUse == FUNCTION_INST_UNOP_ABBREV)
2782         AbbrevToUse = FUNCTION_INST_UNOP_FLAGS_ABBREV;
2783       Vals.push_back(Flags);
2784     }
2785     break;
2786   }
2787   case Instruction::GetElementPtr: {
2788     Code = bitc::FUNC_CODE_INST_GEP;
2789     AbbrevToUse = FUNCTION_INST_GEP_ABBREV;
2790     auto &GEPInst = cast<GetElementPtrInst>(I);
2791     Vals.push_back(GEPInst.isInBounds());
2792     Vals.push_back(VE.getTypeID(GEPInst.getSourceElementType()));
2793     for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
2794       pushValueAndType(I.getOperand(i), InstID, Vals);
2795     break;
2796   }
2797   case Instruction::ExtractValue: {
2798     Code = bitc::FUNC_CODE_INST_EXTRACTVAL;
2799     pushValueAndType(I.getOperand(0), InstID, Vals);
2800     const ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
2801     Vals.append(EVI->idx_begin(), EVI->idx_end());
2802     break;
2803   }
2804   case Instruction::InsertValue: {
2805     Code = bitc::FUNC_CODE_INST_INSERTVAL;
2806     pushValueAndType(I.getOperand(0), InstID, Vals);
2807     pushValueAndType(I.getOperand(1), InstID, Vals);
2808     const InsertValueInst *IVI = cast<InsertValueInst>(&I);
2809     Vals.append(IVI->idx_begin(), IVI->idx_end());
2810     break;
2811   }
2812   case Instruction::Select: {
2813     Code = bitc::FUNC_CODE_INST_VSELECT;
2814     pushValueAndType(I.getOperand(1), InstID, Vals);
2815     pushValue(I.getOperand(2), InstID, Vals);
2816     pushValueAndType(I.getOperand(0), InstID, Vals);
2817     uint64_t Flags = getOptimizationFlags(&I);
2818     if (Flags != 0)
2819       Vals.push_back(Flags);
2820     break;
2821   }
2822   case Instruction::ExtractElement:
2823     Code = bitc::FUNC_CODE_INST_EXTRACTELT;
2824     pushValueAndType(I.getOperand(0), InstID, Vals);
2825     pushValueAndType(I.getOperand(1), InstID, Vals);
2826     break;
2827   case Instruction::InsertElement:
2828     Code = bitc::FUNC_CODE_INST_INSERTELT;
2829     pushValueAndType(I.getOperand(0), InstID, Vals);
2830     pushValue(I.getOperand(1), InstID, Vals);
2831     pushValueAndType(I.getOperand(2), InstID, Vals);
2832     break;
2833   case Instruction::ShuffleVector:
2834     Code = bitc::FUNC_CODE_INST_SHUFFLEVEC;
2835     pushValueAndType(I.getOperand(0), InstID, Vals);
2836     pushValue(I.getOperand(1), InstID, Vals);
2837     pushValue(cast<ShuffleVectorInst>(I).getShuffleMaskForBitcode(), InstID,
2838               Vals);
2839     break;
2840   case Instruction::ICmp:
2841   case Instruction::FCmp: {
2842     // compare returning Int1Ty or vector of Int1Ty
2843     Code = bitc::FUNC_CODE_INST_CMP2;
2844     pushValueAndType(I.getOperand(0), InstID, Vals);
2845     pushValue(I.getOperand(1), InstID, Vals);
2846     Vals.push_back(cast<CmpInst>(I).getPredicate());
2847     uint64_t Flags = getOptimizationFlags(&I);
2848     if (Flags != 0)
2849       Vals.push_back(Flags);
2850     break;
2851   }
2852 
2853   case Instruction::Ret:
2854     {
2855       Code = bitc::FUNC_CODE_INST_RET;
2856       unsigned NumOperands = I.getNumOperands();
2857       if (NumOperands == 0)
2858         AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
2859       else if (NumOperands == 1) {
2860         if (!pushValueAndType(I.getOperand(0), InstID, Vals))
2861           AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
2862       } else {
2863         for (unsigned i = 0, e = NumOperands; i != e; ++i)
2864           pushValueAndType(I.getOperand(i), InstID, Vals);
2865       }
2866     }
2867     break;
2868   case Instruction::Br:
2869     {
2870       Code = bitc::FUNC_CODE_INST_BR;
2871       const BranchInst &II = cast<BranchInst>(I);
2872       Vals.push_back(VE.getValueID(II.getSuccessor(0)));
2873       if (II.isConditional()) {
2874         Vals.push_back(VE.getValueID(II.getSuccessor(1)));
2875         pushValue(II.getCondition(), InstID, Vals);
2876       }
2877     }
2878     break;
2879   case Instruction::Switch:
2880     {
2881       Code = bitc::FUNC_CODE_INST_SWITCH;
2882       const SwitchInst &SI = cast<SwitchInst>(I);
2883       Vals.push_back(VE.getTypeID(SI.getCondition()->getType()));
2884       pushValue(SI.getCondition(), InstID, Vals);
2885       Vals.push_back(VE.getValueID(SI.getDefaultDest()));
2886       for (auto Case : SI.cases()) {
2887         Vals.push_back(VE.getValueID(Case.getCaseValue()));
2888         Vals.push_back(VE.getValueID(Case.getCaseSuccessor()));
2889       }
2890     }
2891     break;
2892   case Instruction::IndirectBr:
2893     Code = bitc::FUNC_CODE_INST_INDIRECTBR;
2894     Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
2895     // Encode the address operand as relative, but not the basic blocks.
2896     pushValue(I.getOperand(0), InstID, Vals);
2897     for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i)
2898       Vals.push_back(VE.getValueID(I.getOperand(i)));
2899     break;
2900 
2901   case Instruction::Invoke: {
2902     const InvokeInst *II = cast<InvokeInst>(&I);
2903     const Value *Callee = II->getCalledOperand();
2904     FunctionType *FTy = II->getFunctionType();
2905 
2906     if (II->hasOperandBundles())
2907       writeOperandBundles(*II, InstID);
2908 
2909     Code = bitc::FUNC_CODE_INST_INVOKE;
2910 
2911     Vals.push_back(VE.getAttributeListID(II->getAttributes()));
2912     Vals.push_back(II->getCallingConv() | 1 << 13);
2913     Vals.push_back(VE.getValueID(II->getNormalDest()));
2914     Vals.push_back(VE.getValueID(II->getUnwindDest()));
2915     Vals.push_back(VE.getTypeID(FTy));
2916     pushValueAndType(Callee, InstID, Vals);
2917 
2918     // Emit value #'s for the fixed parameters.
2919     for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
2920       pushValue(I.getOperand(i), InstID, Vals); // fixed param.
2921 
2922     // Emit type/value pairs for varargs params.
2923     if (FTy->isVarArg()) {
2924       for (unsigned i = FTy->getNumParams(), e = II->arg_size(); i != e; ++i)
2925         pushValueAndType(I.getOperand(i), InstID, Vals); // vararg
2926     }
2927     break;
2928   }
2929   case Instruction::Resume:
2930     Code = bitc::FUNC_CODE_INST_RESUME;
2931     pushValueAndType(I.getOperand(0), InstID, Vals);
2932     break;
2933   case Instruction::CleanupRet: {
2934     Code = bitc::FUNC_CODE_INST_CLEANUPRET;
2935     const auto &CRI = cast<CleanupReturnInst>(I);
2936     pushValue(CRI.getCleanupPad(), InstID, Vals);
2937     if (CRI.hasUnwindDest())
2938       Vals.push_back(VE.getValueID(CRI.getUnwindDest()));
2939     break;
2940   }
2941   case Instruction::CatchRet: {
2942     Code = bitc::FUNC_CODE_INST_CATCHRET;
2943     const auto &CRI = cast<CatchReturnInst>(I);
2944     pushValue(CRI.getCatchPad(), InstID, Vals);
2945     Vals.push_back(VE.getValueID(CRI.getSuccessor()));
2946     break;
2947   }
2948   case Instruction::CleanupPad:
2949   case Instruction::CatchPad: {
2950     const auto &FuncletPad = cast<FuncletPadInst>(I);
2951     Code = isa<CatchPadInst>(FuncletPad) ? bitc::FUNC_CODE_INST_CATCHPAD
2952                                          : bitc::FUNC_CODE_INST_CLEANUPPAD;
2953     pushValue(FuncletPad.getParentPad(), InstID, Vals);
2954 
2955     unsigned NumArgOperands = FuncletPad.getNumArgOperands();
2956     Vals.push_back(NumArgOperands);
2957     for (unsigned Op = 0; Op != NumArgOperands; ++Op)
2958       pushValueAndType(FuncletPad.getArgOperand(Op), InstID, Vals);
2959     break;
2960   }
2961   case Instruction::CatchSwitch: {
2962     Code = bitc::FUNC_CODE_INST_CATCHSWITCH;
2963     const auto &CatchSwitch = cast<CatchSwitchInst>(I);
2964 
2965     pushValue(CatchSwitch.getParentPad(), InstID, Vals);
2966 
2967     unsigned NumHandlers = CatchSwitch.getNumHandlers();
2968     Vals.push_back(NumHandlers);
2969     for (const BasicBlock *CatchPadBB : CatchSwitch.handlers())
2970       Vals.push_back(VE.getValueID(CatchPadBB));
2971 
2972     if (CatchSwitch.hasUnwindDest())
2973       Vals.push_back(VE.getValueID(CatchSwitch.getUnwindDest()));
2974     break;
2975   }
2976   case Instruction::CallBr: {
2977     const CallBrInst *CBI = cast<CallBrInst>(&I);
2978     const Value *Callee = CBI->getCalledOperand();
2979     FunctionType *FTy = CBI->getFunctionType();
2980 
2981     if (CBI->hasOperandBundles())
2982       writeOperandBundles(*CBI, InstID);
2983 
2984     Code = bitc::FUNC_CODE_INST_CALLBR;
2985 
2986     Vals.push_back(VE.getAttributeListID(CBI->getAttributes()));
2987 
2988     Vals.push_back(CBI->getCallingConv() << bitc::CALL_CCONV |
2989                    1 << bitc::CALL_EXPLICIT_TYPE);
2990 
2991     Vals.push_back(VE.getValueID(CBI->getDefaultDest()));
2992     Vals.push_back(CBI->getNumIndirectDests());
2993     for (unsigned i = 0, e = CBI->getNumIndirectDests(); i != e; ++i)
2994       Vals.push_back(VE.getValueID(CBI->getIndirectDest(i)));
2995 
2996     Vals.push_back(VE.getTypeID(FTy));
2997     pushValueAndType(Callee, InstID, Vals);
2998 
2999     // Emit value #'s for the fixed parameters.
3000     for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
3001       pushValue(I.getOperand(i), InstID, Vals); // fixed param.
3002 
3003     // Emit type/value pairs for varargs params.
3004     if (FTy->isVarArg()) {
3005       for (unsigned i = FTy->getNumParams(), e = CBI->arg_size(); i != e; ++i)
3006         pushValueAndType(I.getOperand(i), InstID, Vals); // vararg
3007     }
3008     break;
3009   }
3010   case Instruction::Unreachable:
3011     Code = bitc::FUNC_CODE_INST_UNREACHABLE;
3012     AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
3013     break;
3014 
3015   case Instruction::PHI: {
3016     const PHINode &PN = cast<PHINode>(I);
3017     Code = bitc::FUNC_CODE_INST_PHI;
3018     // With the newer instruction encoding, forward references could give
3019     // negative valued IDs.  This is most common for PHIs, so we use
3020     // signed VBRs.
3021     SmallVector<uint64_t, 128> Vals64;
3022     Vals64.push_back(VE.getTypeID(PN.getType()));
3023     for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
3024       pushValueSigned(PN.getIncomingValue(i), InstID, Vals64);
3025       Vals64.push_back(VE.getValueID(PN.getIncomingBlock(i)));
3026     }
3027 
3028     uint64_t Flags = getOptimizationFlags(&I);
3029     if (Flags != 0)
3030       Vals64.push_back(Flags);
3031 
3032     // Emit a Vals64 vector and exit.
3033     Stream.EmitRecord(Code, Vals64, AbbrevToUse);
3034     Vals64.clear();
3035     return;
3036   }
3037 
3038   case Instruction::LandingPad: {
3039     const LandingPadInst &LP = cast<LandingPadInst>(I);
3040     Code = bitc::FUNC_CODE_INST_LANDINGPAD;
3041     Vals.push_back(VE.getTypeID(LP.getType()));
3042     Vals.push_back(LP.isCleanup());
3043     Vals.push_back(LP.getNumClauses());
3044     for (unsigned I = 0, E = LP.getNumClauses(); I != E; ++I) {
3045       if (LP.isCatch(I))
3046         Vals.push_back(LandingPadInst::Catch);
3047       else
3048         Vals.push_back(LandingPadInst::Filter);
3049       pushValueAndType(LP.getClause(I), InstID, Vals);
3050     }
3051     break;
3052   }
3053 
3054   case Instruction::Alloca: {
3055     Code = bitc::FUNC_CODE_INST_ALLOCA;
3056     const AllocaInst &AI = cast<AllocaInst>(I);
3057     Vals.push_back(VE.getTypeID(AI.getAllocatedType()));
3058     Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
3059     Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
3060     using APV = AllocaPackedValues;
3061     unsigned Record = 0;
3062     unsigned EncodedAlign = getEncodedAlign(AI.getAlign());
3063     Bitfield::set<APV::AlignLower>(
3064         Record, EncodedAlign & ((1 << APV::AlignLower::Bits) - 1));
3065     Bitfield::set<APV::AlignUpper>(Record,
3066                                    EncodedAlign >> APV::AlignLower::Bits);
3067     Bitfield::set<APV::UsedWithInAlloca>(Record, AI.isUsedWithInAlloca());
3068     Bitfield::set<APV::ExplicitType>(Record, true);
3069     Bitfield::set<APV::SwiftError>(Record, AI.isSwiftError());
3070     Vals.push_back(Record);
3071     break;
3072   }
3073 
3074   case Instruction::Load:
3075     if (cast<LoadInst>(I).isAtomic()) {
3076       Code = bitc::FUNC_CODE_INST_LOADATOMIC;
3077       pushValueAndType(I.getOperand(0), InstID, Vals);
3078     } else {
3079       Code = bitc::FUNC_CODE_INST_LOAD;
3080       if (!pushValueAndType(I.getOperand(0), InstID, Vals)) // ptr
3081         AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
3082     }
3083     Vals.push_back(VE.getTypeID(I.getType()));
3084     Vals.push_back(getEncodedAlign(cast<LoadInst>(I).getAlign()));
3085     Vals.push_back(cast<LoadInst>(I).isVolatile());
3086     if (cast<LoadInst>(I).isAtomic()) {
3087       Vals.push_back(getEncodedOrdering(cast<LoadInst>(I).getOrdering()));
3088       Vals.push_back(getEncodedSyncScopeID(cast<LoadInst>(I).getSyncScopeID()));
3089     }
3090     break;
3091   case Instruction::Store:
3092     if (cast<StoreInst>(I).isAtomic())
3093       Code = bitc::FUNC_CODE_INST_STOREATOMIC;
3094     else
3095       Code = bitc::FUNC_CODE_INST_STORE;
3096     pushValueAndType(I.getOperand(1), InstID, Vals); // ptrty + ptr
3097     pushValueAndType(I.getOperand(0), InstID, Vals); // valty + val
3098     Vals.push_back(getEncodedAlign(cast<StoreInst>(I).getAlign()));
3099     Vals.push_back(cast<StoreInst>(I).isVolatile());
3100     if (cast<StoreInst>(I).isAtomic()) {
3101       Vals.push_back(getEncodedOrdering(cast<StoreInst>(I).getOrdering()));
3102       Vals.push_back(
3103           getEncodedSyncScopeID(cast<StoreInst>(I).getSyncScopeID()));
3104     }
3105     break;
3106   case Instruction::AtomicCmpXchg:
3107     Code = bitc::FUNC_CODE_INST_CMPXCHG;
3108     pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr
3109     pushValueAndType(I.getOperand(1), InstID, Vals); // cmp.
3110     pushValue(I.getOperand(2), InstID, Vals);        // newval.
3111     Vals.push_back(cast<AtomicCmpXchgInst>(I).isVolatile());
3112     Vals.push_back(
3113         getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getSuccessOrdering()));
3114     Vals.push_back(
3115         getEncodedSyncScopeID(cast<AtomicCmpXchgInst>(I).getSyncScopeID()));
3116     Vals.push_back(
3117         getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getFailureOrdering()));
3118     Vals.push_back(cast<AtomicCmpXchgInst>(I).isWeak());
3119     Vals.push_back(getEncodedAlign(cast<AtomicCmpXchgInst>(I).getAlign()));
3120     break;
3121   case Instruction::AtomicRMW:
3122     Code = bitc::FUNC_CODE_INST_ATOMICRMW;
3123     pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr
3124     pushValueAndType(I.getOperand(1), InstID, Vals); // valty + val
3125     Vals.push_back(
3126         getEncodedRMWOperation(cast<AtomicRMWInst>(I).getOperation()));
3127     Vals.push_back(cast<AtomicRMWInst>(I).isVolatile());
3128     Vals.push_back(getEncodedOrdering(cast<AtomicRMWInst>(I).getOrdering()));
3129     Vals.push_back(
3130         getEncodedSyncScopeID(cast<AtomicRMWInst>(I).getSyncScopeID()));
3131     Vals.push_back(getEncodedAlign(cast<AtomicRMWInst>(I).getAlign()));
3132     break;
3133   case Instruction::Fence:
3134     Code = bitc::FUNC_CODE_INST_FENCE;
3135     Vals.push_back(getEncodedOrdering(cast<FenceInst>(I).getOrdering()));
3136     Vals.push_back(getEncodedSyncScopeID(cast<FenceInst>(I).getSyncScopeID()));
3137     break;
3138   case Instruction::Call: {
3139     const CallInst &CI = cast<CallInst>(I);
3140     FunctionType *FTy = CI.getFunctionType();
3141 
3142     if (CI.hasOperandBundles())
3143       writeOperandBundles(CI, InstID);
3144 
3145     Code = bitc::FUNC_CODE_INST_CALL;
3146 
3147     Vals.push_back(VE.getAttributeListID(CI.getAttributes()));
3148 
3149     unsigned Flags = getOptimizationFlags(&I);
3150     Vals.push_back(CI.getCallingConv() << bitc::CALL_CCONV |
3151                    unsigned(CI.isTailCall()) << bitc::CALL_TAIL |
3152                    unsigned(CI.isMustTailCall()) << bitc::CALL_MUSTTAIL |
3153                    1 << bitc::CALL_EXPLICIT_TYPE |
3154                    unsigned(CI.isNoTailCall()) << bitc::CALL_NOTAIL |
3155                    unsigned(Flags != 0) << bitc::CALL_FMF);
3156     if (Flags != 0)
3157       Vals.push_back(Flags);
3158 
3159     Vals.push_back(VE.getTypeID(FTy));
3160     pushValueAndType(CI.getCalledOperand(), InstID, Vals); // Callee
3161 
3162     // Emit value #'s for the fixed parameters.
3163     for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
3164       // Check for labels (can happen with asm labels).
3165       if (FTy->getParamType(i)->isLabelTy())
3166         Vals.push_back(VE.getValueID(CI.getArgOperand(i)));
3167       else
3168         pushValue(CI.getArgOperand(i), InstID, Vals); // fixed param.
3169     }
3170 
3171     // Emit type/value pairs for varargs params.
3172     if (FTy->isVarArg()) {
3173       for (unsigned i = FTy->getNumParams(), e = CI.arg_size(); i != e; ++i)
3174         pushValueAndType(CI.getArgOperand(i), InstID, Vals); // varargs
3175     }
3176     break;
3177   }
3178   case Instruction::VAArg:
3179     Code = bitc::FUNC_CODE_INST_VAARG;
3180     Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));   // valistty
3181     pushValue(I.getOperand(0), InstID, Vals);                   // valist.
3182     Vals.push_back(VE.getTypeID(I.getType())); // restype.
3183     break;
3184   case Instruction::Freeze:
3185     Code = bitc::FUNC_CODE_INST_FREEZE;
3186     pushValueAndType(I.getOperand(0), InstID, Vals);
3187     break;
3188   }
3189 
3190   Stream.EmitRecord(Code, Vals, AbbrevToUse);
3191   Vals.clear();
3192 }
3193 
3194 /// Write a GlobalValue VST to the module. The purpose of this data structure is
3195 /// to allow clients to efficiently find the function body.
3196 void ModuleBitcodeWriter::writeGlobalValueSymbolTable(
3197   DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) {
3198   // Get the offset of the VST we are writing, and backpatch it into
3199   // the VST forward declaration record.
3200   uint64_t VSTOffset = Stream.GetCurrentBitNo();
3201   // The BitcodeStartBit was the stream offset of the identification block.
3202   VSTOffset -= bitcodeStartBit();
3203   assert((VSTOffset & 31) == 0 && "VST block not 32-bit aligned");
3204   // Note that we add 1 here because the offset is relative to one word
3205   // before the start of the identification block, which was historically
3206   // always the start of the regular bitcode header.
3207   Stream.BackpatchWord(VSTOffsetPlaceholder, VSTOffset / 32 + 1);
3208 
3209   Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
3210 
3211   auto Abbv = std::make_shared<BitCodeAbbrev>();
3212   Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_FNENTRY));
3213   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
3214   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // funcoffset
3215   unsigned FnEntryAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3216 
3217   for (const Function &F : M) {
3218     uint64_t Record[2];
3219 
3220     if (F.isDeclaration())
3221       continue;
3222 
3223     Record[0] = VE.getValueID(&F);
3224 
3225     // Save the word offset of the function (from the start of the
3226     // actual bitcode written to the stream).
3227     uint64_t BitcodeIndex = FunctionToBitcodeIndex[&F] - bitcodeStartBit();
3228     assert((BitcodeIndex & 31) == 0 && "function block not 32-bit aligned");
3229     // Note that we add 1 here because the offset is relative to one word
3230     // before the start of the identification block, which was historically
3231     // always the start of the regular bitcode header.
3232     Record[1] = BitcodeIndex / 32 + 1;
3233 
3234     Stream.EmitRecord(bitc::VST_CODE_FNENTRY, Record, FnEntryAbbrev);
3235   }
3236 
3237   Stream.ExitBlock();
3238 }
3239 
3240 /// Emit names for arguments, instructions and basic blocks in a function.
3241 void ModuleBitcodeWriter::writeFunctionLevelValueSymbolTable(
3242     const ValueSymbolTable &VST) {
3243   if (VST.empty())
3244     return;
3245 
3246   Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
3247 
3248   // FIXME: Set up the abbrev, we know how many values there are!
3249   // FIXME: We know if the type names can use 7-bit ascii.
3250   SmallVector<uint64_t, 64> NameVals;
3251 
3252   for (const ValueName &Name : VST) {
3253     // Figure out the encoding to use for the name.
3254     StringEncoding Bits = getStringEncoding(Name.getKey());
3255 
3256     unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
3257     NameVals.push_back(VE.getValueID(Name.getValue()));
3258 
3259     // VST_CODE_ENTRY:   [valueid, namechar x N]
3260     // VST_CODE_BBENTRY: [bbid, namechar x N]
3261     unsigned Code;
3262     if (isa<BasicBlock>(Name.getValue())) {
3263       Code = bitc::VST_CODE_BBENTRY;
3264       if (Bits == SE_Char6)
3265         AbbrevToUse = VST_BBENTRY_6_ABBREV;
3266     } else {
3267       Code = bitc::VST_CODE_ENTRY;
3268       if (Bits == SE_Char6)
3269         AbbrevToUse = VST_ENTRY_6_ABBREV;
3270       else if (Bits == SE_Fixed7)
3271         AbbrevToUse = VST_ENTRY_7_ABBREV;
3272     }
3273 
3274     for (const auto P : Name.getKey())
3275       NameVals.push_back((unsigned char)P);
3276 
3277     // Emit the finished record.
3278     Stream.EmitRecord(Code, NameVals, AbbrevToUse);
3279     NameVals.clear();
3280   }
3281 
3282   Stream.ExitBlock();
3283 }
3284 
3285 void ModuleBitcodeWriter::writeUseList(UseListOrder &&Order) {
3286   assert(Order.Shuffle.size() >= 2 && "Shuffle too small");
3287   unsigned Code;
3288   if (isa<BasicBlock>(Order.V))
3289     Code = bitc::USELIST_CODE_BB;
3290   else
3291     Code = bitc::USELIST_CODE_DEFAULT;
3292 
3293   SmallVector<uint64_t, 64> Record(Order.Shuffle.begin(), Order.Shuffle.end());
3294   Record.push_back(VE.getValueID(Order.V));
3295   Stream.EmitRecord(Code, Record);
3296 }
3297 
3298 void ModuleBitcodeWriter::writeUseListBlock(const Function *F) {
3299   assert(VE.shouldPreserveUseListOrder() &&
3300          "Expected to be preserving use-list order");
3301 
3302   auto hasMore = [&]() {
3303     return !VE.UseListOrders.empty() && VE.UseListOrders.back().F == F;
3304   };
3305   if (!hasMore())
3306     // Nothing to do.
3307     return;
3308 
3309   Stream.EnterSubblock(bitc::USELIST_BLOCK_ID, 3);
3310   while (hasMore()) {
3311     writeUseList(std::move(VE.UseListOrders.back()));
3312     VE.UseListOrders.pop_back();
3313   }
3314   Stream.ExitBlock();
3315 }
3316 
3317 /// Emit a function body to the module stream.
3318 void ModuleBitcodeWriter::writeFunction(
3319     const Function &F,
3320     DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) {
3321   // Save the bitcode index of the start of this function block for recording
3322   // in the VST.
3323   FunctionToBitcodeIndex[&F] = Stream.GetCurrentBitNo();
3324 
3325   Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 4);
3326   VE.incorporateFunction(F);
3327 
3328   SmallVector<unsigned, 64> Vals;
3329 
3330   // Emit the number of basic blocks, so the reader can create them ahead of
3331   // time.
3332   Vals.push_back(VE.getBasicBlocks().size());
3333   Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals);
3334   Vals.clear();
3335 
3336   // If there are function-local constants, emit them now.
3337   unsigned CstStart, CstEnd;
3338   VE.getFunctionConstantRange(CstStart, CstEnd);
3339   writeConstants(CstStart, CstEnd, false);
3340 
3341   // If there is function-local metadata, emit it now.
3342   writeFunctionMetadata(F);
3343 
3344   // Keep a running idea of what the instruction ID is.
3345   unsigned InstID = CstEnd;
3346 
3347   bool NeedsMetadataAttachment = F.hasMetadata();
3348 
3349   DILocation *LastDL = nullptr;
3350   // Finally, emit all the instructions, in order.
3351   for (const BasicBlock &BB : F)
3352     for (const Instruction &I : BB) {
3353       writeInstruction(I, InstID, Vals);
3354 
3355       if (!I.getType()->isVoidTy())
3356         ++InstID;
3357 
3358       // If the instruction has metadata, write a metadata attachment later.
3359       NeedsMetadataAttachment |= I.hasMetadataOtherThanDebugLoc();
3360 
3361       // If the instruction has a debug location, emit it.
3362       DILocation *DL = I.getDebugLoc();
3363       if (!DL)
3364         continue;
3365 
3366       if (DL == LastDL) {
3367         // Just repeat the same debug loc as last time.
3368         Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC_AGAIN, Vals);
3369         continue;
3370       }
3371 
3372       Vals.push_back(DL->getLine());
3373       Vals.push_back(DL->getColumn());
3374       Vals.push_back(VE.getMetadataOrNullID(DL->getScope()));
3375       Vals.push_back(VE.getMetadataOrNullID(DL->getInlinedAt()));
3376       Vals.push_back(DL->isImplicitCode());
3377       Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC, Vals);
3378       Vals.clear();
3379 
3380       LastDL = DL;
3381     }
3382 
3383   // Emit names for all the instructions etc.
3384   if (auto *Symtab = F.getValueSymbolTable())
3385     writeFunctionLevelValueSymbolTable(*Symtab);
3386 
3387   if (NeedsMetadataAttachment)
3388     writeFunctionMetadataAttachment(F);
3389   if (VE.shouldPreserveUseListOrder())
3390     writeUseListBlock(&F);
3391   VE.purgeFunction();
3392   Stream.ExitBlock();
3393 }
3394 
3395 // Emit blockinfo, which defines the standard abbreviations etc.
3396 void ModuleBitcodeWriter::writeBlockInfo() {
3397   // We only want to emit block info records for blocks that have multiple
3398   // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK.
3399   // Other blocks can define their abbrevs inline.
3400   Stream.EnterBlockInfoBlock();
3401 
3402   { // 8-bit fixed-width VST_CODE_ENTRY/VST_CODE_BBENTRY strings.
3403     auto Abbv = std::make_shared<BitCodeAbbrev>();
3404     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3));
3405     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3406     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3407     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
3408     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
3409         VST_ENTRY_8_ABBREV)
3410       llvm_unreachable("Unexpected abbrev ordering!");
3411   }
3412 
3413   { // 7-bit fixed width VST_CODE_ENTRY strings.
3414     auto Abbv = std::make_shared<BitCodeAbbrev>();
3415     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
3416     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3417     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3418     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
3419     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
3420         VST_ENTRY_7_ABBREV)
3421       llvm_unreachable("Unexpected abbrev ordering!");
3422   }
3423   { // 6-bit char6 VST_CODE_ENTRY strings.
3424     auto Abbv = std::make_shared<BitCodeAbbrev>();
3425     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
3426     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3427     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3428     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
3429     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
3430         VST_ENTRY_6_ABBREV)
3431       llvm_unreachable("Unexpected abbrev ordering!");
3432   }
3433   { // 6-bit char6 VST_CODE_BBENTRY strings.
3434     auto Abbv = std::make_shared<BitCodeAbbrev>();
3435     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY));
3436     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3437     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3438     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
3439     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
3440         VST_BBENTRY_6_ABBREV)
3441       llvm_unreachable("Unexpected abbrev ordering!");
3442   }
3443 
3444   { // SETTYPE abbrev for CONSTANTS_BLOCK.
3445     auto Abbv = std::make_shared<BitCodeAbbrev>();
3446     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_SETTYPE));
3447     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
3448                               VE.computeBitsRequiredForTypeIndicies()));
3449     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
3450         CONSTANTS_SETTYPE_ABBREV)
3451       llvm_unreachable("Unexpected abbrev ordering!");
3452   }
3453 
3454   { // INTEGER abbrev for CONSTANTS_BLOCK.
3455     auto Abbv = std::make_shared<BitCodeAbbrev>();
3456     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_INTEGER));
3457     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3458     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
3459         CONSTANTS_INTEGER_ABBREV)
3460       llvm_unreachable("Unexpected abbrev ordering!");
3461   }
3462 
3463   { // CE_CAST abbrev for CONSTANTS_BLOCK.
3464     auto Abbv = std::make_shared<BitCodeAbbrev>();
3465     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CE_CAST));
3466     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4));  // cast opc
3467     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,       // typeid
3468                               VE.computeBitsRequiredForTypeIndicies()));
3469     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));    // value id
3470 
3471     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
3472         CONSTANTS_CE_CAST_Abbrev)
3473       llvm_unreachable("Unexpected abbrev ordering!");
3474   }
3475   { // NULL abbrev for CONSTANTS_BLOCK.
3476     auto Abbv = std::make_shared<BitCodeAbbrev>();
3477     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_NULL));
3478     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
3479         CONSTANTS_NULL_Abbrev)
3480       llvm_unreachable("Unexpected abbrev ordering!");
3481   }
3482 
3483   // FIXME: This should only use space for first class types!
3484 
3485   { // INST_LOAD abbrev for FUNCTION_BLOCK.
3486     auto Abbv = std::make_shared<BitCodeAbbrev>();
3487     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_LOAD));
3488     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Ptr
3489     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,    // dest ty
3490                               VE.computeBitsRequiredForTypeIndicies()));
3491     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align
3492     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile
3493     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3494         FUNCTION_INST_LOAD_ABBREV)
3495       llvm_unreachable("Unexpected abbrev ordering!");
3496   }
3497   { // INST_UNOP abbrev for FUNCTION_BLOCK.
3498     auto Abbv = std::make_shared<BitCodeAbbrev>();
3499     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNOP));
3500     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
3501     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3502     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3503         FUNCTION_INST_UNOP_ABBREV)
3504       llvm_unreachable("Unexpected abbrev ordering!");
3505   }
3506   { // INST_UNOP_FLAGS abbrev for FUNCTION_BLOCK.
3507     auto Abbv = std::make_shared<BitCodeAbbrev>();
3508     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNOP));
3509     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
3510     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3511     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); // flags
3512     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3513         FUNCTION_INST_UNOP_FLAGS_ABBREV)
3514       llvm_unreachable("Unexpected abbrev ordering!");
3515   }
3516   { // INST_BINOP abbrev for FUNCTION_BLOCK.
3517     auto Abbv = std::make_shared<BitCodeAbbrev>();
3518     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
3519     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
3520     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
3521     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3522     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3523         FUNCTION_INST_BINOP_ABBREV)
3524       llvm_unreachable("Unexpected abbrev ordering!");
3525   }
3526   { // INST_BINOP_FLAGS abbrev for FUNCTION_BLOCK.
3527     auto Abbv = std::make_shared<BitCodeAbbrev>();
3528     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
3529     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
3530     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
3531     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3532     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); // flags
3533     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3534         FUNCTION_INST_BINOP_FLAGS_ABBREV)
3535       llvm_unreachable("Unexpected abbrev ordering!");
3536   }
3537   { // INST_CAST abbrev for FUNCTION_BLOCK.
3538     auto Abbv = std::make_shared<BitCodeAbbrev>();
3539     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST));
3540     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));    // OpVal
3541     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,       // dest ty
3542                               VE.computeBitsRequiredForTypeIndicies()));
3543     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4));  // opc
3544     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3545         FUNCTION_INST_CAST_ABBREV)
3546       llvm_unreachable("Unexpected abbrev ordering!");
3547   }
3548 
3549   { // INST_RET abbrev for FUNCTION_BLOCK.
3550     auto Abbv = std::make_shared<BitCodeAbbrev>();
3551     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
3552     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3553         FUNCTION_INST_RET_VOID_ABBREV)
3554       llvm_unreachable("Unexpected abbrev ordering!");
3555   }
3556   { // INST_RET abbrev for FUNCTION_BLOCK.
3557     auto Abbv = std::make_shared<BitCodeAbbrev>();
3558     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
3559     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ValID
3560     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3561         FUNCTION_INST_RET_VAL_ABBREV)
3562       llvm_unreachable("Unexpected abbrev ordering!");
3563   }
3564   { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK.
3565     auto Abbv = std::make_shared<BitCodeAbbrev>();
3566     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNREACHABLE));
3567     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3568         FUNCTION_INST_UNREACHABLE_ABBREV)
3569       llvm_unreachable("Unexpected abbrev ordering!");
3570   }
3571   {
3572     auto Abbv = std::make_shared<BitCodeAbbrev>();
3573     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_GEP));
3574     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
3575     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
3576                               Log2_32_Ceil(VE.getTypes().size() + 1)));
3577     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3578     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
3579     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3580         FUNCTION_INST_GEP_ABBREV)
3581       llvm_unreachable("Unexpected abbrev ordering!");
3582   }
3583 
3584   Stream.ExitBlock();
3585 }
3586 
3587 /// Write the module path strings, currently only used when generating
3588 /// a combined index file.
3589 void IndexBitcodeWriter::writeModStrings() {
3590   Stream.EnterSubblock(bitc::MODULE_STRTAB_BLOCK_ID, 3);
3591 
3592   // TODO: See which abbrev sizes we actually need to emit
3593 
3594   // 8-bit fixed-width MST_ENTRY strings.
3595   auto Abbv = std::make_shared<BitCodeAbbrev>();
3596   Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
3597   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3598   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3599   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
3600   unsigned Abbrev8Bit = Stream.EmitAbbrev(std::move(Abbv));
3601 
3602   // 7-bit fixed width MST_ENTRY strings.
3603   Abbv = std::make_shared<BitCodeAbbrev>();
3604   Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
3605   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3606   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3607   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
3608   unsigned Abbrev7Bit = Stream.EmitAbbrev(std::move(Abbv));
3609 
3610   // 6-bit char6 MST_ENTRY strings.
3611   Abbv = std::make_shared<BitCodeAbbrev>();
3612   Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
3613   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3614   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3615   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
3616   unsigned Abbrev6Bit = Stream.EmitAbbrev(std::move(Abbv));
3617 
3618   // Module Hash, 160 bits SHA1. Optionally, emitted after each MST_CODE_ENTRY.
3619   Abbv = std::make_shared<BitCodeAbbrev>();
3620   Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_HASH));
3621   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3622   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3623   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3624   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3625   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3626   unsigned AbbrevHash = Stream.EmitAbbrev(std::move(Abbv));
3627 
3628   SmallVector<unsigned, 64> Vals;
3629   forEachModule(
3630       [&](const StringMapEntry<std::pair<uint64_t, ModuleHash>> &MPSE) {
3631         StringRef Key = MPSE.getKey();
3632         const auto &Value = MPSE.getValue();
3633         StringEncoding Bits = getStringEncoding(Key);
3634         unsigned AbbrevToUse = Abbrev8Bit;
3635         if (Bits == SE_Char6)
3636           AbbrevToUse = Abbrev6Bit;
3637         else if (Bits == SE_Fixed7)
3638           AbbrevToUse = Abbrev7Bit;
3639 
3640         Vals.push_back(Value.first);
3641         Vals.append(Key.begin(), Key.end());
3642 
3643         // Emit the finished record.
3644         Stream.EmitRecord(bitc::MST_CODE_ENTRY, Vals, AbbrevToUse);
3645 
3646         // Emit an optional hash for the module now
3647         const auto &Hash = Value.second;
3648         if (llvm::any_of(Hash, [](uint32_t H) { return H; })) {
3649           Vals.assign(Hash.begin(), Hash.end());
3650           // Emit the hash record.
3651           Stream.EmitRecord(bitc::MST_CODE_HASH, Vals, AbbrevHash);
3652         }
3653 
3654         Vals.clear();
3655       });
3656   Stream.ExitBlock();
3657 }
3658 
3659 /// Write the function type metadata related records that need to appear before
3660 /// a function summary entry (whether per-module or combined).
3661 template <typename Fn>
3662 static void writeFunctionTypeMetadataRecords(BitstreamWriter &Stream,
3663                                              FunctionSummary *FS,
3664                                              Fn GetValueID) {
3665   if (!FS->type_tests().empty())
3666     Stream.EmitRecord(bitc::FS_TYPE_TESTS, FS->type_tests());
3667 
3668   SmallVector<uint64_t, 64> Record;
3669 
3670   auto WriteVFuncIdVec = [&](uint64_t Ty,
3671                              ArrayRef<FunctionSummary::VFuncId> VFs) {
3672     if (VFs.empty())
3673       return;
3674     Record.clear();
3675     for (auto &VF : VFs) {
3676       Record.push_back(VF.GUID);
3677       Record.push_back(VF.Offset);
3678     }
3679     Stream.EmitRecord(Ty, Record);
3680   };
3681 
3682   WriteVFuncIdVec(bitc::FS_TYPE_TEST_ASSUME_VCALLS,
3683                   FS->type_test_assume_vcalls());
3684   WriteVFuncIdVec(bitc::FS_TYPE_CHECKED_LOAD_VCALLS,
3685                   FS->type_checked_load_vcalls());
3686 
3687   auto WriteConstVCallVec = [&](uint64_t Ty,
3688                                 ArrayRef<FunctionSummary::ConstVCall> VCs) {
3689     for (auto &VC : VCs) {
3690       Record.clear();
3691       Record.push_back(VC.VFunc.GUID);
3692       Record.push_back(VC.VFunc.Offset);
3693       llvm::append_range(Record, VC.Args);
3694       Stream.EmitRecord(Ty, Record);
3695     }
3696   };
3697 
3698   WriteConstVCallVec(bitc::FS_TYPE_TEST_ASSUME_CONST_VCALL,
3699                      FS->type_test_assume_const_vcalls());
3700   WriteConstVCallVec(bitc::FS_TYPE_CHECKED_LOAD_CONST_VCALL,
3701                      FS->type_checked_load_const_vcalls());
3702 
3703   auto WriteRange = [&](ConstantRange Range) {
3704     Range = Range.sextOrTrunc(FunctionSummary::ParamAccess::RangeWidth);
3705     assert(Range.getLower().getNumWords() == 1);
3706     assert(Range.getUpper().getNumWords() == 1);
3707     emitSignedInt64(Record, *Range.getLower().getRawData());
3708     emitSignedInt64(Record, *Range.getUpper().getRawData());
3709   };
3710 
3711   if (!FS->paramAccesses().empty()) {
3712     Record.clear();
3713     for (auto &Arg : FS->paramAccesses()) {
3714       size_t UndoSize = Record.size();
3715       Record.push_back(Arg.ParamNo);
3716       WriteRange(Arg.Use);
3717       Record.push_back(Arg.Calls.size());
3718       for (auto &Call : Arg.Calls) {
3719         Record.push_back(Call.ParamNo);
3720         Optional<unsigned> ValueID = GetValueID(Call.Callee);
3721         if (!ValueID) {
3722           // If ValueID is unknown we can't drop just this call, we must drop
3723           // entire parameter.
3724           Record.resize(UndoSize);
3725           break;
3726         }
3727         Record.push_back(*ValueID);
3728         WriteRange(Call.Offsets);
3729       }
3730     }
3731     if (!Record.empty())
3732       Stream.EmitRecord(bitc::FS_PARAM_ACCESS, Record);
3733   }
3734 }
3735 
3736 /// Collect type IDs from type tests used by function.
3737 static void
3738 getReferencedTypeIds(FunctionSummary *FS,
3739                      std::set<GlobalValue::GUID> &ReferencedTypeIds) {
3740   if (!FS->type_tests().empty())
3741     for (auto &TT : FS->type_tests())
3742       ReferencedTypeIds.insert(TT);
3743 
3744   auto GetReferencedTypesFromVFuncIdVec =
3745       [&](ArrayRef<FunctionSummary::VFuncId> VFs) {
3746         for (auto &VF : VFs)
3747           ReferencedTypeIds.insert(VF.GUID);
3748       };
3749 
3750   GetReferencedTypesFromVFuncIdVec(FS->type_test_assume_vcalls());
3751   GetReferencedTypesFromVFuncIdVec(FS->type_checked_load_vcalls());
3752 
3753   auto GetReferencedTypesFromConstVCallVec =
3754       [&](ArrayRef<FunctionSummary::ConstVCall> VCs) {
3755         for (auto &VC : VCs)
3756           ReferencedTypeIds.insert(VC.VFunc.GUID);
3757       };
3758 
3759   GetReferencedTypesFromConstVCallVec(FS->type_test_assume_const_vcalls());
3760   GetReferencedTypesFromConstVCallVec(FS->type_checked_load_const_vcalls());
3761 }
3762 
3763 static void writeWholeProgramDevirtResolutionByArg(
3764     SmallVector<uint64_t, 64> &NameVals, const std::vector<uint64_t> &args,
3765     const WholeProgramDevirtResolution::ByArg &ByArg) {
3766   NameVals.push_back(args.size());
3767   llvm::append_range(NameVals, args);
3768 
3769   NameVals.push_back(ByArg.TheKind);
3770   NameVals.push_back(ByArg.Info);
3771   NameVals.push_back(ByArg.Byte);
3772   NameVals.push_back(ByArg.Bit);
3773 }
3774 
3775 static void writeWholeProgramDevirtResolution(
3776     SmallVector<uint64_t, 64> &NameVals, StringTableBuilder &StrtabBuilder,
3777     uint64_t Id, const WholeProgramDevirtResolution &Wpd) {
3778   NameVals.push_back(Id);
3779 
3780   NameVals.push_back(Wpd.TheKind);
3781   NameVals.push_back(StrtabBuilder.add(Wpd.SingleImplName));
3782   NameVals.push_back(Wpd.SingleImplName.size());
3783 
3784   NameVals.push_back(Wpd.ResByArg.size());
3785   for (auto &A : Wpd.ResByArg)
3786     writeWholeProgramDevirtResolutionByArg(NameVals, A.first, A.second);
3787 }
3788 
3789 static void writeTypeIdSummaryRecord(SmallVector<uint64_t, 64> &NameVals,
3790                                      StringTableBuilder &StrtabBuilder,
3791                                      const std::string &Id,
3792                                      const TypeIdSummary &Summary) {
3793   NameVals.push_back(StrtabBuilder.add(Id));
3794   NameVals.push_back(Id.size());
3795 
3796   NameVals.push_back(Summary.TTRes.TheKind);
3797   NameVals.push_back(Summary.TTRes.SizeM1BitWidth);
3798   NameVals.push_back(Summary.TTRes.AlignLog2);
3799   NameVals.push_back(Summary.TTRes.SizeM1);
3800   NameVals.push_back(Summary.TTRes.BitMask);
3801   NameVals.push_back(Summary.TTRes.InlineBits);
3802 
3803   for (auto &W : Summary.WPDRes)
3804     writeWholeProgramDevirtResolution(NameVals, StrtabBuilder, W.first,
3805                                       W.second);
3806 }
3807 
3808 static void writeTypeIdCompatibleVtableSummaryRecord(
3809     SmallVector<uint64_t, 64> &NameVals, StringTableBuilder &StrtabBuilder,
3810     const std::string &Id, const TypeIdCompatibleVtableInfo &Summary,
3811     ValueEnumerator &VE) {
3812   NameVals.push_back(StrtabBuilder.add(Id));
3813   NameVals.push_back(Id.size());
3814 
3815   for (auto &P : Summary) {
3816     NameVals.push_back(P.AddressPointOffset);
3817     NameVals.push_back(VE.getValueID(P.VTableVI.getValue()));
3818   }
3819 }
3820 
3821 // Helper to emit a single function summary record.
3822 void ModuleBitcodeWriterBase::writePerModuleFunctionSummaryRecord(
3823     SmallVector<uint64_t, 64> &NameVals, GlobalValueSummary *Summary,
3824     unsigned ValueID, unsigned FSCallsAbbrev, unsigned FSCallsProfileAbbrev,
3825     const Function &F) {
3826   NameVals.push_back(ValueID);
3827 
3828   FunctionSummary *FS = cast<FunctionSummary>(Summary);
3829 
3830   writeFunctionTypeMetadataRecords(
3831       Stream, FS, [&](const ValueInfo &VI) -> Optional<unsigned> {
3832         return {VE.getValueID(VI.getValue())};
3833       });
3834 
3835   auto SpecialRefCnts = FS->specialRefCounts();
3836   NameVals.push_back(getEncodedGVSummaryFlags(FS->flags()));
3837   NameVals.push_back(FS->instCount());
3838   NameVals.push_back(getEncodedFFlags(FS->fflags()));
3839   NameVals.push_back(FS->refs().size());
3840   NameVals.push_back(SpecialRefCnts.first);  // rorefcnt
3841   NameVals.push_back(SpecialRefCnts.second); // worefcnt
3842 
3843   for (auto &RI : FS->refs())
3844     NameVals.push_back(VE.getValueID(RI.getValue()));
3845 
3846   bool HasProfileData =
3847       F.hasProfileData() || ForceSummaryEdgesCold != FunctionSummary::FSHT_None;
3848   for (auto &ECI : FS->calls()) {
3849     NameVals.push_back(getValueId(ECI.first));
3850     if (HasProfileData)
3851       NameVals.push_back(static_cast<uint8_t>(ECI.second.Hotness));
3852     else if (WriteRelBFToSummary)
3853       NameVals.push_back(ECI.second.RelBlockFreq);
3854   }
3855 
3856   unsigned FSAbbrev = (HasProfileData ? FSCallsProfileAbbrev : FSCallsAbbrev);
3857   unsigned Code =
3858       (HasProfileData ? bitc::FS_PERMODULE_PROFILE
3859                       : (WriteRelBFToSummary ? bitc::FS_PERMODULE_RELBF
3860                                              : bitc::FS_PERMODULE));
3861 
3862   // Emit the finished record.
3863   Stream.EmitRecord(Code, NameVals, FSAbbrev);
3864   NameVals.clear();
3865 }
3866 
3867 // Collect the global value references in the given variable's initializer,
3868 // and emit them in a summary record.
3869 void ModuleBitcodeWriterBase::writeModuleLevelReferences(
3870     const GlobalVariable &V, SmallVector<uint64_t, 64> &NameVals,
3871     unsigned FSModRefsAbbrev, unsigned FSModVTableRefsAbbrev) {
3872   auto VI = Index->getValueInfo(V.getGUID());
3873   if (!VI || VI.getSummaryList().empty()) {
3874     // Only declarations should not have a summary (a declaration might however
3875     // have a summary if the def was in module level asm).
3876     assert(V.isDeclaration());
3877     return;
3878   }
3879   auto *Summary = VI.getSummaryList()[0].get();
3880   NameVals.push_back(VE.getValueID(&V));
3881   GlobalVarSummary *VS = cast<GlobalVarSummary>(Summary);
3882   NameVals.push_back(getEncodedGVSummaryFlags(VS->flags()));
3883   NameVals.push_back(getEncodedGVarFlags(VS->varflags()));
3884 
3885   auto VTableFuncs = VS->vTableFuncs();
3886   if (!VTableFuncs.empty())
3887     NameVals.push_back(VS->refs().size());
3888 
3889   unsigned SizeBeforeRefs = NameVals.size();
3890   for (auto &RI : VS->refs())
3891     NameVals.push_back(VE.getValueID(RI.getValue()));
3892   // Sort the refs for determinism output, the vector returned by FS->refs() has
3893   // been initialized from a DenseSet.
3894   llvm::sort(drop_begin(NameVals, SizeBeforeRefs));
3895 
3896   if (VTableFuncs.empty())
3897     Stream.EmitRecord(bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS, NameVals,
3898                       FSModRefsAbbrev);
3899   else {
3900     // VTableFuncs pairs should already be sorted by offset.
3901     for (auto &P : VTableFuncs) {
3902       NameVals.push_back(VE.getValueID(P.FuncVI.getValue()));
3903       NameVals.push_back(P.VTableOffset);
3904     }
3905 
3906     Stream.EmitRecord(bitc::FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS, NameVals,
3907                       FSModVTableRefsAbbrev);
3908   }
3909   NameVals.clear();
3910 }
3911 
3912 /// Emit the per-module summary section alongside the rest of
3913 /// the module's bitcode.
3914 void ModuleBitcodeWriterBase::writePerModuleGlobalValueSummary() {
3915   // By default we compile with ThinLTO if the module has a summary, but the
3916   // client can request full LTO with a module flag.
3917   bool IsThinLTO = true;
3918   if (auto *MD =
3919           mdconst::extract_or_null<ConstantInt>(M.getModuleFlag("ThinLTO")))
3920     IsThinLTO = MD->getZExtValue();
3921   Stream.EnterSubblock(IsThinLTO ? bitc::GLOBALVAL_SUMMARY_BLOCK_ID
3922                                  : bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID,
3923                        4);
3924 
3925   Stream.EmitRecord(
3926       bitc::FS_VERSION,
3927       ArrayRef<uint64_t>{ModuleSummaryIndex::BitcodeSummaryVersion});
3928 
3929   // Write the index flags.
3930   uint64_t Flags = 0;
3931   // Bits 1-3 are set only in the combined index, skip them.
3932   if (Index->enableSplitLTOUnit())
3933     Flags |= 0x8;
3934   Stream.EmitRecord(bitc::FS_FLAGS, ArrayRef<uint64_t>{Flags});
3935 
3936   if (Index->begin() == Index->end()) {
3937     Stream.ExitBlock();
3938     return;
3939   }
3940 
3941   for (const auto &GVI : valueIds()) {
3942     Stream.EmitRecord(bitc::FS_VALUE_GUID,
3943                       ArrayRef<uint64_t>{GVI.second, GVI.first});
3944   }
3945 
3946   // Abbrev for FS_PERMODULE_PROFILE.
3947   auto Abbv = std::make_shared<BitCodeAbbrev>();
3948   Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_PROFILE));
3949   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // valueid
3950   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // flags
3951   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // instcount
3952   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // fflags
3953   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // numrefs
3954   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // rorefcnt
3955   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // worefcnt
3956   // numrefs x valueid, n x (valueid, hotness)
3957   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3958   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3959   unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3960 
3961   // Abbrev for FS_PERMODULE or FS_PERMODULE_RELBF.
3962   Abbv = std::make_shared<BitCodeAbbrev>();
3963   if (WriteRelBFToSummary)
3964     Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_RELBF));
3965   else
3966     Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE));
3967   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // valueid
3968   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // flags
3969   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // instcount
3970   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // fflags
3971   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // numrefs
3972   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // rorefcnt
3973   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // worefcnt
3974   // numrefs x valueid, n x (valueid [, rel_block_freq])
3975   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3976   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3977   unsigned FSCallsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3978 
3979   // Abbrev for FS_PERMODULE_GLOBALVAR_INIT_REFS.
3980   Abbv = std::make_shared<BitCodeAbbrev>();
3981   Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS));
3982   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
3983   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
3984   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));  // valueids
3985   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3986   unsigned FSModRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3987 
3988   // Abbrev for FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS.
3989   Abbv = std::make_shared<BitCodeAbbrev>();
3990   Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS));
3991   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
3992   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
3993   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
3994   // numrefs x valueid, n x (valueid , offset)
3995   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3996   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3997   unsigned FSModVTableRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3998 
3999   // Abbrev for FS_ALIAS.
4000   Abbv = std::make_shared<BitCodeAbbrev>();
4001   Abbv->Add(BitCodeAbbrevOp(bitc::FS_ALIAS));
4002   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // valueid
4003   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // flags
4004   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // valueid
4005   unsigned FSAliasAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4006 
4007   // Abbrev for FS_TYPE_ID_METADATA
4008   Abbv = std::make_shared<BitCodeAbbrev>();
4009   Abbv->Add(BitCodeAbbrevOp(bitc::FS_TYPE_ID_METADATA));
4010   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // typeid strtab index
4011   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // typeid length
4012   // n x (valueid , offset)
4013   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4014   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4015   unsigned TypeIdCompatibleVtableAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4016 
4017   SmallVector<uint64_t, 64> NameVals;
4018   // Iterate over the list of functions instead of the Index to
4019   // ensure the ordering is stable.
4020   for (const Function &F : M) {
4021     // Summary emission does not support anonymous functions, they have to
4022     // renamed using the anonymous function renaming pass.
4023     if (!F.hasName())
4024       report_fatal_error("Unexpected anonymous function when writing summary");
4025 
4026     ValueInfo VI = Index->getValueInfo(F.getGUID());
4027     if (!VI || VI.getSummaryList().empty()) {
4028       // Only declarations should not have a summary (a declaration might
4029       // however have a summary if the def was in module level asm).
4030       assert(F.isDeclaration());
4031       continue;
4032     }
4033     auto *Summary = VI.getSummaryList()[0].get();
4034     writePerModuleFunctionSummaryRecord(NameVals, Summary, VE.getValueID(&F),
4035                                         FSCallsAbbrev, FSCallsProfileAbbrev, F);
4036   }
4037 
4038   // Capture references from GlobalVariable initializers, which are outside
4039   // of a function scope.
4040   for (const GlobalVariable &G : M.globals())
4041     writeModuleLevelReferences(G, NameVals, FSModRefsAbbrev,
4042                                FSModVTableRefsAbbrev);
4043 
4044   for (const GlobalAlias &A : M.aliases()) {
4045     auto *Aliasee = A.getAliaseeObject();
4046     if (!Aliasee->hasName())
4047       // Nameless function don't have an entry in the summary, skip it.
4048       continue;
4049     auto AliasId = VE.getValueID(&A);
4050     auto AliaseeId = VE.getValueID(Aliasee);
4051     NameVals.push_back(AliasId);
4052     auto *Summary = Index->getGlobalValueSummary(A);
4053     AliasSummary *AS = cast<AliasSummary>(Summary);
4054     NameVals.push_back(getEncodedGVSummaryFlags(AS->flags()));
4055     NameVals.push_back(AliaseeId);
4056     Stream.EmitRecord(bitc::FS_ALIAS, NameVals, FSAliasAbbrev);
4057     NameVals.clear();
4058   }
4059 
4060   for (auto &S : Index->typeIdCompatibleVtableMap()) {
4061     writeTypeIdCompatibleVtableSummaryRecord(NameVals, StrtabBuilder, S.first,
4062                                              S.second, VE);
4063     Stream.EmitRecord(bitc::FS_TYPE_ID_METADATA, NameVals,
4064                       TypeIdCompatibleVtableAbbrev);
4065     NameVals.clear();
4066   }
4067 
4068   Stream.EmitRecord(bitc::FS_BLOCK_COUNT,
4069                     ArrayRef<uint64_t>{Index->getBlockCount()});
4070 
4071   Stream.ExitBlock();
4072 }
4073 
4074 /// Emit the combined summary section into the combined index file.
4075 void IndexBitcodeWriter::writeCombinedGlobalValueSummary() {
4076   Stream.EnterSubblock(bitc::GLOBALVAL_SUMMARY_BLOCK_ID, 3);
4077   Stream.EmitRecord(
4078       bitc::FS_VERSION,
4079       ArrayRef<uint64_t>{ModuleSummaryIndex::BitcodeSummaryVersion});
4080 
4081   // Write the index flags.
4082   Stream.EmitRecord(bitc::FS_FLAGS, ArrayRef<uint64_t>{Index.getFlags()});
4083 
4084   for (const auto &GVI : valueIds()) {
4085     Stream.EmitRecord(bitc::FS_VALUE_GUID,
4086                       ArrayRef<uint64_t>{GVI.second, GVI.first});
4087   }
4088 
4089   // Abbrev for FS_COMBINED.
4090   auto Abbv = std::make_shared<BitCodeAbbrev>();
4091   Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED));
4092   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // valueid
4093   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // modid
4094   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // flags
4095   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // instcount
4096   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // fflags
4097   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // entrycount
4098   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // numrefs
4099   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // rorefcnt
4100   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // worefcnt
4101   // numrefs x valueid, n x (valueid)
4102   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4103   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4104   unsigned FSCallsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4105 
4106   // Abbrev for FS_COMBINED_PROFILE.
4107   Abbv = std::make_shared<BitCodeAbbrev>();
4108   Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_PROFILE));
4109   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // valueid
4110   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // modid
4111   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // flags
4112   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // instcount
4113   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // fflags
4114   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // entrycount
4115   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // numrefs
4116   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // rorefcnt
4117   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // worefcnt
4118   // numrefs x valueid, n x (valueid, hotness)
4119   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4120   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4121   unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4122 
4123   // Abbrev for FS_COMBINED_GLOBALVAR_INIT_REFS.
4124   Abbv = std::make_shared<BitCodeAbbrev>();
4125   Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_GLOBALVAR_INIT_REFS));
4126   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // valueid
4127   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // modid
4128   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // flags
4129   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));    // valueids
4130   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4131   unsigned FSModRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4132 
4133   // Abbrev for FS_COMBINED_ALIAS.
4134   Abbv = std::make_shared<BitCodeAbbrev>();
4135   Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_ALIAS));
4136   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // valueid
4137   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // modid
4138   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // flags
4139   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // valueid
4140   unsigned FSAliasAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4141 
4142   // The aliases are emitted as a post-pass, and will point to the value
4143   // id of the aliasee. Save them in a vector for post-processing.
4144   SmallVector<AliasSummary *, 64> Aliases;
4145 
4146   // Save the value id for each summary for alias emission.
4147   DenseMap<const GlobalValueSummary *, unsigned> SummaryToValueIdMap;
4148 
4149   SmallVector<uint64_t, 64> NameVals;
4150 
4151   // Set that will be populated during call to writeFunctionTypeMetadataRecords
4152   // with the type ids referenced by this index file.
4153   std::set<GlobalValue::GUID> ReferencedTypeIds;
4154 
4155   // For local linkage, we also emit the original name separately
4156   // immediately after the record.
4157   auto MaybeEmitOriginalName = [&](GlobalValueSummary &S) {
4158     // We don't need to emit the original name if we are writing the index for
4159     // distributed backends (in which case ModuleToSummariesForIndex is
4160     // non-null). The original name is only needed during the thin link, since
4161     // for SamplePGO the indirect call targets for local functions have
4162     // have the original name annotated in profile.
4163     // Continue to emit it when writing out the entire combined index, which is
4164     // used in testing the thin link via llvm-lto.
4165     if (ModuleToSummariesForIndex || !GlobalValue::isLocalLinkage(S.linkage()))
4166       return;
4167     NameVals.push_back(S.getOriginalName());
4168     Stream.EmitRecord(bitc::FS_COMBINED_ORIGINAL_NAME, NameVals);
4169     NameVals.clear();
4170   };
4171 
4172   std::set<GlobalValue::GUID> DefOrUseGUIDs;
4173   forEachSummary([&](GVInfo I, bool IsAliasee) {
4174     GlobalValueSummary *S = I.second;
4175     assert(S);
4176     DefOrUseGUIDs.insert(I.first);
4177     for (const ValueInfo &VI : S->refs())
4178       DefOrUseGUIDs.insert(VI.getGUID());
4179 
4180     auto ValueId = getValueId(I.first);
4181     assert(ValueId);
4182     SummaryToValueIdMap[S] = *ValueId;
4183 
4184     // If this is invoked for an aliasee, we want to record the above
4185     // mapping, but then not emit a summary entry (if the aliasee is
4186     // to be imported, we will invoke this separately with IsAliasee=false).
4187     if (IsAliasee)
4188       return;
4189 
4190     if (auto *AS = dyn_cast<AliasSummary>(S)) {
4191       // Will process aliases as a post-pass because the reader wants all
4192       // global to be loaded first.
4193       Aliases.push_back(AS);
4194       return;
4195     }
4196 
4197     if (auto *VS = dyn_cast<GlobalVarSummary>(S)) {
4198       NameVals.push_back(*ValueId);
4199       NameVals.push_back(Index.getModuleId(VS->modulePath()));
4200       NameVals.push_back(getEncodedGVSummaryFlags(VS->flags()));
4201       NameVals.push_back(getEncodedGVarFlags(VS->varflags()));
4202       for (auto &RI : VS->refs()) {
4203         auto RefValueId = getValueId(RI.getGUID());
4204         if (!RefValueId)
4205           continue;
4206         NameVals.push_back(*RefValueId);
4207       }
4208 
4209       // Emit the finished record.
4210       Stream.EmitRecord(bitc::FS_COMBINED_GLOBALVAR_INIT_REFS, NameVals,
4211                         FSModRefsAbbrev);
4212       NameVals.clear();
4213       MaybeEmitOriginalName(*S);
4214       return;
4215     }
4216 
4217     auto GetValueId = [&](const ValueInfo &VI) -> Optional<unsigned> {
4218       return getValueId(VI.getGUID());
4219     };
4220 
4221     auto *FS = cast<FunctionSummary>(S);
4222     writeFunctionTypeMetadataRecords(Stream, FS, GetValueId);
4223     getReferencedTypeIds(FS, ReferencedTypeIds);
4224 
4225     NameVals.push_back(*ValueId);
4226     NameVals.push_back(Index.getModuleId(FS->modulePath()));
4227     NameVals.push_back(getEncodedGVSummaryFlags(FS->flags()));
4228     NameVals.push_back(FS->instCount());
4229     NameVals.push_back(getEncodedFFlags(FS->fflags()));
4230     NameVals.push_back(FS->entryCount());
4231 
4232     // Fill in below
4233     NameVals.push_back(0); // numrefs
4234     NameVals.push_back(0); // rorefcnt
4235     NameVals.push_back(0); // worefcnt
4236 
4237     unsigned Count = 0, RORefCnt = 0, WORefCnt = 0;
4238     for (auto &RI : FS->refs()) {
4239       auto RefValueId = getValueId(RI.getGUID());
4240       if (!RefValueId)
4241         continue;
4242       NameVals.push_back(*RefValueId);
4243       if (RI.isReadOnly())
4244         RORefCnt++;
4245       else if (RI.isWriteOnly())
4246         WORefCnt++;
4247       Count++;
4248     }
4249     NameVals[6] = Count;
4250     NameVals[7] = RORefCnt;
4251     NameVals[8] = WORefCnt;
4252 
4253     bool HasProfileData = false;
4254     for (auto &EI : FS->calls()) {
4255       HasProfileData |=
4256           EI.second.getHotness() != CalleeInfo::HotnessType::Unknown;
4257       if (HasProfileData)
4258         break;
4259     }
4260 
4261     for (auto &EI : FS->calls()) {
4262       // If this GUID doesn't have a value id, it doesn't have a function
4263       // summary and we don't need to record any calls to it.
4264       Optional<unsigned> CallValueId = GetValueId(EI.first);
4265       if (!CallValueId)
4266         continue;
4267       NameVals.push_back(*CallValueId);
4268       if (HasProfileData)
4269         NameVals.push_back(static_cast<uint8_t>(EI.second.Hotness));
4270     }
4271 
4272     unsigned FSAbbrev = (HasProfileData ? FSCallsProfileAbbrev : FSCallsAbbrev);
4273     unsigned Code =
4274         (HasProfileData ? bitc::FS_COMBINED_PROFILE : bitc::FS_COMBINED);
4275 
4276     // Emit the finished record.
4277     Stream.EmitRecord(Code, NameVals, FSAbbrev);
4278     NameVals.clear();
4279     MaybeEmitOriginalName(*S);
4280   });
4281 
4282   for (auto *AS : Aliases) {
4283     auto AliasValueId = SummaryToValueIdMap[AS];
4284     assert(AliasValueId);
4285     NameVals.push_back(AliasValueId);
4286     NameVals.push_back(Index.getModuleId(AS->modulePath()));
4287     NameVals.push_back(getEncodedGVSummaryFlags(AS->flags()));
4288     auto AliaseeValueId = SummaryToValueIdMap[&AS->getAliasee()];
4289     assert(AliaseeValueId);
4290     NameVals.push_back(AliaseeValueId);
4291 
4292     // Emit the finished record.
4293     Stream.EmitRecord(bitc::FS_COMBINED_ALIAS, NameVals, FSAliasAbbrev);
4294     NameVals.clear();
4295     MaybeEmitOriginalName(*AS);
4296 
4297     if (auto *FS = dyn_cast<FunctionSummary>(&AS->getAliasee()))
4298       getReferencedTypeIds(FS, ReferencedTypeIds);
4299   }
4300 
4301   if (!Index.cfiFunctionDefs().empty()) {
4302     for (auto &S : Index.cfiFunctionDefs()) {
4303       if (DefOrUseGUIDs.count(
4304               GlobalValue::getGUID(GlobalValue::dropLLVMManglingEscape(S)))) {
4305         NameVals.push_back(StrtabBuilder.add(S));
4306         NameVals.push_back(S.size());
4307       }
4308     }
4309     if (!NameVals.empty()) {
4310       Stream.EmitRecord(bitc::FS_CFI_FUNCTION_DEFS, NameVals);
4311       NameVals.clear();
4312     }
4313   }
4314 
4315   if (!Index.cfiFunctionDecls().empty()) {
4316     for (auto &S : Index.cfiFunctionDecls()) {
4317       if (DefOrUseGUIDs.count(
4318               GlobalValue::getGUID(GlobalValue::dropLLVMManglingEscape(S)))) {
4319         NameVals.push_back(StrtabBuilder.add(S));
4320         NameVals.push_back(S.size());
4321       }
4322     }
4323     if (!NameVals.empty()) {
4324       Stream.EmitRecord(bitc::FS_CFI_FUNCTION_DECLS, NameVals);
4325       NameVals.clear();
4326     }
4327   }
4328 
4329   // Walk the GUIDs that were referenced, and write the
4330   // corresponding type id records.
4331   for (auto &T : ReferencedTypeIds) {
4332     auto TidIter = Index.typeIds().equal_range(T);
4333     for (auto It = TidIter.first; It != TidIter.second; ++It) {
4334       writeTypeIdSummaryRecord(NameVals, StrtabBuilder, It->second.first,
4335                                It->second.second);
4336       Stream.EmitRecord(bitc::FS_TYPE_ID, NameVals);
4337       NameVals.clear();
4338     }
4339   }
4340 
4341   Stream.EmitRecord(bitc::FS_BLOCK_COUNT,
4342                     ArrayRef<uint64_t>{Index.getBlockCount()});
4343 
4344   Stream.ExitBlock();
4345 }
4346 
4347 /// Create the "IDENTIFICATION_BLOCK_ID" containing a single string with the
4348 /// current llvm version, and a record for the epoch number.
4349 static void writeIdentificationBlock(BitstreamWriter &Stream) {
4350   Stream.EnterSubblock(bitc::IDENTIFICATION_BLOCK_ID, 5);
4351 
4352   // Write the "user readable" string identifying the bitcode producer
4353   auto Abbv = std::make_shared<BitCodeAbbrev>();
4354   Abbv->Add(BitCodeAbbrevOp(bitc::IDENTIFICATION_CODE_STRING));
4355   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4356   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
4357   auto StringAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4358   writeStringRecord(Stream, bitc::IDENTIFICATION_CODE_STRING,
4359                     "LLVM" LLVM_VERSION_STRING, StringAbbrev);
4360 
4361   // Write the epoch version
4362   Abbv = std::make_shared<BitCodeAbbrev>();
4363   Abbv->Add(BitCodeAbbrevOp(bitc::IDENTIFICATION_CODE_EPOCH));
4364   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
4365   auto EpochAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4366   constexpr std::array<unsigned, 1> Vals = {{bitc::BITCODE_CURRENT_EPOCH}};
4367   Stream.EmitRecord(bitc::IDENTIFICATION_CODE_EPOCH, Vals, EpochAbbrev);
4368   Stream.ExitBlock();
4369 }
4370 
4371 void ModuleBitcodeWriter::writeModuleHash(size_t BlockStartPos) {
4372   // Emit the module's hash.
4373   // MODULE_CODE_HASH: [5*i32]
4374   if (GenerateHash) {
4375     uint32_t Vals[5];
4376     Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&(Buffer)[BlockStartPos],
4377                                     Buffer.size() - BlockStartPos));
4378     StringRef Hash = Hasher.result();
4379     for (int Pos = 0; Pos < 20; Pos += 4) {
4380       Vals[Pos / 4] = support::endian::read32be(Hash.data() + Pos);
4381     }
4382 
4383     // Emit the finished record.
4384     Stream.EmitRecord(bitc::MODULE_CODE_HASH, Vals);
4385 
4386     if (ModHash)
4387       // Save the written hash value.
4388       llvm::copy(Vals, std::begin(*ModHash));
4389   }
4390 }
4391 
4392 void ModuleBitcodeWriter::write() {
4393   writeIdentificationBlock(Stream);
4394 
4395   Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
4396   size_t BlockStartPos = Buffer.size();
4397 
4398   writeModuleVersion();
4399 
4400   // Emit blockinfo, which defines the standard abbreviations etc.
4401   writeBlockInfo();
4402 
4403   // Emit information describing all of the types in the module.
4404   writeTypeTable();
4405 
4406   // Emit information about attribute groups.
4407   writeAttributeGroupTable();
4408 
4409   // Emit information about parameter attributes.
4410   writeAttributeTable();
4411 
4412   writeComdats();
4413 
4414   // Emit top-level description of module, including target triple, inline asm,
4415   // descriptors for global variables, and function prototype info.
4416   writeModuleInfo();
4417 
4418   // Emit constants.
4419   writeModuleConstants();
4420 
4421   // Emit metadata kind names.
4422   writeModuleMetadataKinds();
4423 
4424   // Emit metadata.
4425   writeModuleMetadata();
4426 
4427   // Emit module-level use-lists.
4428   if (VE.shouldPreserveUseListOrder())
4429     writeUseListBlock(nullptr);
4430 
4431   writeOperandBundleTags();
4432   writeSyncScopeNames();
4433 
4434   // Emit function bodies.
4435   DenseMap<const Function *, uint64_t> FunctionToBitcodeIndex;
4436   for (const Function &F : M)
4437     if (!F.isDeclaration())
4438       writeFunction(F, FunctionToBitcodeIndex);
4439 
4440   // Need to write after the above call to WriteFunction which populates
4441   // the summary information in the index.
4442   if (Index)
4443     writePerModuleGlobalValueSummary();
4444 
4445   writeGlobalValueSymbolTable(FunctionToBitcodeIndex);
4446 
4447   writeModuleHash(BlockStartPos);
4448 
4449   Stream.ExitBlock();
4450 }
4451 
4452 static void writeInt32ToBuffer(uint32_t Value, SmallVectorImpl<char> &Buffer,
4453                                uint32_t &Position) {
4454   support::endian::write32le(&Buffer[Position], Value);
4455   Position += 4;
4456 }
4457 
4458 /// If generating a bc file on darwin, we have to emit a
4459 /// header and trailer to make it compatible with the system archiver.  To do
4460 /// this we emit the following header, and then emit a trailer that pads the
4461 /// file out to be a multiple of 16 bytes.
4462 ///
4463 /// struct bc_header {
4464 ///   uint32_t Magic;         // 0x0B17C0DE
4465 ///   uint32_t Version;       // Version, currently always 0.
4466 ///   uint32_t BitcodeOffset; // Offset to traditional bitcode file.
4467 ///   uint32_t BitcodeSize;   // Size of traditional bitcode file.
4468 ///   uint32_t CPUType;       // CPU specifier.
4469 ///   ... potentially more later ...
4470 /// };
4471 static void emitDarwinBCHeaderAndTrailer(SmallVectorImpl<char> &Buffer,
4472                                          const Triple &TT) {
4473   unsigned CPUType = ~0U;
4474 
4475   // Match x86_64-*, i[3-9]86-*, powerpc-*, powerpc64-*, arm-*, thumb-*,
4476   // armv[0-9]-*, thumbv[0-9]-*, armv5te-*, or armv6t2-*. The CPUType is a magic
4477   // number from /usr/include/mach/machine.h.  It is ok to reproduce the
4478   // specific constants here because they are implicitly part of the Darwin ABI.
4479   enum {
4480     DARWIN_CPU_ARCH_ABI64      = 0x01000000,
4481     DARWIN_CPU_TYPE_X86        = 7,
4482     DARWIN_CPU_TYPE_ARM        = 12,
4483     DARWIN_CPU_TYPE_POWERPC    = 18
4484   };
4485 
4486   Triple::ArchType Arch = TT.getArch();
4487   if (Arch == Triple::x86_64)
4488     CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64;
4489   else if (Arch == Triple::x86)
4490     CPUType = DARWIN_CPU_TYPE_X86;
4491   else if (Arch == Triple::ppc)
4492     CPUType = DARWIN_CPU_TYPE_POWERPC;
4493   else if (Arch == Triple::ppc64)
4494     CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64;
4495   else if (Arch == Triple::arm || Arch == Triple::thumb)
4496     CPUType = DARWIN_CPU_TYPE_ARM;
4497 
4498   // Traditional Bitcode starts after header.
4499   assert(Buffer.size() >= BWH_HeaderSize &&
4500          "Expected header size to be reserved");
4501   unsigned BCOffset = BWH_HeaderSize;
4502   unsigned BCSize = Buffer.size() - BWH_HeaderSize;
4503 
4504   // Write the magic and version.
4505   unsigned Position = 0;
4506   writeInt32ToBuffer(0x0B17C0DE, Buffer, Position);
4507   writeInt32ToBuffer(0, Buffer, Position); // Version.
4508   writeInt32ToBuffer(BCOffset, Buffer, Position);
4509   writeInt32ToBuffer(BCSize, Buffer, Position);
4510   writeInt32ToBuffer(CPUType, Buffer, Position);
4511 
4512   // If the file is not a multiple of 16 bytes, insert dummy padding.
4513   while (Buffer.size() & 15)
4514     Buffer.push_back(0);
4515 }
4516 
4517 /// Helper to write the header common to all bitcode files.
4518 static void writeBitcodeHeader(BitstreamWriter &Stream) {
4519   // Emit the file header.
4520   Stream.Emit((unsigned)'B', 8);
4521   Stream.Emit((unsigned)'C', 8);
4522   Stream.Emit(0x0, 4);
4523   Stream.Emit(0xC, 4);
4524   Stream.Emit(0xE, 4);
4525   Stream.Emit(0xD, 4);
4526 }
4527 
4528 BitcodeWriter::BitcodeWriter(SmallVectorImpl<char> &Buffer, raw_fd_stream *FS)
4529     : Buffer(Buffer), Stream(new BitstreamWriter(Buffer, FS, FlushThreshold)) {
4530   writeBitcodeHeader(*Stream);
4531 }
4532 
4533 BitcodeWriter::~BitcodeWriter() { assert(WroteStrtab); }
4534 
4535 void BitcodeWriter::writeBlob(unsigned Block, unsigned Record, StringRef Blob) {
4536   Stream->EnterSubblock(Block, 3);
4537 
4538   auto Abbv = std::make_shared<BitCodeAbbrev>();
4539   Abbv->Add(BitCodeAbbrevOp(Record));
4540   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
4541   auto AbbrevNo = Stream->EmitAbbrev(std::move(Abbv));
4542 
4543   Stream->EmitRecordWithBlob(AbbrevNo, ArrayRef<uint64_t>{Record}, Blob);
4544 
4545   Stream->ExitBlock();
4546 }
4547 
4548 void BitcodeWriter::writeSymtab() {
4549   assert(!WroteStrtab && !WroteSymtab);
4550 
4551   // If any module has module-level inline asm, we will require a registered asm
4552   // parser for the target so that we can create an accurate symbol table for
4553   // the module.
4554   for (Module *M : Mods) {
4555     if (M->getModuleInlineAsm().empty())
4556       continue;
4557 
4558     std::string Err;
4559     const Triple TT(M->getTargetTriple());
4560     const Target *T = TargetRegistry::lookupTarget(TT.str(), Err);
4561     if (!T || !T->hasMCAsmParser())
4562       return;
4563   }
4564 
4565   WroteSymtab = true;
4566   SmallVector<char, 0> Symtab;
4567   // The irsymtab::build function may be unable to create a symbol table if the
4568   // module is malformed (e.g. it contains an invalid alias). Writing a symbol
4569   // table is not required for correctness, but we still want to be able to
4570   // write malformed modules to bitcode files, so swallow the error.
4571   if (Error E = irsymtab::build(Mods, Symtab, StrtabBuilder, Alloc)) {
4572     consumeError(std::move(E));
4573     return;
4574   }
4575 
4576   writeBlob(bitc::SYMTAB_BLOCK_ID, bitc::SYMTAB_BLOB,
4577             {Symtab.data(), Symtab.size()});
4578 }
4579 
4580 void BitcodeWriter::writeStrtab() {
4581   assert(!WroteStrtab);
4582 
4583   std::vector<char> Strtab;
4584   StrtabBuilder.finalizeInOrder();
4585   Strtab.resize(StrtabBuilder.getSize());
4586   StrtabBuilder.write((uint8_t *)Strtab.data());
4587 
4588   writeBlob(bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB,
4589             {Strtab.data(), Strtab.size()});
4590 
4591   WroteStrtab = true;
4592 }
4593 
4594 void BitcodeWriter::copyStrtab(StringRef Strtab) {
4595   writeBlob(bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB, Strtab);
4596   WroteStrtab = true;
4597 }
4598 
4599 void BitcodeWriter::writeModule(const Module &M,
4600                                 bool ShouldPreserveUseListOrder,
4601                                 const ModuleSummaryIndex *Index,
4602                                 bool GenerateHash, ModuleHash *ModHash) {
4603   assert(!WroteStrtab);
4604 
4605   // The Mods vector is used by irsymtab::build, which requires non-const
4606   // Modules in case it needs to materialize metadata. But the bitcode writer
4607   // requires that the module is materialized, so we can cast to non-const here,
4608   // after checking that it is in fact materialized.
4609   assert(M.isMaterialized());
4610   Mods.push_back(const_cast<Module *>(&M));
4611 
4612   ModuleBitcodeWriter ModuleWriter(M, Buffer, StrtabBuilder, *Stream,
4613                                    ShouldPreserveUseListOrder, Index,
4614                                    GenerateHash, ModHash);
4615   ModuleWriter.write();
4616 }
4617 
4618 void BitcodeWriter::writeIndex(
4619     const ModuleSummaryIndex *Index,
4620     const std::map<std::string, GVSummaryMapTy> *ModuleToSummariesForIndex) {
4621   IndexBitcodeWriter IndexWriter(*Stream, StrtabBuilder, *Index,
4622                                  ModuleToSummariesForIndex);
4623   IndexWriter.write();
4624 }
4625 
4626 /// Write the specified module to the specified output stream.
4627 void llvm::WriteBitcodeToFile(const Module &M, raw_ostream &Out,
4628                               bool ShouldPreserveUseListOrder,
4629                               const ModuleSummaryIndex *Index,
4630                               bool GenerateHash, ModuleHash *ModHash) {
4631   SmallVector<char, 0> Buffer;
4632   Buffer.reserve(256*1024);
4633 
4634   // If this is darwin or another generic macho target, reserve space for the
4635   // header.
4636   Triple TT(M.getTargetTriple());
4637   if (TT.isOSDarwin() || TT.isOSBinFormatMachO())
4638     Buffer.insert(Buffer.begin(), BWH_HeaderSize, 0);
4639 
4640   BitcodeWriter Writer(Buffer, dyn_cast<raw_fd_stream>(&Out));
4641   Writer.writeModule(M, ShouldPreserveUseListOrder, Index, GenerateHash,
4642                      ModHash);
4643   Writer.writeSymtab();
4644   Writer.writeStrtab();
4645 
4646   if (TT.isOSDarwin() || TT.isOSBinFormatMachO())
4647     emitDarwinBCHeaderAndTrailer(Buffer, TT);
4648 
4649   // Write the generated bitstream to "Out".
4650   if (!Buffer.empty())
4651     Out.write((char *)&Buffer.front(), Buffer.size());
4652 }
4653 
4654 void IndexBitcodeWriter::write() {
4655   Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
4656 
4657   writeModuleVersion();
4658 
4659   // Write the module paths in the combined index.
4660   writeModStrings();
4661 
4662   // Write the summary combined index records.
4663   writeCombinedGlobalValueSummary();
4664 
4665   Stream.ExitBlock();
4666 }
4667 
4668 // Write the specified module summary index to the given raw output stream,
4669 // where it will be written in a new bitcode block. This is used when
4670 // writing the combined index file for ThinLTO. When writing a subset of the
4671 // index for a distributed backend, provide a \p ModuleToSummariesForIndex map.
4672 void llvm::writeIndexToFile(
4673     const ModuleSummaryIndex &Index, raw_ostream &Out,
4674     const std::map<std::string, GVSummaryMapTy> *ModuleToSummariesForIndex) {
4675   SmallVector<char, 0> Buffer;
4676   Buffer.reserve(256 * 1024);
4677 
4678   BitcodeWriter Writer(Buffer);
4679   Writer.writeIndex(&Index, ModuleToSummariesForIndex);
4680   Writer.writeStrtab();
4681 
4682   Out.write((char *)&Buffer.front(), Buffer.size());
4683 }
4684 
4685 namespace {
4686 
4687 /// Class to manage the bitcode writing for a thin link bitcode file.
4688 class ThinLinkBitcodeWriter : public ModuleBitcodeWriterBase {
4689   /// ModHash is for use in ThinLTO incremental build, generated while writing
4690   /// the module bitcode file.
4691   const ModuleHash *ModHash;
4692 
4693 public:
4694   ThinLinkBitcodeWriter(const Module &M, StringTableBuilder &StrtabBuilder,
4695                         BitstreamWriter &Stream,
4696                         const ModuleSummaryIndex &Index,
4697                         const ModuleHash &ModHash)
4698       : ModuleBitcodeWriterBase(M, StrtabBuilder, Stream,
4699                                 /*ShouldPreserveUseListOrder=*/false, &Index),
4700         ModHash(&ModHash) {}
4701 
4702   void write();
4703 
4704 private:
4705   void writeSimplifiedModuleInfo();
4706 };
4707 
4708 } // end anonymous namespace
4709 
4710 // This function writes a simpilified module info for thin link bitcode file.
4711 // It only contains the source file name along with the name(the offset and
4712 // size in strtab) and linkage for global values. For the global value info
4713 // entry, in order to keep linkage at offset 5, there are three zeros used
4714 // as padding.
4715 void ThinLinkBitcodeWriter::writeSimplifiedModuleInfo() {
4716   SmallVector<unsigned, 64> Vals;
4717   // Emit the module's source file name.
4718   {
4719     StringEncoding Bits = getStringEncoding(M.getSourceFileName());
4720     BitCodeAbbrevOp AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8);
4721     if (Bits == SE_Char6)
4722       AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Char6);
4723     else if (Bits == SE_Fixed7)
4724       AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7);
4725 
4726     // MODULE_CODE_SOURCE_FILENAME: [namechar x N]
4727     auto Abbv = std::make_shared<BitCodeAbbrev>();
4728     Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_SOURCE_FILENAME));
4729     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4730     Abbv->Add(AbbrevOpToUse);
4731     unsigned FilenameAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4732 
4733     for (const auto P : M.getSourceFileName())
4734       Vals.push_back((unsigned char)P);
4735 
4736     Stream.EmitRecord(bitc::MODULE_CODE_SOURCE_FILENAME, Vals, FilenameAbbrev);
4737     Vals.clear();
4738   }
4739 
4740   // Emit the global variable information.
4741   for (const GlobalVariable &GV : M.globals()) {
4742     // GLOBALVAR: [strtab offset, strtab size, 0, 0, 0, linkage]
4743     Vals.push_back(StrtabBuilder.add(GV.getName()));
4744     Vals.push_back(GV.getName().size());
4745     Vals.push_back(0);
4746     Vals.push_back(0);
4747     Vals.push_back(0);
4748     Vals.push_back(getEncodedLinkage(GV));
4749 
4750     Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals);
4751     Vals.clear();
4752   }
4753 
4754   // Emit the function proto information.
4755   for (const Function &F : M) {
4756     // FUNCTION:  [strtab offset, strtab size, 0, 0, 0, linkage]
4757     Vals.push_back(StrtabBuilder.add(F.getName()));
4758     Vals.push_back(F.getName().size());
4759     Vals.push_back(0);
4760     Vals.push_back(0);
4761     Vals.push_back(0);
4762     Vals.push_back(getEncodedLinkage(F));
4763 
4764     Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals);
4765     Vals.clear();
4766   }
4767 
4768   // Emit the alias information.
4769   for (const GlobalAlias &A : M.aliases()) {
4770     // ALIAS: [strtab offset, strtab size, 0, 0, 0, linkage]
4771     Vals.push_back(StrtabBuilder.add(A.getName()));
4772     Vals.push_back(A.getName().size());
4773     Vals.push_back(0);
4774     Vals.push_back(0);
4775     Vals.push_back(0);
4776     Vals.push_back(getEncodedLinkage(A));
4777 
4778     Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals);
4779     Vals.clear();
4780   }
4781 
4782   // Emit the ifunc information.
4783   for (const GlobalIFunc &I : M.ifuncs()) {
4784     // IFUNC: [strtab offset, strtab size, 0, 0, 0, linkage]
4785     Vals.push_back(StrtabBuilder.add(I.getName()));
4786     Vals.push_back(I.getName().size());
4787     Vals.push_back(0);
4788     Vals.push_back(0);
4789     Vals.push_back(0);
4790     Vals.push_back(getEncodedLinkage(I));
4791 
4792     Stream.EmitRecord(bitc::MODULE_CODE_IFUNC, Vals);
4793     Vals.clear();
4794   }
4795 }
4796 
4797 void ThinLinkBitcodeWriter::write() {
4798   Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
4799 
4800   writeModuleVersion();
4801 
4802   writeSimplifiedModuleInfo();
4803 
4804   writePerModuleGlobalValueSummary();
4805 
4806   // Write module hash.
4807   Stream.EmitRecord(bitc::MODULE_CODE_HASH, ArrayRef<uint32_t>(*ModHash));
4808 
4809   Stream.ExitBlock();
4810 }
4811 
4812 void BitcodeWriter::writeThinLinkBitcode(const Module &M,
4813                                          const ModuleSummaryIndex &Index,
4814                                          const ModuleHash &ModHash) {
4815   assert(!WroteStrtab);
4816 
4817   // The Mods vector is used by irsymtab::build, which requires non-const
4818   // Modules in case it needs to materialize metadata. But the bitcode writer
4819   // requires that the module is materialized, so we can cast to non-const here,
4820   // after checking that it is in fact materialized.
4821   assert(M.isMaterialized());
4822   Mods.push_back(const_cast<Module *>(&M));
4823 
4824   ThinLinkBitcodeWriter ThinLinkWriter(M, StrtabBuilder, *Stream, Index,
4825                                        ModHash);
4826   ThinLinkWriter.write();
4827 }
4828 
4829 // Write the specified thin link bitcode file to the given raw output stream,
4830 // where it will be written in a new bitcode block. This is used when
4831 // writing the per-module index file for ThinLTO.
4832 void llvm::writeThinLinkBitcodeToFile(const Module &M, raw_ostream &Out,
4833                                       const ModuleSummaryIndex &Index,
4834                                       const ModuleHash &ModHash) {
4835   SmallVector<char, 0> Buffer;
4836   Buffer.reserve(256 * 1024);
4837 
4838   BitcodeWriter Writer(Buffer);
4839   Writer.writeThinLinkBitcode(M, Index, ModHash);
4840   Writer.writeSymtab();
4841   Writer.writeStrtab();
4842 
4843   Out.write((char *)&Buffer.front(), Buffer.size());
4844 }
4845 
4846 static const char *getSectionNameForBitcode(const Triple &T) {
4847   switch (T.getObjectFormat()) {
4848   case Triple::MachO:
4849     return "__LLVM,__bitcode";
4850   case Triple::COFF:
4851   case Triple::ELF:
4852   case Triple::Wasm:
4853   case Triple::UnknownObjectFormat:
4854     return ".llvmbc";
4855   case Triple::GOFF:
4856     llvm_unreachable("GOFF is not yet implemented");
4857     break;
4858   case Triple::XCOFF:
4859     llvm_unreachable("XCOFF is not yet implemented");
4860     break;
4861   }
4862   llvm_unreachable("Unimplemented ObjectFormatType");
4863 }
4864 
4865 static const char *getSectionNameForCommandline(const Triple &T) {
4866   switch (T.getObjectFormat()) {
4867   case Triple::MachO:
4868     return "__LLVM,__cmdline";
4869   case Triple::COFF:
4870   case Triple::ELF:
4871   case Triple::Wasm:
4872   case Triple::UnknownObjectFormat:
4873     return ".llvmcmd";
4874   case Triple::GOFF:
4875     llvm_unreachable("GOFF is not yet implemented");
4876     break;
4877   case Triple::XCOFF:
4878     llvm_unreachable("XCOFF is not yet implemented");
4879     break;
4880   }
4881   llvm_unreachable("Unimplemented ObjectFormatType");
4882 }
4883 
4884 void llvm::embedBitcodeInModule(llvm::Module &M, llvm::MemoryBufferRef Buf,
4885                                 bool EmbedBitcode, bool EmbedCmdline,
4886                                 const std::vector<uint8_t> &CmdArgs) {
4887   // Save llvm.compiler.used and remove it.
4888   SmallVector<Constant *, 2> UsedArray;
4889   SmallVector<GlobalValue *, 4> UsedGlobals;
4890   Type *UsedElementType = Type::getInt8Ty(M.getContext())->getPointerTo(0);
4891   GlobalVariable *Used = collectUsedGlobalVariables(M, UsedGlobals, true);
4892   for (auto *GV : UsedGlobals) {
4893     if (GV->getName() != "llvm.embedded.module" &&
4894         GV->getName() != "llvm.cmdline")
4895       UsedArray.push_back(
4896           ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
4897   }
4898   if (Used)
4899     Used->eraseFromParent();
4900 
4901   // Embed the bitcode for the llvm module.
4902   std::string Data;
4903   ArrayRef<uint8_t> ModuleData;
4904   Triple T(M.getTargetTriple());
4905 
4906   if (EmbedBitcode) {
4907     if (Buf.getBufferSize() == 0 ||
4908         !isBitcode((const unsigned char *)Buf.getBufferStart(),
4909                    (const unsigned char *)Buf.getBufferEnd())) {
4910       // If the input is LLVM Assembly, bitcode is produced by serializing
4911       // the module. Use-lists order need to be preserved in this case.
4912       llvm::raw_string_ostream OS(Data);
4913       llvm::WriteBitcodeToFile(M, OS, /* ShouldPreserveUseListOrder */ true);
4914       ModuleData =
4915           ArrayRef<uint8_t>((const uint8_t *)OS.str().data(), OS.str().size());
4916     } else
4917       // If the input is LLVM bitcode, write the input byte stream directly.
4918       ModuleData = ArrayRef<uint8_t>((const uint8_t *)Buf.getBufferStart(),
4919                                      Buf.getBufferSize());
4920   }
4921   llvm::Constant *ModuleConstant =
4922       llvm::ConstantDataArray::get(M.getContext(), ModuleData);
4923   llvm::GlobalVariable *GV = new llvm::GlobalVariable(
4924       M, ModuleConstant->getType(), true, llvm::GlobalValue::PrivateLinkage,
4925       ModuleConstant);
4926   GV->setSection(getSectionNameForBitcode(T));
4927   // Set alignment to 1 to prevent padding between two contributions from input
4928   // sections after linking.
4929   GV->setAlignment(Align(1));
4930   UsedArray.push_back(
4931       ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
4932   if (llvm::GlobalVariable *Old =
4933           M.getGlobalVariable("llvm.embedded.module", true)) {
4934     assert(Old->hasOneUse() &&
4935            "llvm.embedded.module can only be used once in llvm.compiler.used");
4936     GV->takeName(Old);
4937     Old->eraseFromParent();
4938   } else {
4939     GV->setName("llvm.embedded.module");
4940   }
4941 
4942   // Skip if only bitcode needs to be embedded.
4943   if (EmbedCmdline) {
4944     // Embed command-line options.
4945     ArrayRef<uint8_t> CmdData(const_cast<uint8_t *>(CmdArgs.data()),
4946                               CmdArgs.size());
4947     llvm::Constant *CmdConstant =
4948         llvm::ConstantDataArray::get(M.getContext(), CmdData);
4949     GV = new llvm::GlobalVariable(M, CmdConstant->getType(), true,
4950                                   llvm::GlobalValue::PrivateLinkage,
4951                                   CmdConstant);
4952     GV->setSection(getSectionNameForCommandline(T));
4953     GV->setAlignment(Align(1));
4954     UsedArray.push_back(
4955         ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
4956     if (llvm::GlobalVariable *Old = M.getGlobalVariable("llvm.cmdline", true)) {
4957       assert(Old->hasOneUse() &&
4958              "llvm.cmdline can only be used once in llvm.compiler.used");
4959       GV->takeName(Old);
4960       Old->eraseFromParent();
4961     } else {
4962       GV->setName("llvm.cmdline");
4963     }
4964   }
4965 
4966   if (UsedArray.empty())
4967     return;
4968 
4969   // Recreate llvm.compiler.used.
4970   ArrayType *ATy = ArrayType::get(UsedElementType, UsedArray.size());
4971   auto *NewUsed = new GlobalVariable(
4972       M, ATy, false, llvm::GlobalValue::AppendingLinkage,
4973       llvm::ConstantArray::get(ATy, UsedArray), "llvm.compiler.used");
4974   NewUsed->setSection("llvm.metadata");
4975 }
4976