xref: /freebsd-src/contrib/llvm-project/llvm/lib/Bitcode/Writer/BitcodeWriter.cpp (revision 5e801ac66d24704442eba426ed13c3effb8a34e7)
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 (unsigned i = 0, e = Str.size(); i != e; ++i) {
600     if (AbbrevToUse && !BitCodeAbbrevOp::isChar6(Str[i]))
601       AbbrevToUse = 0;
602     Vals.push_back(Str[i]);
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 (unsigned i = 0, e = Attrs.size(); i != e; ++i) {
837     AttributeList AL = Attrs[i];
838     for (unsigned i : AL.indexes()) {
839       AttributeSet AS = AL.getAttributes(i);
840       if (AS.hasAttributes())
841         Record.push_back(VE.getAttributeGroupID({i, AS}));
842     }
843 
844     Stream.EmitRecord(bitc::PARAMATTR_CODE_ENTRY, Record);
845     Record.clear();
846   }
847 
848   Stream.ExitBlock();
849 }
850 
851 /// WriteTypeTable - Write out the type table for a module.
852 void ModuleBitcodeWriter::writeTypeTable() {
853   const ValueEnumerator::TypeList &TypeList = VE.getTypes();
854 
855   Stream.EnterSubblock(bitc::TYPE_BLOCK_ID_NEW, 4 /*count from # abbrevs */);
856   SmallVector<uint64_t, 64> TypeVals;
857 
858   uint64_t NumBits = VE.computeBitsRequiredForTypeIndicies();
859 
860   // Abbrev for TYPE_CODE_POINTER.
861   auto Abbv = std::make_shared<BitCodeAbbrev>();
862   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_POINTER));
863   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
864   Abbv->Add(BitCodeAbbrevOp(0));  // Addrspace = 0
865   unsigned PtrAbbrev = Stream.EmitAbbrev(std::move(Abbv));
866 
867   // Abbrev for TYPE_CODE_OPAQUE_POINTER.
868   Abbv = std::make_shared<BitCodeAbbrev>();
869   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_OPAQUE_POINTER));
870   Abbv->Add(BitCodeAbbrevOp(0)); // Addrspace = 0
871   unsigned OpaquePtrAbbrev = Stream.EmitAbbrev(std::move(Abbv));
872 
873   // Abbrev for TYPE_CODE_FUNCTION.
874   Abbv = std::make_shared<BitCodeAbbrev>();
875   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_FUNCTION));
876   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));  // isvararg
877   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
878   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
879   unsigned FunctionAbbrev = Stream.EmitAbbrev(std::move(Abbv));
880 
881   // Abbrev for TYPE_CODE_STRUCT_ANON.
882   Abbv = std::make_shared<BitCodeAbbrev>();
883   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_ANON));
884   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));  // ispacked
885   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
886   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
887   unsigned StructAnonAbbrev = Stream.EmitAbbrev(std::move(Abbv));
888 
889   // Abbrev for TYPE_CODE_STRUCT_NAME.
890   Abbv = std::make_shared<BitCodeAbbrev>();
891   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAME));
892   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
893   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
894   unsigned StructNameAbbrev = Stream.EmitAbbrev(std::move(Abbv));
895 
896   // Abbrev for TYPE_CODE_STRUCT_NAMED.
897   Abbv = std::make_shared<BitCodeAbbrev>();
898   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAMED));
899   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));  // ispacked
900   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
901   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
902   unsigned StructNamedAbbrev = Stream.EmitAbbrev(std::move(Abbv));
903 
904   // Abbrev for TYPE_CODE_ARRAY.
905   Abbv = std::make_shared<BitCodeAbbrev>();
906   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_ARRAY));
907   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // size
908   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
909   unsigned ArrayAbbrev = Stream.EmitAbbrev(std::move(Abbv));
910 
911   // Emit an entry count so the reader can reserve space.
912   TypeVals.push_back(TypeList.size());
913   Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals);
914   TypeVals.clear();
915 
916   // Loop over all of the types, emitting each in turn.
917   for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
918     Type *T = TypeList[i];
919     int AbbrevToUse = 0;
920     unsigned Code = 0;
921 
922     switch (T->getTypeID()) {
923     case Type::VoidTyID:      Code = bitc::TYPE_CODE_VOID;      break;
924     case Type::HalfTyID:      Code = bitc::TYPE_CODE_HALF;      break;
925     case Type::BFloatTyID:    Code = bitc::TYPE_CODE_BFLOAT;    break;
926     case Type::FloatTyID:     Code = bitc::TYPE_CODE_FLOAT;     break;
927     case Type::DoubleTyID:    Code = bitc::TYPE_CODE_DOUBLE;    break;
928     case Type::X86_FP80TyID:  Code = bitc::TYPE_CODE_X86_FP80;  break;
929     case Type::FP128TyID:     Code = bitc::TYPE_CODE_FP128;     break;
930     case Type::PPC_FP128TyID: Code = bitc::TYPE_CODE_PPC_FP128; break;
931     case Type::LabelTyID:     Code = bitc::TYPE_CODE_LABEL;     break;
932     case Type::MetadataTyID:  Code = bitc::TYPE_CODE_METADATA;  break;
933     case Type::X86_MMXTyID:   Code = bitc::TYPE_CODE_X86_MMX;   break;
934     case Type::X86_AMXTyID:   Code = bitc::TYPE_CODE_X86_AMX;   break;
935     case Type::TokenTyID:     Code = bitc::TYPE_CODE_TOKEN;     break;
936     case Type::IntegerTyID:
937       // INTEGER: [width]
938       Code = bitc::TYPE_CODE_INTEGER;
939       TypeVals.push_back(cast<IntegerType>(T)->getBitWidth());
940       break;
941     case Type::PointerTyID: {
942       PointerType *PTy = cast<PointerType>(T);
943       unsigned AddressSpace = PTy->getAddressSpace();
944       if (PTy->isOpaque()) {
945         // OPAQUE_POINTER: [address space]
946         Code = bitc::TYPE_CODE_OPAQUE_POINTER;
947         TypeVals.push_back(AddressSpace);
948         if (AddressSpace == 0)
949           AbbrevToUse = OpaquePtrAbbrev;
950       } else {
951         // POINTER: [pointee type, address space]
952         Code = bitc::TYPE_CODE_POINTER;
953         TypeVals.push_back(VE.getTypeID(PTy->getElementType()));
954         TypeVals.push_back(AddressSpace);
955         if (AddressSpace == 0)
956           AbbrevToUse = PtrAbbrev;
957       }
958       break;
959     }
960     case Type::FunctionTyID: {
961       FunctionType *FT = cast<FunctionType>(T);
962       // FUNCTION: [isvararg, retty, paramty x N]
963       Code = bitc::TYPE_CODE_FUNCTION;
964       TypeVals.push_back(FT->isVarArg());
965       TypeVals.push_back(VE.getTypeID(FT->getReturnType()));
966       for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
967         TypeVals.push_back(VE.getTypeID(FT->getParamType(i)));
968       AbbrevToUse = FunctionAbbrev;
969       break;
970     }
971     case Type::StructTyID: {
972       StructType *ST = cast<StructType>(T);
973       // STRUCT: [ispacked, eltty x N]
974       TypeVals.push_back(ST->isPacked());
975       // Output all of the element types.
976       for (Type *ET : ST->elements())
977         TypeVals.push_back(VE.getTypeID(ET));
978 
979       if (ST->isLiteral()) {
980         Code = bitc::TYPE_CODE_STRUCT_ANON;
981         AbbrevToUse = StructAnonAbbrev;
982       } else {
983         if (ST->isOpaque()) {
984           Code = bitc::TYPE_CODE_OPAQUE;
985         } else {
986           Code = bitc::TYPE_CODE_STRUCT_NAMED;
987           AbbrevToUse = StructNamedAbbrev;
988         }
989 
990         // Emit the name if it is present.
991         if (!ST->getName().empty())
992           writeStringRecord(Stream, bitc::TYPE_CODE_STRUCT_NAME, ST->getName(),
993                             StructNameAbbrev);
994       }
995       break;
996     }
997     case Type::ArrayTyID: {
998       ArrayType *AT = cast<ArrayType>(T);
999       // ARRAY: [numelts, eltty]
1000       Code = bitc::TYPE_CODE_ARRAY;
1001       TypeVals.push_back(AT->getNumElements());
1002       TypeVals.push_back(VE.getTypeID(AT->getElementType()));
1003       AbbrevToUse = ArrayAbbrev;
1004       break;
1005     }
1006     case Type::FixedVectorTyID:
1007     case Type::ScalableVectorTyID: {
1008       VectorType *VT = cast<VectorType>(T);
1009       // VECTOR [numelts, eltty] or
1010       //        [numelts, eltty, scalable]
1011       Code = bitc::TYPE_CODE_VECTOR;
1012       TypeVals.push_back(VT->getElementCount().getKnownMinValue());
1013       TypeVals.push_back(VE.getTypeID(VT->getElementType()));
1014       if (isa<ScalableVectorType>(VT))
1015         TypeVals.push_back(true);
1016       break;
1017     }
1018     }
1019 
1020     // Emit the finished record.
1021     Stream.EmitRecord(Code, TypeVals, AbbrevToUse);
1022     TypeVals.clear();
1023   }
1024 
1025   Stream.ExitBlock();
1026 }
1027 
1028 static unsigned getEncodedLinkage(const GlobalValue::LinkageTypes Linkage) {
1029   switch (Linkage) {
1030   case GlobalValue::ExternalLinkage:
1031     return 0;
1032   case GlobalValue::WeakAnyLinkage:
1033     return 16;
1034   case GlobalValue::AppendingLinkage:
1035     return 2;
1036   case GlobalValue::InternalLinkage:
1037     return 3;
1038   case GlobalValue::LinkOnceAnyLinkage:
1039     return 18;
1040   case GlobalValue::ExternalWeakLinkage:
1041     return 7;
1042   case GlobalValue::CommonLinkage:
1043     return 8;
1044   case GlobalValue::PrivateLinkage:
1045     return 9;
1046   case GlobalValue::WeakODRLinkage:
1047     return 17;
1048   case GlobalValue::LinkOnceODRLinkage:
1049     return 19;
1050   case GlobalValue::AvailableExternallyLinkage:
1051     return 12;
1052   }
1053   llvm_unreachable("Invalid linkage");
1054 }
1055 
1056 static unsigned getEncodedLinkage(const GlobalValue &GV) {
1057   return getEncodedLinkage(GV.getLinkage());
1058 }
1059 
1060 static uint64_t getEncodedFFlags(FunctionSummary::FFlags Flags) {
1061   uint64_t RawFlags = 0;
1062   RawFlags |= Flags.ReadNone;
1063   RawFlags |= (Flags.ReadOnly << 1);
1064   RawFlags |= (Flags.NoRecurse << 2);
1065   RawFlags |= (Flags.ReturnDoesNotAlias << 3);
1066   RawFlags |= (Flags.NoInline << 4);
1067   RawFlags |= (Flags.AlwaysInline << 5);
1068   RawFlags |= (Flags.NoUnwind << 6);
1069   RawFlags |= (Flags.MayThrow << 7);
1070   RawFlags |= (Flags.HasUnknownCall << 8);
1071   return RawFlags;
1072 }
1073 
1074 // Decode the flags for GlobalValue in the summary. See getDecodedGVSummaryFlags
1075 // in BitcodeReader.cpp.
1076 static uint64_t getEncodedGVSummaryFlags(GlobalValueSummary::GVFlags Flags) {
1077   uint64_t RawFlags = 0;
1078 
1079   RawFlags |= Flags.NotEligibleToImport; // bool
1080   RawFlags |= (Flags.Live << 1);
1081   RawFlags |= (Flags.DSOLocal << 2);
1082   RawFlags |= (Flags.CanAutoHide << 3);
1083 
1084   // Linkage don't need to be remapped at that time for the summary. Any future
1085   // change to the getEncodedLinkage() function will need to be taken into
1086   // account here as well.
1087   RawFlags = (RawFlags << 4) | Flags.Linkage; // 4 bits
1088 
1089   RawFlags |= (Flags.Visibility << 8); // 2 bits
1090 
1091   return RawFlags;
1092 }
1093 
1094 static uint64_t getEncodedGVarFlags(GlobalVarSummary::GVarFlags Flags) {
1095   uint64_t RawFlags = Flags.MaybeReadOnly | (Flags.MaybeWriteOnly << 1) |
1096                       (Flags.Constant << 2) | Flags.VCallVisibility << 3;
1097   return RawFlags;
1098 }
1099 
1100 static unsigned getEncodedVisibility(const GlobalValue &GV) {
1101   switch (GV.getVisibility()) {
1102   case GlobalValue::DefaultVisibility:   return 0;
1103   case GlobalValue::HiddenVisibility:    return 1;
1104   case GlobalValue::ProtectedVisibility: return 2;
1105   }
1106   llvm_unreachable("Invalid visibility");
1107 }
1108 
1109 static unsigned getEncodedDLLStorageClass(const GlobalValue &GV) {
1110   switch (GV.getDLLStorageClass()) {
1111   case GlobalValue::DefaultStorageClass:   return 0;
1112   case GlobalValue::DLLImportStorageClass: return 1;
1113   case GlobalValue::DLLExportStorageClass: return 2;
1114   }
1115   llvm_unreachable("Invalid DLL storage class");
1116 }
1117 
1118 static unsigned getEncodedThreadLocalMode(const GlobalValue &GV) {
1119   switch (GV.getThreadLocalMode()) {
1120     case GlobalVariable::NotThreadLocal:         return 0;
1121     case GlobalVariable::GeneralDynamicTLSModel: return 1;
1122     case GlobalVariable::LocalDynamicTLSModel:   return 2;
1123     case GlobalVariable::InitialExecTLSModel:    return 3;
1124     case GlobalVariable::LocalExecTLSModel:      return 4;
1125   }
1126   llvm_unreachable("Invalid TLS model");
1127 }
1128 
1129 static unsigned getEncodedComdatSelectionKind(const Comdat &C) {
1130   switch (C.getSelectionKind()) {
1131   case Comdat::Any:
1132     return bitc::COMDAT_SELECTION_KIND_ANY;
1133   case Comdat::ExactMatch:
1134     return bitc::COMDAT_SELECTION_KIND_EXACT_MATCH;
1135   case Comdat::Largest:
1136     return bitc::COMDAT_SELECTION_KIND_LARGEST;
1137   case Comdat::NoDeduplicate:
1138     return bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES;
1139   case Comdat::SameSize:
1140     return bitc::COMDAT_SELECTION_KIND_SAME_SIZE;
1141   }
1142   llvm_unreachable("Invalid selection kind");
1143 }
1144 
1145 static unsigned getEncodedUnnamedAddr(const GlobalValue &GV) {
1146   switch (GV.getUnnamedAddr()) {
1147   case GlobalValue::UnnamedAddr::None:   return 0;
1148   case GlobalValue::UnnamedAddr::Local:  return 2;
1149   case GlobalValue::UnnamedAddr::Global: return 1;
1150   }
1151   llvm_unreachable("Invalid unnamed_addr");
1152 }
1153 
1154 size_t ModuleBitcodeWriter::addToStrtab(StringRef Str) {
1155   if (GenerateHash)
1156     Hasher.update(Str);
1157   return StrtabBuilder.add(Str);
1158 }
1159 
1160 void ModuleBitcodeWriter::writeComdats() {
1161   SmallVector<unsigned, 64> Vals;
1162   for (const Comdat *C : VE.getComdats()) {
1163     // COMDAT: [strtab offset, strtab size, selection_kind]
1164     Vals.push_back(addToStrtab(C->getName()));
1165     Vals.push_back(C->getName().size());
1166     Vals.push_back(getEncodedComdatSelectionKind(*C));
1167     Stream.EmitRecord(bitc::MODULE_CODE_COMDAT, Vals, /*AbbrevToUse=*/0);
1168     Vals.clear();
1169   }
1170 }
1171 
1172 /// Write a record that will eventually hold the word offset of the
1173 /// module-level VST. For now the offset is 0, which will be backpatched
1174 /// after the real VST is written. Saves the bit offset to backpatch.
1175 void ModuleBitcodeWriter::writeValueSymbolTableForwardDecl() {
1176   // Write a placeholder value in for the offset of the real VST,
1177   // which is written after the function blocks so that it can include
1178   // the offset of each function. The placeholder offset will be
1179   // updated when the real VST is written.
1180   auto Abbv = std::make_shared<BitCodeAbbrev>();
1181   Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_VSTOFFSET));
1182   // Blocks are 32-bit aligned, so we can use a 32-bit word offset to
1183   // hold the real VST offset. Must use fixed instead of VBR as we don't
1184   // know how many VBR chunks to reserve ahead of time.
1185   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1186   unsigned VSTOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1187 
1188   // Emit the placeholder
1189   uint64_t Vals[] = {bitc::MODULE_CODE_VSTOFFSET, 0};
1190   Stream.EmitRecordWithAbbrev(VSTOffsetAbbrev, Vals);
1191 
1192   // Compute and save the bit offset to the placeholder, which will be
1193   // patched when the real VST is written. We can simply subtract the 32-bit
1194   // fixed size from the current bit number to get the location to backpatch.
1195   VSTOffsetPlaceholder = Stream.GetCurrentBitNo() - 32;
1196 }
1197 
1198 enum StringEncoding { SE_Char6, SE_Fixed7, SE_Fixed8 };
1199 
1200 /// Determine the encoding to use for the given string name and length.
1201 static StringEncoding getStringEncoding(StringRef Str) {
1202   bool isChar6 = true;
1203   for (char C : Str) {
1204     if (isChar6)
1205       isChar6 = BitCodeAbbrevOp::isChar6(C);
1206     if ((unsigned char)C & 128)
1207       // don't bother scanning the rest.
1208       return SE_Fixed8;
1209   }
1210   if (isChar6)
1211     return SE_Char6;
1212   return SE_Fixed7;
1213 }
1214 
1215 /// Emit top-level description of module, including target triple, inline asm,
1216 /// descriptors for global variables, and function prototype info.
1217 /// Returns the bit offset to backpatch with the location of the real VST.
1218 void ModuleBitcodeWriter::writeModuleInfo() {
1219   // Emit various pieces of data attached to a module.
1220   if (!M.getTargetTriple().empty())
1221     writeStringRecord(Stream, bitc::MODULE_CODE_TRIPLE, M.getTargetTriple(),
1222                       0 /*TODO*/);
1223   const std::string &DL = M.getDataLayoutStr();
1224   if (!DL.empty())
1225     writeStringRecord(Stream, bitc::MODULE_CODE_DATALAYOUT, DL, 0 /*TODO*/);
1226   if (!M.getModuleInlineAsm().empty())
1227     writeStringRecord(Stream, bitc::MODULE_CODE_ASM, M.getModuleInlineAsm(),
1228                       0 /*TODO*/);
1229 
1230   // Emit information about sections and GC, computing how many there are. Also
1231   // compute the maximum alignment value.
1232   std::map<std::string, unsigned> SectionMap;
1233   std::map<std::string, unsigned> GCMap;
1234   MaybeAlign MaxAlignment;
1235   unsigned MaxGlobalType = 0;
1236   const auto UpdateMaxAlignment = [&MaxAlignment](const MaybeAlign A) {
1237     if (A)
1238       MaxAlignment = !MaxAlignment ? *A : std::max(*MaxAlignment, *A);
1239   };
1240   for (const GlobalVariable &GV : M.globals()) {
1241     UpdateMaxAlignment(GV.getAlign());
1242     MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV.getValueType()));
1243     if (GV.hasSection()) {
1244       // Give section names unique ID's.
1245       unsigned &Entry = SectionMap[std::string(GV.getSection())];
1246       if (!Entry) {
1247         writeStringRecord(Stream, bitc::MODULE_CODE_SECTIONNAME, GV.getSection(),
1248                           0 /*TODO*/);
1249         Entry = SectionMap.size();
1250       }
1251     }
1252   }
1253   for (const Function &F : M) {
1254     UpdateMaxAlignment(F.getAlign());
1255     if (F.hasSection()) {
1256       // Give section names unique ID's.
1257       unsigned &Entry = SectionMap[std::string(F.getSection())];
1258       if (!Entry) {
1259         writeStringRecord(Stream, bitc::MODULE_CODE_SECTIONNAME, F.getSection(),
1260                           0 /*TODO*/);
1261         Entry = SectionMap.size();
1262       }
1263     }
1264     if (F.hasGC()) {
1265       // Same for GC names.
1266       unsigned &Entry = GCMap[F.getGC()];
1267       if (!Entry) {
1268         writeStringRecord(Stream, bitc::MODULE_CODE_GCNAME, F.getGC(),
1269                           0 /*TODO*/);
1270         Entry = GCMap.size();
1271       }
1272     }
1273   }
1274 
1275   // Emit abbrev for globals, now that we know # sections and max alignment.
1276   unsigned SimpleGVarAbbrev = 0;
1277   if (!M.global_empty()) {
1278     // Add an abbrev for common globals with no visibility or thread localness.
1279     auto Abbv = std::make_shared<BitCodeAbbrev>();
1280     Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GLOBALVAR));
1281     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1282     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1283     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
1284                               Log2_32_Ceil(MaxGlobalType+1)));
1285     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // AddrSpace << 2
1286                                                            //| explicitType << 1
1287                                                            //| constant
1288     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // Initializer.
1289     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5)); // Linkage.
1290     if (!MaxAlignment)                                     // Alignment.
1291       Abbv->Add(BitCodeAbbrevOp(0));
1292     else {
1293       unsigned MaxEncAlignment = getEncodedAlign(MaxAlignment);
1294       Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
1295                                Log2_32_Ceil(MaxEncAlignment+1)));
1296     }
1297     if (SectionMap.empty())                                    // Section.
1298       Abbv->Add(BitCodeAbbrevOp(0));
1299     else
1300       Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
1301                                Log2_32_Ceil(SectionMap.size()+1)));
1302     // Don't bother emitting vis + thread local.
1303     SimpleGVarAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1304   }
1305 
1306   SmallVector<unsigned, 64> Vals;
1307   // Emit the module's source file name.
1308   {
1309     StringEncoding Bits = getStringEncoding(M.getSourceFileName());
1310     BitCodeAbbrevOp AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8);
1311     if (Bits == SE_Char6)
1312       AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Char6);
1313     else if (Bits == SE_Fixed7)
1314       AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7);
1315 
1316     // MODULE_CODE_SOURCE_FILENAME: [namechar x N]
1317     auto Abbv = std::make_shared<BitCodeAbbrev>();
1318     Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_SOURCE_FILENAME));
1319     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1320     Abbv->Add(AbbrevOpToUse);
1321     unsigned FilenameAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1322 
1323     for (const auto P : M.getSourceFileName())
1324       Vals.push_back((unsigned char)P);
1325 
1326     // Emit the finished record.
1327     Stream.EmitRecord(bitc::MODULE_CODE_SOURCE_FILENAME, Vals, FilenameAbbrev);
1328     Vals.clear();
1329   }
1330 
1331   // Emit the global variable information.
1332   for (const GlobalVariable &GV : M.globals()) {
1333     unsigned AbbrevToUse = 0;
1334 
1335     // GLOBALVAR: [strtab offset, strtab size, type, isconst, initid,
1336     //             linkage, alignment, section, visibility, threadlocal,
1337     //             unnamed_addr, externally_initialized, dllstorageclass,
1338     //             comdat, attributes, DSO_Local]
1339     Vals.push_back(addToStrtab(GV.getName()));
1340     Vals.push_back(GV.getName().size());
1341     Vals.push_back(VE.getTypeID(GV.getValueType()));
1342     Vals.push_back(GV.getType()->getAddressSpace() << 2 | 2 | GV.isConstant());
1343     Vals.push_back(GV.isDeclaration() ? 0 :
1344                    (VE.getValueID(GV.getInitializer()) + 1));
1345     Vals.push_back(getEncodedLinkage(GV));
1346     Vals.push_back(getEncodedAlign(GV.getAlign()));
1347     Vals.push_back(GV.hasSection() ? SectionMap[std::string(GV.getSection())]
1348                                    : 0);
1349     if (GV.isThreadLocal() ||
1350         GV.getVisibility() != GlobalValue::DefaultVisibility ||
1351         GV.getUnnamedAddr() != GlobalValue::UnnamedAddr::None ||
1352         GV.isExternallyInitialized() ||
1353         GV.getDLLStorageClass() != GlobalValue::DefaultStorageClass ||
1354         GV.hasComdat() ||
1355         GV.hasAttributes() ||
1356         GV.isDSOLocal() ||
1357         GV.hasPartition()) {
1358       Vals.push_back(getEncodedVisibility(GV));
1359       Vals.push_back(getEncodedThreadLocalMode(GV));
1360       Vals.push_back(getEncodedUnnamedAddr(GV));
1361       Vals.push_back(GV.isExternallyInitialized());
1362       Vals.push_back(getEncodedDLLStorageClass(GV));
1363       Vals.push_back(GV.hasComdat() ? VE.getComdatID(GV.getComdat()) : 0);
1364 
1365       auto AL = GV.getAttributesAsList(AttributeList::FunctionIndex);
1366       Vals.push_back(VE.getAttributeListID(AL));
1367 
1368       Vals.push_back(GV.isDSOLocal());
1369       Vals.push_back(addToStrtab(GV.getPartition()));
1370       Vals.push_back(GV.getPartition().size());
1371     } else {
1372       AbbrevToUse = SimpleGVarAbbrev;
1373     }
1374 
1375     Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse);
1376     Vals.clear();
1377   }
1378 
1379   // Emit the function proto information.
1380   for (const Function &F : M) {
1381     // FUNCTION:  [strtab offset, strtab size, type, callingconv, isproto,
1382     //             linkage, paramattrs, alignment, section, visibility, gc,
1383     //             unnamed_addr, prologuedata, dllstorageclass, comdat,
1384     //             prefixdata, personalityfn, DSO_Local, addrspace]
1385     Vals.push_back(addToStrtab(F.getName()));
1386     Vals.push_back(F.getName().size());
1387     Vals.push_back(VE.getTypeID(F.getFunctionType()));
1388     Vals.push_back(F.getCallingConv());
1389     Vals.push_back(F.isDeclaration());
1390     Vals.push_back(getEncodedLinkage(F));
1391     Vals.push_back(VE.getAttributeListID(F.getAttributes()));
1392     Vals.push_back(getEncodedAlign(F.getAlign()));
1393     Vals.push_back(F.hasSection() ? SectionMap[std::string(F.getSection())]
1394                                   : 0);
1395     Vals.push_back(getEncodedVisibility(F));
1396     Vals.push_back(F.hasGC() ? GCMap[F.getGC()] : 0);
1397     Vals.push_back(getEncodedUnnamedAddr(F));
1398     Vals.push_back(F.hasPrologueData() ? (VE.getValueID(F.getPrologueData()) + 1)
1399                                        : 0);
1400     Vals.push_back(getEncodedDLLStorageClass(F));
1401     Vals.push_back(F.hasComdat() ? VE.getComdatID(F.getComdat()) : 0);
1402     Vals.push_back(F.hasPrefixData() ? (VE.getValueID(F.getPrefixData()) + 1)
1403                                      : 0);
1404     Vals.push_back(
1405         F.hasPersonalityFn() ? (VE.getValueID(F.getPersonalityFn()) + 1) : 0);
1406 
1407     Vals.push_back(F.isDSOLocal());
1408     Vals.push_back(F.getAddressSpace());
1409     Vals.push_back(addToStrtab(F.getPartition()));
1410     Vals.push_back(F.getPartition().size());
1411 
1412     unsigned AbbrevToUse = 0;
1413     Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse);
1414     Vals.clear();
1415   }
1416 
1417   // Emit the alias information.
1418   for (const GlobalAlias &A : M.aliases()) {
1419     // ALIAS: [strtab offset, strtab size, alias type, aliasee val#, linkage,
1420     //         visibility, dllstorageclass, threadlocal, unnamed_addr,
1421     //         DSO_Local]
1422     Vals.push_back(addToStrtab(A.getName()));
1423     Vals.push_back(A.getName().size());
1424     Vals.push_back(VE.getTypeID(A.getValueType()));
1425     Vals.push_back(A.getType()->getAddressSpace());
1426     Vals.push_back(VE.getValueID(A.getAliasee()));
1427     Vals.push_back(getEncodedLinkage(A));
1428     Vals.push_back(getEncodedVisibility(A));
1429     Vals.push_back(getEncodedDLLStorageClass(A));
1430     Vals.push_back(getEncodedThreadLocalMode(A));
1431     Vals.push_back(getEncodedUnnamedAddr(A));
1432     Vals.push_back(A.isDSOLocal());
1433     Vals.push_back(addToStrtab(A.getPartition()));
1434     Vals.push_back(A.getPartition().size());
1435 
1436     unsigned AbbrevToUse = 0;
1437     Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse);
1438     Vals.clear();
1439   }
1440 
1441   // Emit the ifunc information.
1442   for (const GlobalIFunc &I : M.ifuncs()) {
1443     // IFUNC: [strtab offset, strtab size, ifunc type, address space, resolver
1444     //         val#, linkage, visibility, DSO_Local]
1445     Vals.push_back(addToStrtab(I.getName()));
1446     Vals.push_back(I.getName().size());
1447     Vals.push_back(VE.getTypeID(I.getValueType()));
1448     Vals.push_back(I.getType()->getAddressSpace());
1449     Vals.push_back(VE.getValueID(I.getResolver()));
1450     Vals.push_back(getEncodedLinkage(I));
1451     Vals.push_back(getEncodedVisibility(I));
1452     Vals.push_back(I.isDSOLocal());
1453     Vals.push_back(addToStrtab(I.getPartition()));
1454     Vals.push_back(I.getPartition().size());
1455     Stream.EmitRecord(bitc::MODULE_CODE_IFUNC, Vals);
1456     Vals.clear();
1457   }
1458 
1459   writeValueSymbolTableForwardDecl();
1460 }
1461 
1462 static uint64_t getOptimizationFlags(const Value *V) {
1463   uint64_t Flags = 0;
1464 
1465   if (const auto *OBO = dyn_cast<OverflowingBinaryOperator>(V)) {
1466     if (OBO->hasNoSignedWrap())
1467       Flags |= 1 << bitc::OBO_NO_SIGNED_WRAP;
1468     if (OBO->hasNoUnsignedWrap())
1469       Flags |= 1 << bitc::OBO_NO_UNSIGNED_WRAP;
1470   } else if (const auto *PEO = dyn_cast<PossiblyExactOperator>(V)) {
1471     if (PEO->isExact())
1472       Flags |= 1 << bitc::PEO_EXACT;
1473   } else if (const auto *FPMO = dyn_cast<FPMathOperator>(V)) {
1474     if (FPMO->hasAllowReassoc())
1475       Flags |= bitc::AllowReassoc;
1476     if (FPMO->hasNoNaNs())
1477       Flags |= bitc::NoNaNs;
1478     if (FPMO->hasNoInfs())
1479       Flags |= bitc::NoInfs;
1480     if (FPMO->hasNoSignedZeros())
1481       Flags |= bitc::NoSignedZeros;
1482     if (FPMO->hasAllowReciprocal())
1483       Flags |= bitc::AllowReciprocal;
1484     if (FPMO->hasAllowContract())
1485       Flags |= bitc::AllowContract;
1486     if (FPMO->hasApproxFunc())
1487       Flags |= bitc::ApproxFunc;
1488   }
1489 
1490   return Flags;
1491 }
1492 
1493 void ModuleBitcodeWriter::writeValueAsMetadata(
1494     const ValueAsMetadata *MD, SmallVectorImpl<uint64_t> &Record) {
1495   // Mimic an MDNode with a value as one operand.
1496   Value *V = MD->getValue();
1497   Record.push_back(VE.getTypeID(V->getType()));
1498   Record.push_back(VE.getValueID(V));
1499   Stream.EmitRecord(bitc::METADATA_VALUE, Record, 0);
1500   Record.clear();
1501 }
1502 
1503 void ModuleBitcodeWriter::writeMDTuple(const MDTuple *N,
1504                                        SmallVectorImpl<uint64_t> &Record,
1505                                        unsigned Abbrev) {
1506   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1507     Metadata *MD = N->getOperand(i);
1508     assert(!(MD && isa<LocalAsMetadata>(MD)) &&
1509            "Unexpected function-local metadata");
1510     Record.push_back(VE.getMetadataOrNullID(MD));
1511   }
1512   Stream.EmitRecord(N->isDistinct() ? bitc::METADATA_DISTINCT_NODE
1513                                     : bitc::METADATA_NODE,
1514                     Record, Abbrev);
1515   Record.clear();
1516 }
1517 
1518 unsigned ModuleBitcodeWriter::createDILocationAbbrev() {
1519   // Assume the column is usually under 128, and always output the inlined-at
1520   // location (it's never more expensive than building an array size 1).
1521   auto Abbv = std::make_shared<BitCodeAbbrev>();
1522   Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_LOCATION));
1523   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1524   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1525   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1526   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1527   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1528   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1529   return Stream.EmitAbbrev(std::move(Abbv));
1530 }
1531 
1532 void ModuleBitcodeWriter::writeDILocation(const DILocation *N,
1533                                           SmallVectorImpl<uint64_t> &Record,
1534                                           unsigned &Abbrev) {
1535   if (!Abbrev)
1536     Abbrev = createDILocationAbbrev();
1537 
1538   Record.push_back(N->isDistinct());
1539   Record.push_back(N->getLine());
1540   Record.push_back(N->getColumn());
1541   Record.push_back(VE.getMetadataID(N->getScope()));
1542   Record.push_back(VE.getMetadataOrNullID(N->getInlinedAt()));
1543   Record.push_back(N->isImplicitCode());
1544 
1545   Stream.EmitRecord(bitc::METADATA_LOCATION, Record, Abbrev);
1546   Record.clear();
1547 }
1548 
1549 unsigned ModuleBitcodeWriter::createGenericDINodeAbbrev() {
1550   // Assume the column is usually under 128, and always output the inlined-at
1551   // location (it's never more expensive than building an array size 1).
1552   auto Abbv = std::make_shared<BitCodeAbbrev>();
1553   Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_GENERIC_DEBUG));
1554   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1555   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1556   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1557   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1558   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1559   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1560   return Stream.EmitAbbrev(std::move(Abbv));
1561 }
1562 
1563 void ModuleBitcodeWriter::writeGenericDINode(const GenericDINode *N,
1564                                              SmallVectorImpl<uint64_t> &Record,
1565                                              unsigned &Abbrev) {
1566   if (!Abbrev)
1567     Abbrev = createGenericDINodeAbbrev();
1568 
1569   Record.push_back(N->isDistinct());
1570   Record.push_back(N->getTag());
1571   Record.push_back(0); // Per-tag version field; unused for now.
1572 
1573   for (auto &I : N->operands())
1574     Record.push_back(VE.getMetadataOrNullID(I));
1575 
1576   Stream.EmitRecord(bitc::METADATA_GENERIC_DEBUG, Record, Abbrev);
1577   Record.clear();
1578 }
1579 
1580 void ModuleBitcodeWriter::writeDISubrange(const DISubrange *N,
1581                                           SmallVectorImpl<uint64_t> &Record,
1582                                           unsigned Abbrev) {
1583   const uint64_t Version = 2 << 1;
1584   Record.push_back((uint64_t)N->isDistinct() | Version);
1585   Record.push_back(VE.getMetadataOrNullID(N->getRawCountNode()));
1586   Record.push_back(VE.getMetadataOrNullID(N->getRawLowerBound()));
1587   Record.push_back(VE.getMetadataOrNullID(N->getRawUpperBound()));
1588   Record.push_back(VE.getMetadataOrNullID(N->getRawStride()));
1589 
1590   Stream.EmitRecord(bitc::METADATA_SUBRANGE, Record, Abbrev);
1591   Record.clear();
1592 }
1593 
1594 void ModuleBitcodeWriter::writeDIGenericSubrange(
1595     const DIGenericSubrange *N, SmallVectorImpl<uint64_t> &Record,
1596     unsigned Abbrev) {
1597   Record.push_back((uint64_t)N->isDistinct());
1598   Record.push_back(VE.getMetadataOrNullID(N->getRawCountNode()));
1599   Record.push_back(VE.getMetadataOrNullID(N->getRawLowerBound()));
1600   Record.push_back(VE.getMetadataOrNullID(N->getRawUpperBound()));
1601   Record.push_back(VE.getMetadataOrNullID(N->getRawStride()));
1602 
1603   Stream.EmitRecord(bitc::METADATA_GENERIC_SUBRANGE, Record, Abbrev);
1604   Record.clear();
1605 }
1606 
1607 static void emitSignedInt64(SmallVectorImpl<uint64_t> &Vals, uint64_t V) {
1608   if ((int64_t)V >= 0)
1609     Vals.push_back(V << 1);
1610   else
1611     Vals.push_back((-V << 1) | 1);
1612 }
1613 
1614 static void emitWideAPInt(SmallVectorImpl<uint64_t> &Vals, const APInt &A) {
1615   // We have an arbitrary precision integer value to write whose
1616   // bit width is > 64. However, in canonical unsigned integer
1617   // format it is likely that the high bits are going to be zero.
1618   // So, we only write the number of active words.
1619   unsigned NumWords = A.getActiveWords();
1620   const uint64_t *RawData = A.getRawData();
1621   for (unsigned i = 0; i < NumWords; i++)
1622     emitSignedInt64(Vals, RawData[i]);
1623 }
1624 
1625 void ModuleBitcodeWriter::writeDIEnumerator(const DIEnumerator *N,
1626                                             SmallVectorImpl<uint64_t> &Record,
1627                                             unsigned Abbrev) {
1628   const uint64_t IsBigInt = 1 << 2;
1629   Record.push_back(IsBigInt | (N->isUnsigned() << 1) | N->isDistinct());
1630   Record.push_back(N->getValue().getBitWidth());
1631   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1632   emitWideAPInt(Record, N->getValue());
1633 
1634   Stream.EmitRecord(bitc::METADATA_ENUMERATOR, Record, Abbrev);
1635   Record.clear();
1636 }
1637 
1638 void ModuleBitcodeWriter::writeDIBasicType(const DIBasicType *N,
1639                                            SmallVectorImpl<uint64_t> &Record,
1640                                            unsigned Abbrev) {
1641   Record.push_back(N->isDistinct());
1642   Record.push_back(N->getTag());
1643   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1644   Record.push_back(N->getSizeInBits());
1645   Record.push_back(N->getAlignInBits());
1646   Record.push_back(N->getEncoding());
1647   Record.push_back(N->getFlags());
1648 
1649   Stream.EmitRecord(bitc::METADATA_BASIC_TYPE, Record, Abbrev);
1650   Record.clear();
1651 }
1652 
1653 void ModuleBitcodeWriter::writeDIStringType(const DIStringType *N,
1654                                             SmallVectorImpl<uint64_t> &Record,
1655                                             unsigned Abbrev) {
1656   Record.push_back(N->isDistinct());
1657   Record.push_back(N->getTag());
1658   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1659   Record.push_back(VE.getMetadataOrNullID(N->getStringLength()));
1660   Record.push_back(VE.getMetadataOrNullID(N->getStringLengthExp()));
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(
2463           unsigned(IA->hasSideEffects()) | unsigned(IA->isAlignStack()) << 1 |
2464           unsigned(IA->getDialect() & 1) << 2 | unsigned(IA->canThrow()) << 3);
2465 
2466       // Add the asm string.
2467       const std::string &AsmStr = IA->getAsmString();
2468       Record.push_back(AsmStr.size());
2469       Record.append(AsmStr.begin(), AsmStr.end());
2470 
2471       // Add the constraint string.
2472       const std::string &ConstraintStr = IA->getConstraintString();
2473       Record.push_back(ConstraintStr.size());
2474       Record.append(ConstraintStr.begin(), ConstraintStr.end());
2475       Stream.EmitRecord(bitc::CST_CODE_INLINEASM, Record);
2476       Record.clear();
2477       continue;
2478     }
2479     const Constant *C = cast<Constant>(V);
2480     unsigned Code = -1U;
2481     unsigned AbbrevToUse = 0;
2482     if (C->isNullValue()) {
2483       Code = bitc::CST_CODE_NULL;
2484     } else if (isa<PoisonValue>(C)) {
2485       Code = bitc::CST_CODE_POISON;
2486     } else if (isa<UndefValue>(C)) {
2487       Code = bitc::CST_CODE_UNDEF;
2488     } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {
2489       if (IV->getBitWidth() <= 64) {
2490         uint64_t V = IV->getSExtValue();
2491         emitSignedInt64(Record, V);
2492         Code = bitc::CST_CODE_INTEGER;
2493         AbbrevToUse = CONSTANTS_INTEGER_ABBREV;
2494       } else {                             // Wide integers, > 64 bits in size.
2495         emitWideAPInt(Record, IV->getValue());
2496         Code = bitc::CST_CODE_WIDE_INTEGER;
2497       }
2498     } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
2499       Code = bitc::CST_CODE_FLOAT;
2500       Type *Ty = CFP->getType();
2501       if (Ty->isHalfTy() || Ty->isBFloatTy() || Ty->isFloatTy() ||
2502           Ty->isDoubleTy()) {
2503         Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
2504       } else if (Ty->isX86_FP80Ty()) {
2505         // api needed to prevent premature destruction
2506         // bits are not in the same order as a normal i80 APInt, compensate.
2507         APInt api = CFP->getValueAPF().bitcastToAPInt();
2508         const uint64_t *p = api.getRawData();
2509         Record.push_back((p[1] << 48) | (p[0] >> 16));
2510         Record.push_back(p[0] & 0xffffLL);
2511       } else if (Ty->isFP128Ty() || Ty->isPPC_FP128Ty()) {
2512         APInt api = CFP->getValueAPF().bitcastToAPInt();
2513         const uint64_t *p = api.getRawData();
2514         Record.push_back(p[0]);
2515         Record.push_back(p[1]);
2516       } else {
2517         assert(0 && "Unknown FP type!");
2518       }
2519     } else if (isa<ConstantDataSequential>(C) &&
2520                cast<ConstantDataSequential>(C)->isString()) {
2521       const ConstantDataSequential *Str = cast<ConstantDataSequential>(C);
2522       // Emit constant strings specially.
2523       unsigned NumElts = Str->getNumElements();
2524       // If this is a null-terminated string, use the denser CSTRING encoding.
2525       if (Str->isCString()) {
2526         Code = bitc::CST_CODE_CSTRING;
2527         --NumElts;  // Don't encode the null, which isn't allowed by char6.
2528       } else {
2529         Code = bitc::CST_CODE_STRING;
2530         AbbrevToUse = String8Abbrev;
2531       }
2532       bool isCStr7 = Code == bitc::CST_CODE_CSTRING;
2533       bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING;
2534       for (unsigned i = 0; i != NumElts; ++i) {
2535         unsigned char V = Str->getElementAsInteger(i);
2536         Record.push_back(V);
2537         isCStr7 &= (V & 128) == 0;
2538         if (isCStrChar6)
2539           isCStrChar6 = BitCodeAbbrevOp::isChar6(V);
2540       }
2541 
2542       if (isCStrChar6)
2543         AbbrevToUse = CString6Abbrev;
2544       else if (isCStr7)
2545         AbbrevToUse = CString7Abbrev;
2546     } else if (const ConstantDataSequential *CDS =
2547                   dyn_cast<ConstantDataSequential>(C)) {
2548       Code = bitc::CST_CODE_DATA;
2549       Type *EltTy = CDS->getElementType();
2550       if (isa<IntegerType>(EltTy)) {
2551         for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
2552           Record.push_back(CDS->getElementAsInteger(i));
2553       } else {
2554         for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
2555           Record.push_back(
2556               CDS->getElementAsAPFloat(i).bitcastToAPInt().getLimitedValue());
2557       }
2558     } else if (isa<ConstantAggregate>(C)) {
2559       Code = bitc::CST_CODE_AGGREGATE;
2560       for (const Value *Op : C->operands())
2561         Record.push_back(VE.getValueID(Op));
2562       AbbrevToUse = AggregateAbbrev;
2563     } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
2564       switch (CE->getOpcode()) {
2565       default:
2566         if (Instruction::isCast(CE->getOpcode())) {
2567           Code = bitc::CST_CODE_CE_CAST;
2568           Record.push_back(getEncodedCastOpcode(CE->getOpcode()));
2569           Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2570           Record.push_back(VE.getValueID(C->getOperand(0)));
2571           AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;
2572         } else {
2573           assert(CE->getNumOperands() == 2 && "Unknown constant expr!");
2574           Code = bitc::CST_CODE_CE_BINOP;
2575           Record.push_back(getEncodedBinaryOpcode(CE->getOpcode()));
2576           Record.push_back(VE.getValueID(C->getOperand(0)));
2577           Record.push_back(VE.getValueID(C->getOperand(1)));
2578           uint64_t Flags = getOptimizationFlags(CE);
2579           if (Flags != 0)
2580             Record.push_back(Flags);
2581         }
2582         break;
2583       case Instruction::FNeg: {
2584         assert(CE->getNumOperands() == 1 && "Unknown constant expr!");
2585         Code = bitc::CST_CODE_CE_UNOP;
2586         Record.push_back(getEncodedUnaryOpcode(CE->getOpcode()));
2587         Record.push_back(VE.getValueID(C->getOperand(0)));
2588         uint64_t Flags = getOptimizationFlags(CE);
2589         if (Flags != 0)
2590           Record.push_back(Flags);
2591         break;
2592       }
2593       case Instruction::GetElementPtr: {
2594         Code = bitc::CST_CODE_CE_GEP;
2595         const auto *GO = cast<GEPOperator>(C);
2596         Record.push_back(VE.getTypeID(GO->getSourceElementType()));
2597         if (Optional<unsigned> Idx = GO->getInRangeIndex()) {
2598           Code = bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX;
2599           Record.push_back((*Idx << 1) | GO->isInBounds());
2600         } else if (GO->isInBounds())
2601           Code = bitc::CST_CODE_CE_INBOUNDS_GEP;
2602         for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
2603           Record.push_back(VE.getTypeID(C->getOperand(i)->getType()));
2604           Record.push_back(VE.getValueID(C->getOperand(i)));
2605         }
2606         break;
2607       }
2608       case Instruction::Select:
2609         Code = bitc::CST_CODE_CE_SELECT;
2610         Record.push_back(VE.getValueID(C->getOperand(0)));
2611         Record.push_back(VE.getValueID(C->getOperand(1)));
2612         Record.push_back(VE.getValueID(C->getOperand(2)));
2613         break;
2614       case Instruction::ExtractElement:
2615         Code = bitc::CST_CODE_CE_EXTRACTELT;
2616         Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2617         Record.push_back(VE.getValueID(C->getOperand(0)));
2618         Record.push_back(VE.getTypeID(C->getOperand(1)->getType()));
2619         Record.push_back(VE.getValueID(C->getOperand(1)));
2620         break;
2621       case Instruction::InsertElement:
2622         Code = bitc::CST_CODE_CE_INSERTELT;
2623         Record.push_back(VE.getValueID(C->getOperand(0)));
2624         Record.push_back(VE.getValueID(C->getOperand(1)));
2625         Record.push_back(VE.getTypeID(C->getOperand(2)->getType()));
2626         Record.push_back(VE.getValueID(C->getOperand(2)));
2627         break;
2628       case Instruction::ShuffleVector:
2629         // If the return type and argument types are the same, this is a
2630         // standard shufflevector instruction.  If the types are different,
2631         // then the shuffle is widening or truncating the input vectors, and
2632         // the argument type must also be encoded.
2633         if (C->getType() == C->getOperand(0)->getType()) {
2634           Code = bitc::CST_CODE_CE_SHUFFLEVEC;
2635         } else {
2636           Code = bitc::CST_CODE_CE_SHUFVEC_EX;
2637           Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2638         }
2639         Record.push_back(VE.getValueID(C->getOperand(0)));
2640         Record.push_back(VE.getValueID(C->getOperand(1)));
2641         Record.push_back(VE.getValueID(CE->getShuffleMaskForBitcode()));
2642         break;
2643       case Instruction::ICmp:
2644       case Instruction::FCmp:
2645         Code = bitc::CST_CODE_CE_CMP;
2646         Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2647         Record.push_back(VE.getValueID(C->getOperand(0)));
2648         Record.push_back(VE.getValueID(C->getOperand(1)));
2649         Record.push_back(CE->getPredicate());
2650         break;
2651       }
2652     } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) {
2653       Code = bitc::CST_CODE_BLOCKADDRESS;
2654       Record.push_back(VE.getTypeID(BA->getFunction()->getType()));
2655       Record.push_back(VE.getValueID(BA->getFunction()));
2656       Record.push_back(VE.getGlobalBasicBlockID(BA->getBasicBlock()));
2657     } else if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C)) {
2658       Code = bitc::CST_CODE_DSO_LOCAL_EQUIVALENT;
2659       Record.push_back(VE.getTypeID(Equiv->getGlobalValue()->getType()));
2660       Record.push_back(VE.getValueID(Equiv->getGlobalValue()));
2661     } else {
2662 #ifndef NDEBUG
2663       C->dump();
2664 #endif
2665       llvm_unreachable("Unknown constant!");
2666     }
2667     Stream.EmitRecord(Code, Record, AbbrevToUse);
2668     Record.clear();
2669   }
2670 
2671   Stream.ExitBlock();
2672 }
2673 
2674 void ModuleBitcodeWriter::writeModuleConstants() {
2675   const ValueEnumerator::ValueList &Vals = VE.getValues();
2676 
2677   // Find the first constant to emit, which is the first non-globalvalue value.
2678   // We know globalvalues have been emitted by WriteModuleInfo.
2679   for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
2680     if (!isa<GlobalValue>(Vals[i].first)) {
2681       writeConstants(i, Vals.size(), true);
2682       return;
2683     }
2684   }
2685 }
2686 
2687 /// pushValueAndType - The file has to encode both the value and type id for
2688 /// many values, because we need to know what type to create for forward
2689 /// references.  However, most operands are not forward references, so this type
2690 /// field is not needed.
2691 ///
2692 /// This function adds V's value ID to Vals.  If the value ID is higher than the
2693 /// instruction ID, then it is a forward reference, and it also includes the
2694 /// type ID.  The value ID that is written is encoded relative to the InstID.
2695 bool ModuleBitcodeWriter::pushValueAndType(const Value *V, unsigned InstID,
2696                                            SmallVectorImpl<unsigned> &Vals) {
2697   unsigned ValID = VE.getValueID(V);
2698   // Make encoding relative to the InstID.
2699   Vals.push_back(InstID - ValID);
2700   if (ValID >= InstID) {
2701     Vals.push_back(VE.getTypeID(V->getType()));
2702     return true;
2703   }
2704   return false;
2705 }
2706 
2707 void ModuleBitcodeWriter::writeOperandBundles(const CallBase &CS,
2708                                               unsigned InstID) {
2709   SmallVector<unsigned, 64> Record;
2710   LLVMContext &C = CS.getContext();
2711 
2712   for (unsigned i = 0, e = CS.getNumOperandBundles(); i != e; ++i) {
2713     const auto &Bundle = CS.getOperandBundleAt(i);
2714     Record.push_back(C.getOperandBundleTagID(Bundle.getTagName()));
2715 
2716     for (auto &Input : Bundle.Inputs)
2717       pushValueAndType(Input, InstID, Record);
2718 
2719     Stream.EmitRecord(bitc::FUNC_CODE_OPERAND_BUNDLE, Record);
2720     Record.clear();
2721   }
2722 }
2723 
2724 /// pushValue - Like pushValueAndType, but where the type of the value is
2725 /// omitted (perhaps it was already encoded in an earlier operand).
2726 void ModuleBitcodeWriter::pushValue(const Value *V, unsigned InstID,
2727                                     SmallVectorImpl<unsigned> &Vals) {
2728   unsigned ValID = VE.getValueID(V);
2729   Vals.push_back(InstID - ValID);
2730 }
2731 
2732 void ModuleBitcodeWriter::pushValueSigned(const Value *V, unsigned InstID,
2733                                           SmallVectorImpl<uint64_t> &Vals) {
2734   unsigned ValID = VE.getValueID(V);
2735   int64_t diff = ((int32_t)InstID - (int32_t)ValID);
2736   emitSignedInt64(Vals, diff);
2737 }
2738 
2739 /// WriteInstruction - Emit an instruction to the specified stream.
2740 void ModuleBitcodeWriter::writeInstruction(const Instruction &I,
2741                                            unsigned InstID,
2742                                            SmallVectorImpl<unsigned> &Vals) {
2743   unsigned Code = 0;
2744   unsigned AbbrevToUse = 0;
2745   VE.setInstructionID(&I);
2746   switch (I.getOpcode()) {
2747   default:
2748     if (Instruction::isCast(I.getOpcode())) {
2749       Code = bitc::FUNC_CODE_INST_CAST;
2750       if (!pushValueAndType(I.getOperand(0), InstID, Vals))
2751         AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
2752       Vals.push_back(VE.getTypeID(I.getType()));
2753       Vals.push_back(getEncodedCastOpcode(I.getOpcode()));
2754     } else {
2755       assert(isa<BinaryOperator>(I) && "Unknown instruction!");
2756       Code = bitc::FUNC_CODE_INST_BINOP;
2757       if (!pushValueAndType(I.getOperand(0), InstID, Vals))
2758         AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
2759       pushValue(I.getOperand(1), InstID, Vals);
2760       Vals.push_back(getEncodedBinaryOpcode(I.getOpcode()));
2761       uint64_t Flags = getOptimizationFlags(&I);
2762       if (Flags != 0) {
2763         if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV)
2764           AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV;
2765         Vals.push_back(Flags);
2766       }
2767     }
2768     break;
2769   case Instruction::FNeg: {
2770     Code = bitc::FUNC_CODE_INST_UNOP;
2771     if (!pushValueAndType(I.getOperand(0), InstID, Vals))
2772       AbbrevToUse = FUNCTION_INST_UNOP_ABBREV;
2773     Vals.push_back(getEncodedUnaryOpcode(I.getOpcode()));
2774     uint64_t Flags = getOptimizationFlags(&I);
2775     if (Flags != 0) {
2776       if (AbbrevToUse == FUNCTION_INST_UNOP_ABBREV)
2777         AbbrevToUse = FUNCTION_INST_UNOP_FLAGS_ABBREV;
2778       Vals.push_back(Flags);
2779     }
2780     break;
2781   }
2782   case Instruction::GetElementPtr: {
2783     Code = bitc::FUNC_CODE_INST_GEP;
2784     AbbrevToUse = FUNCTION_INST_GEP_ABBREV;
2785     auto &GEPInst = cast<GetElementPtrInst>(I);
2786     Vals.push_back(GEPInst.isInBounds());
2787     Vals.push_back(VE.getTypeID(GEPInst.getSourceElementType()));
2788     for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
2789       pushValueAndType(I.getOperand(i), InstID, Vals);
2790     break;
2791   }
2792   case Instruction::ExtractValue: {
2793     Code = bitc::FUNC_CODE_INST_EXTRACTVAL;
2794     pushValueAndType(I.getOperand(0), InstID, Vals);
2795     const ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
2796     Vals.append(EVI->idx_begin(), EVI->idx_end());
2797     break;
2798   }
2799   case Instruction::InsertValue: {
2800     Code = bitc::FUNC_CODE_INST_INSERTVAL;
2801     pushValueAndType(I.getOperand(0), InstID, Vals);
2802     pushValueAndType(I.getOperand(1), InstID, Vals);
2803     const InsertValueInst *IVI = cast<InsertValueInst>(&I);
2804     Vals.append(IVI->idx_begin(), IVI->idx_end());
2805     break;
2806   }
2807   case Instruction::Select: {
2808     Code = bitc::FUNC_CODE_INST_VSELECT;
2809     pushValueAndType(I.getOperand(1), InstID, Vals);
2810     pushValue(I.getOperand(2), InstID, Vals);
2811     pushValueAndType(I.getOperand(0), InstID, Vals);
2812     uint64_t Flags = getOptimizationFlags(&I);
2813     if (Flags != 0)
2814       Vals.push_back(Flags);
2815     break;
2816   }
2817   case Instruction::ExtractElement:
2818     Code = bitc::FUNC_CODE_INST_EXTRACTELT;
2819     pushValueAndType(I.getOperand(0), InstID, Vals);
2820     pushValueAndType(I.getOperand(1), InstID, Vals);
2821     break;
2822   case Instruction::InsertElement:
2823     Code = bitc::FUNC_CODE_INST_INSERTELT;
2824     pushValueAndType(I.getOperand(0), InstID, Vals);
2825     pushValue(I.getOperand(1), InstID, Vals);
2826     pushValueAndType(I.getOperand(2), InstID, Vals);
2827     break;
2828   case Instruction::ShuffleVector:
2829     Code = bitc::FUNC_CODE_INST_SHUFFLEVEC;
2830     pushValueAndType(I.getOperand(0), InstID, Vals);
2831     pushValue(I.getOperand(1), InstID, Vals);
2832     pushValue(cast<ShuffleVectorInst>(I).getShuffleMaskForBitcode(), InstID,
2833               Vals);
2834     break;
2835   case Instruction::ICmp:
2836   case Instruction::FCmp: {
2837     // compare returning Int1Ty or vector of Int1Ty
2838     Code = bitc::FUNC_CODE_INST_CMP2;
2839     pushValueAndType(I.getOperand(0), InstID, Vals);
2840     pushValue(I.getOperand(1), InstID, Vals);
2841     Vals.push_back(cast<CmpInst>(I).getPredicate());
2842     uint64_t Flags = getOptimizationFlags(&I);
2843     if (Flags != 0)
2844       Vals.push_back(Flags);
2845     break;
2846   }
2847 
2848   case Instruction::Ret:
2849     {
2850       Code = bitc::FUNC_CODE_INST_RET;
2851       unsigned NumOperands = I.getNumOperands();
2852       if (NumOperands == 0)
2853         AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
2854       else if (NumOperands == 1) {
2855         if (!pushValueAndType(I.getOperand(0), InstID, Vals))
2856           AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
2857       } else {
2858         for (unsigned i = 0, e = NumOperands; i != e; ++i)
2859           pushValueAndType(I.getOperand(i), InstID, Vals);
2860       }
2861     }
2862     break;
2863   case Instruction::Br:
2864     {
2865       Code = bitc::FUNC_CODE_INST_BR;
2866       const BranchInst &II = cast<BranchInst>(I);
2867       Vals.push_back(VE.getValueID(II.getSuccessor(0)));
2868       if (II.isConditional()) {
2869         Vals.push_back(VE.getValueID(II.getSuccessor(1)));
2870         pushValue(II.getCondition(), InstID, Vals);
2871       }
2872     }
2873     break;
2874   case Instruction::Switch:
2875     {
2876       Code = bitc::FUNC_CODE_INST_SWITCH;
2877       const SwitchInst &SI = cast<SwitchInst>(I);
2878       Vals.push_back(VE.getTypeID(SI.getCondition()->getType()));
2879       pushValue(SI.getCondition(), InstID, Vals);
2880       Vals.push_back(VE.getValueID(SI.getDefaultDest()));
2881       for (auto Case : SI.cases()) {
2882         Vals.push_back(VE.getValueID(Case.getCaseValue()));
2883         Vals.push_back(VE.getValueID(Case.getCaseSuccessor()));
2884       }
2885     }
2886     break;
2887   case Instruction::IndirectBr:
2888     Code = bitc::FUNC_CODE_INST_INDIRECTBR;
2889     Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
2890     // Encode the address operand as relative, but not the basic blocks.
2891     pushValue(I.getOperand(0), InstID, Vals);
2892     for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i)
2893       Vals.push_back(VE.getValueID(I.getOperand(i)));
2894     break;
2895 
2896   case Instruction::Invoke: {
2897     const InvokeInst *II = cast<InvokeInst>(&I);
2898     const Value *Callee = II->getCalledOperand();
2899     FunctionType *FTy = II->getFunctionType();
2900 
2901     if (II->hasOperandBundles())
2902       writeOperandBundles(*II, InstID);
2903 
2904     Code = bitc::FUNC_CODE_INST_INVOKE;
2905 
2906     Vals.push_back(VE.getAttributeListID(II->getAttributes()));
2907     Vals.push_back(II->getCallingConv() | 1 << 13);
2908     Vals.push_back(VE.getValueID(II->getNormalDest()));
2909     Vals.push_back(VE.getValueID(II->getUnwindDest()));
2910     Vals.push_back(VE.getTypeID(FTy));
2911     pushValueAndType(Callee, InstID, Vals);
2912 
2913     // Emit value #'s for the fixed parameters.
2914     for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
2915       pushValue(I.getOperand(i), InstID, Vals); // fixed param.
2916 
2917     // Emit type/value pairs for varargs params.
2918     if (FTy->isVarArg()) {
2919       for (unsigned i = FTy->getNumParams(), e = II->arg_size(); i != e; ++i)
2920         pushValueAndType(I.getOperand(i), InstID, Vals); // vararg
2921     }
2922     break;
2923   }
2924   case Instruction::Resume:
2925     Code = bitc::FUNC_CODE_INST_RESUME;
2926     pushValueAndType(I.getOperand(0), InstID, Vals);
2927     break;
2928   case Instruction::CleanupRet: {
2929     Code = bitc::FUNC_CODE_INST_CLEANUPRET;
2930     const auto &CRI = cast<CleanupReturnInst>(I);
2931     pushValue(CRI.getCleanupPad(), InstID, Vals);
2932     if (CRI.hasUnwindDest())
2933       Vals.push_back(VE.getValueID(CRI.getUnwindDest()));
2934     break;
2935   }
2936   case Instruction::CatchRet: {
2937     Code = bitc::FUNC_CODE_INST_CATCHRET;
2938     const auto &CRI = cast<CatchReturnInst>(I);
2939     pushValue(CRI.getCatchPad(), InstID, Vals);
2940     Vals.push_back(VE.getValueID(CRI.getSuccessor()));
2941     break;
2942   }
2943   case Instruction::CleanupPad:
2944   case Instruction::CatchPad: {
2945     const auto &FuncletPad = cast<FuncletPadInst>(I);
2946     Code = isa<CatchPadInst>(FuncletPad) ? bitc::FUNC_CODE_INST_CATCHPAD
2947                                          : bitc::FUNC_CODE_INST_CLEANUPPAD;
2948     pushValue(FuncletPad.getParentPad(), InstID, Vals);
2949 
2950     unsigned NumArgOperands = FuncletPad.getNumArgOperands();
2951     Vals.push_back(NumArgOperands);
2952     for (unsigned Op = 0; Op != NumArgOperands; ++Op)
2953       pushValueAndType(FuncletPad.getArgOperand(Op), InstID, Vals);
2954     break;
2955   }
2956   case Instruction::CatchSwitch: {
2957     Code = bitc::FUNC_CODE_INST_CATCHSWITCH;
2958     const auto &CatchSwitch = cast<CatchSwitchInst>(I);
2959 
2960     pushValue(CatchSwitch.getParentPad(), InstID, Vals);
2961 
2962     unsigned NumHandlers = CatchSwitch.getNumHandlers();
2963     Vals.push_back(NumHandlers);
2964     for (const BasicBlock *CatchPadBB : CatchSwitch.handlers())
2965       Vals.push_back(VE.getValueID(CatchPadBB));
2966 
2967     if (CatchSwitch.hasUnwindDest())
2968       Vals.push_back(VE.getValueID(CatchSwitch.getUnwindDest()));
2969     break;
2970   }
2971   case Instruction::CallBr: {
2972     const CallBrInst *CBI = cast<CallBrInst>(&I);
2973     const Value *Callee = CBI->getCalledOperand();
2974     FunctionType *FTy = CBI->getFunctionType();
2975 
2976     if (CBI->hasOperandBundles())
2977       writeOperandBundles(*CBI, InstID);
2978 
2979     Code = bitc::FUNC_CODE_INST_CALLBR;
2980 
2981     Vals.push_back(VE.getAttributeListID(CBI->getAttributes()));
2982 
2983     Vals.push_back(CBI->getCallingConv() << bitc::CALL_CCONV |
2984                    1 << bitc::CALL_EXPLICIT_TYPE);
2985 
2986     Vals.push_back(VE.getValueID(CBI->getDefaultDest()));
2987     Vals.push_back(CBI->getNumIndirectDests());
2988     for (unsigned i = 0, e = CBI->getNumIndirectDests(); i != e; ++i)
2989       Vals.push_back(VE.getValueID(CBI->getIndirectDest(i)));
2990 
2991     Vals.push_back(VE.getTypeID(FTy));
2992     pushValueAndType(Callee, InstID, Vals);
2993 
2994     // Emit value #'s for the fixed parameters.
2995     for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
2996       pushValue(I.getOperand(i), InstID, Vals); // fixed param.
2997 
2998     // Emit type/value pairs for varargs params.
2999     if (FTy->isVarArg()) {
3000       for (unsigned i = FTy->getNumParams(), e = CBI->arg_size(); i != e; ++i)
3001         pushValueAndType(I.getOperand(i), InstID, Vals); // vararg
3002     }
3003     break;
3004   }
3005   case Instruction::Unreachable:
3006     Code = bitc::FUNC_CODE_INST_UNREACHABLE;
3007     AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
3008     break;
3009 
3010   case Instruction::PHI: {
3011     const PHINode &PN = cast<PHINode>(I);
3012     Code = bitc::FUNC_CODE_INST_PHI;
3013     // With the newer instruction encoding, forward references could give
3014     // negative valued IDs.  This is most common for PHIs, so we use
3015     // signed VBRs.
3016     SmallVector<uint64_t, 128> Vals64;
3017     Vals64.push_back(VE.getTypeID(PN.getType()));
3018     for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
3019       pushValueSigned(PN.getIncomingValue(i), InstID, Vals64);
3020       Vals64.push_back(VE.getValueID(PN.getIncomingBlock(i)));
3021     }
3022 
3023     uint64_t Flags = getOptimizationFlags(&I);
3024     if (Flags != 0)
3025       Vals64.push_back(Flags);
3026 
3027     // Emit a Vals64 vector and exit.
3028     Stream.EmitRecord(Code, Vals64, AbbrevToUse);
3029     Vals64.clear();
3030     return;
3031   }
3032 
3033   case Instruction::LandingPad: {
3034     const LandingPadInst &LP = cast<LandingPadInst>(I);
3035     Code = bitc::FUNC_CODE_INST_LANDINGPAD;
3036     Vals.push_back(VE.getTypeID(LP.getType()));
3037     Vals.push_back(LP.isCleanup());
3038     Vals.push_back(LP.getNumClauses());
3039     for (unsigned I = 0, E = LP.getNumClauses(); I != E; ++I) {
3040       if (LP.isCatch(I))
3041         Vals.push_back(LandingPadInst::Catch);
3042       else
3043         Vals.push_back(LandingPadInst::Filter);
3044       pushValueAndType(LP.getClause(I), InstID, Vals);
3045     }
3046     break;
3047   }
3048 
3049   case Instruction::Alloca: {
3050     Code = bitc::FUNC_CODE_INST_ALLOCA;
3051     const AllocaInst &AI = cast<AllocaInst>(I);
3052     Vals.push_back(VE.getTypeID(AI.getAllocatedType()));
3053     Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
3054     Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
3055     using APV = AllocaPackedValues;
3056     unsigned Record = 0;
3057     unsigned EncodedAlign = getEncodedAlign(AI.getAlign());
3058     Bitfield::set<APV::AlignLower>(
3059         Record, EncodedAlign & ((1 << APV::AlignLower::Bits) - 1));
3060     Bitfield::set<APV::AlignUpper>(Record,
3061                                    EncodedAlign >> APV::AlignLower::Bits);
3062     Bitfield::set<APV::UsedWithInAlloca>(Record, AI.isUsedWithInAlloca());
3063     Bitfield::set<APV::ExplicitType>(Record, true);
3064     Bitfield::set<APV::SwiftError>(Record, AI.isSwiftError());
3065     Vals.push_back(Record);
3066     break;
3067   }
3068 
3069   case Instruction::Load:
3070     if (cast<LoadInst>(I).isAtomic()) {
3071       Code = bitc::FUNC_CODE_INST_LOADATOMIC;
3072       pushValueAndType(I.getOperand(0), InstID, Vals);
3073     } else {
3074       Code = bitc::FUNC_CODE_INST_LOAD;
3075       if (!pushValueAndType(I.getOperand(0), InstID, Vals)) // ptr
3076         AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
3077     }
3078     Vals.push_back(VE.getTypeID(I.getType()));
3079     Vals.push_back(getEncodedAlign(cast<LoadInst>(I).getAlign()));
3080     Vals.push_back(cast<LoadInst>(I).isVolatile());
3081     if (cast<LoadInst>(I).isAtomic()) {
3082       Vals.push_back(getEncodedOrdering(cast<LoadInst>(I).getOrdering()));
3083       Vals.push_back(getEncodedSyncScopeID(cast<LoadInst>(I).getSyncScopeID()));
3084     }
3085     break;
3086   case Instruction::Store:
3087     if (cast<StoreInst>(I).isAtomic())
3088       Code = bitc::FUNC_CODE_INST_STOREATOMIC;
3089     else
3090       Code = bitc::FUNC_CODE_INST_STORE;
3091     pushValueAndType(I.getOperand(1), InstID, Vals); // ptrty + ptr
3092     pushValueAndType(I.getOperand(0), InstID, Vals); // valty + val
3093     Vals.push_back(getEncodedAlign(cast<StoreInst>(I).getAlign()));
3094     Vals.push_back(cast<StoreInst>(I).isVolatile());
3095     if (cast<StoreInst>(I).isAtomic()) {
3096       Vals.push_back(getEncodedOrdering(cast<StoreInst>(I).getOrdering()));
3097       Vals.push_back(
3098           getEncodedSyncScopeID(cast<StoreInst>(I).getSyncScopeID()));
3099     }
3100     break;
3101   case Instruction::AtomicCmpXchg:
3102     Code = bitc::FUNC_CODE_INST_CMPXCHG;
3103     pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr
3104     pushValueAndType(I.getOperand(1), InstID, Vals); // cmp.
3105     pushValue(I.getOperand(2), InstID, Vals);        // newval.
3106     Vals.push_back(cast<AtomicCmpXchgInst>(I).isVolatile());
3107     Vals.push_back(
3108         getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getSuccessOrdering()));
3109     Vals.push_back(
3110         getEncodedSyncScopeID(cast<AtomicCmpXchgInst>(I).getSyncScopeID()));
3111     Vals.push_back(
3112         getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getFailureOrdering()));
3113     Vals.push_back(cast<AtomicCmpXchgInst>(I).isWeak());
3114     Vals.push_back(getEncodedAlign(cast<AtomicCmpXchgInst>(I).getAlign()));
3115     break;
3116   case Instruction::AtomicRMW:
3117     Code = bitc::FUNC_CODE_INST_ATOMICRMW;
3118     pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr
3119     pushValueAndType(I.getOperand(1), InstID, Vals); // valty + val
3120     Vals.push_back(
3121         getEncodedRMWOperation(cast<AtomicRMWInst>(I).getOperation()));
3122     Vals.push_back(cast<AtomicRMWInst>(I).isVolatile());
3123     Vals.push_back(getEncodedOrdering(cast<AtomicRMWInst>(I).getOrdering()));
3124     Vals.push_back(
3125         getEncodedSyncScopeID(cast<AtomicRMWInst>(I).getSyncScopeID()));
3126     Vals.push_back(getEncodedAlign(cast<AtomicRMWInst>(I).getAlign()));
3127     break;
3128   case Instruction::Fence:
3129     Code = bitc::FUNC_CODE_INST_FENCE;
3130     Vals.push_back(getEncodedOrdering(cast<FenceInst>(I).getOrdering()));
3131     Vals.push_back(getEncodedSyncScopeID(cast<FenceInst>(I).getSyncScopeID()));
3132     break;
3133   case Instruction::Call: {
3134     const CallInst &CI = cast<CallInst>(I);
3135     FunctionType *FTy = CI.getFunctionType();
3136 
3137     if (CI.hasOperandBundles())
3138       writeOperandBundles(CI, InstID);
3139 
3140     Code = bitc::FUNC_CODE_INST_CALL;
3141 
3142     Vals.push_back(VE.getAttributeListID(CI.getAttributes()));
3143 
3144     unsigned Flags = getOptimizationFlags(&I);
3145     Vals.push_back(CI.getCallingConv() << bitc::CALL_CCONV |
3146                    unsigned(CI.isTailCall()) << bitc::CALL_TAIL |
3147                    unsigned(CI.isMustTailCall()) << bitc::CALL_MUSTTAIL |
3148                    1 << bitc::CALL_EXPLICIT_TYPE |
3149                    unsigned(CI.isNoTailCall()) << bitc::CALL_NOTAIL |
3150                    unsigned(Flags != 0) << bitc::CALL_FMF);
3151     if (Flags != 0)
3152       Vals.push_back(Flags);
3153 
3154     Vals.push_back(VE.getTypeID(FTy));
3155     pushValueAndType(CI.getCalledOperand(), InstID, Vals); // Callee
3156 
3157     // Emit value #'s for the fixed parameters.
3158     for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
3159       // Check for labels (can happen with asm labels).
3160       if (FTy->getParamType(i)->isLabelTy())
3161         Vals.push_back(VE.getValueID(CI.getArgOperand(i)));
3162       else
3163         pushValue(CI.getArgOperand(i), InstID, Vals); // fixed param.
3164     }
3165 
3166     // Emit type/value pairs for varargs params.
3167     if (FTy->isVarArg()) {
3168       for (unsigned i = FTy->getNumParams(), e = CI.arg_size(); i != e; ++i)
3169         pushValueAndType(CI.getArgOperand(i), InstID, Vals); // varargs
3170     }
3171     break;
3172   }
3173   case Instruction::VAArg:
3174     Code = bitc::FUNC_CODE_INST_VAARG;
3175     Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));   // valistty
3176     pushValue(I.getOperand(0), InstID, Vals);                   // valist.
3177     Vals.push_back(VE.getTypeID(I.getType())); // restype.
3178     break;
3179   case Instruction::Freeze:
3180     Code = bitc::FUNC_CODE_INST_FREEZE;
3181     pushValueAndType(I.getOperand(0), InstID, Vals);
3182     break;
3183   }
3184 
3185   Stream.EmitRecord(Code, Vals, AbbrevToUse);
3186   Vals.clear();
3187 }
3188 
3189 /// Write a GlobalValue VST to the module. The purpose of this data structure is
3190 /// to allow clients to efficiently find the function body.
3191 void ModuleBitcodeWriter::writeGlobalValueSymbolTable(
3192   DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) {
3193   // Get the offset of the VST we are writing, and backpatch it into
3194   // the VST forward declaration record.
3195   uint64_t VSTOffset = Stream.GetCurrentBitNo();
3196   // The BitcodeStartBit was the stream offset of the identification block.
3197   VSTOffset -= bitcodeStartBit();
3198   assert((VSTOffset & 31) == 0 && "VST block not 32-bit aligned");
3199   // Note that we add 1 here because the offset is relative to one word
3200   // before the start of the identification block, which was historically
3201   // always the start of the regular bitcode header.
3202   Stream.BackpatchWord(VSTOffsetPlaceholder, VSTOffset / 32 + 1);
3203 
3204   Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
3205 
3206   auto Abbv = std::make_shared<BitCodeAbbrev>();
3207   Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_FNENTRY));
3208   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
3209   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // funcoffset
3210   unsigned FnEntryAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3211 
3212   for (const Function &F : M) {
3213     uint64_t Record[2];
3214 
3215     if (F.isDeclaration())
3216       continue;
3217 
3218     Record[0] = VE.getValueID(&F);
3219 
3220     // Save the word offset of the function (from the start of the
3221     // actual bitcode written to the stream).
3222     uint64_t BitcodeIndex = FunctionToBitcodeIndex[&F] - bitcodeStartBit();
3223     assert((BitcodeIndex & 31) == 0 && "function block not 32-bit aligned");
3224     // Note that we add 1 here because the offset is relative to one word
3225     // before the start of the identification block, which was historically
3226     // always the start of the regular bitcode header.
3227     Record[1] = BitcodeIndex / 32 + 1;
3228 
3229     Stream.EmitRecord(bitc::VST_CODE_FNENTRY, Record, FnEntryAbbrev);
3230   }
3231 
3232   Stream.ExitBlock();
3233 }
3234 
3235 /// Emit names for arguments, instructions and basic blocks in a function.
3236 void ModuleBitcodeWriter::writeFunctionLevelValueSymbolTable(
3237     const ValueSymbolTable &VST) {
3238   if (VST.empty())
3239     return;
3240 
3241   Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
3242 
3243   // FIXME: Set up the abbrev, we know how many values there are!
3244   // FIXME: We know if the type names can use 7-bit ascii.
3245   SmallVector<uint64_t, 64> NameVals;
3246 
3247   for (const ValueName &Name : VST) {
3248     // Figure out the encoding to use for the name.
3249     StringEncoding Bits = getStringEncoding(Name.getKey());
3250 
3251     unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
3252     NameVals.push_back(VE.getValueID(Name.getValue()));
3253 
3254     // VST_CODE_ENTRY:   [valueid, namechar x N]
3255     // VST_CODE_BBENTRY: [bbid, namechar x N]
3256     unsigned Code;
3257     if (isa<BasicBlock>(Name.getValue())) {
3258       Code = bitc::VST_CODE_BBENTRY;
3259       if (Bits == SE_Char6)
3260         AbbrevToUse = VST_BBENTRY_6_ABBREV;
3261     } else {
3262       Code = bitc::VST_CODE_ENTRY;
3263       if (Bits == SE_Char6)
3264         AbbrevToUse = VST_ENTRY_6_ABBREV;
3265       else if (Bits == SE_Fixed7)
3266         AbbrevToUse = VST_ENTRY_7_ABBREV;
3267     }
3268 
3269     for (const auto P : Name.getKey())
3270       NameVals.push_back((unsigned char)P);
3271 
3272     // Emit the finished record.
3273     Stream.EmitRecord(Code, NameVals, AbbrevToUse);
3274     NameVals.clear();
3275   }
3276 
3277   Stream.ExitBlock();
3278 }
3279 
3280 void ModuleBitcodeWriter::writeUseList(UseListOrder &&Order) {
3281   assert(Order.Shuffle.size() >= 2 && "Shuffle too small");
3282   unsigned Code;
3283   if (isa<BasicBlock>(Order.V))
3284     Code = bitc::USELIST_CODE_BB;
3285   else
3286     Code = bitc::USELIST_CODE_DEFAULT;
3287 
3288   SmallVector<uint64_t, 64> Record(Order.Shuffle.begin(), Order.Shuffle.end());
3289   Record.push_back(VE.getValueID(Order.V));
3290   Stream.EmitRecord(Code, Record);
3291 }
3292 
3293 void ModuleBitcodeWriter::writeUseListBlock(const Function *F) {
3294   assert(VE.shouldPreserveUseListOrder() &&
3295          "Expected to be preserving use-list order");
3296 
3297   auto hasMore = [&]() {
3298     return !VE.UseListOrders.empty() && VE.UseListOrders.back().F == F;
3299   };
3300   if (!hasMore())
3301     // Nothing to do.
3302     return;
3303 
3304   Stream.EnterSubblock(bitc::USELIST_BLOCK_ID, 3);
3305   while (hasMore()) {
3306     writeUseList(std::move(VE.UseListOrders.back()));
3307     VE.UseListOrders.pop_back();
3308   }
3309   Stream.ExitBlock();
3310 }
3311 
3312 /// Emit a function body to the module stream.
3313 void ModuleBitcodeWriter::writeFunction(
3314     const Function &F,
3315     DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) {
3316   // Save the bitcode index of the start of this function block for recording
3317   // in the VST.
3318   FunctionToBitcodeIndex[&F] = Stream.GetCurrentBitNo();
3319 
3320   Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 4);
3321   VE.incorporateFunction(F);
3322 
3323   SmallVector<unsigned, 64> Vals;
3324 
3325   // Emit the number of basic blocks, so the reader can create them ahead of
3326   // time.
3327   Vals.push_back(VE.getBasicBlocks().size());
3328   Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals);
3329   Vals.clear();
3330 
3331   // If there are function-local constants, emit them now.
3332   unsigned CstStart, CstEnd;
3333   VE.getFunctionConstantRange(CstStart, CstEnd);
3334   writeConstants(CstStart, CstEnd, false);
3335 
3336   // If there is function-local metadata, emit it now.
3337   writeFunctionMetadata(F);
3338 
3339   // Keep a running idea of what the instruction ID is.
3340   unsigned InstID = CstEnd;
3341 
3342   bool NeedsMetadataAttachment = F.hasMetadata();
3343 
3344   DILocation *LastDL = nullptr;
3345   // Finally, emit all the instructions, in order.
3346   for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
3347     for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
3348          I != E; ++I) {
3349       writeInstruction(*I, InstID, Vals);
3350 
3351       if (!I->getType()->isVoidTy())
3352         ++InstID;
3353 
3354       // If the instruction has metadata, write a metadata attachment later.
3355       NeedsMetadataAttachment |= I->hasMetadataOtherThanDebugLoc();
3356 
3357       // If the instruction has a debug location, emit it.
3358       DILocation *DL = I->getDebugLoc();
3359       if (!DL)
3360         continue;
3361 
3362       if (DL == LastDL) {
3363         // Just repeat the same debug loc as last time.
3364         Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC_AGAIN, Vals);
3365         continue;
3366       }
3367 
3368       Vals.push_back(DL->getLine());
3369       Vals.push_back(DL->getColumn());
3370       Vals.push_back(VE.getMetadataOrNullID(DL->getScope()));
3371       Vals.push_back(VE.getMetadataOrNullID(DL->getInlinedAt()));
3372       Vals.push_back(DL->isImplicitCode());
3373       Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC, Vals);
3374       Vals.clear();
3375 
3376       LastDL = DL;
3377     }
3378 
3379   // Emit names for all the instructions etc.
3380   if (auto *Symtab = F.getValueSymbolTable())
3381     writeFunctionLevelValueSymbolTable(*Symtab);
3382 
3383   if (NeedsMetadataAttachment)
3384     writeFunctionMetadataAttachment(F);
3385   if (VE.shouldPreserveUseListOrder())
3386     writeUseListBlock(&F);
3387   VE.purgeFunction();
3388   Stream.ExitBlock();
3389 }
3390 
3391 // Emit blockinfo, which defines the standard abbreviations etc.
3392 void ModuleBitcodeWriter::writeBlockInfo() {
3393   // We only want to emit block info records for blocks that have multiple
3394   // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK.
3395   // Other blocks can define their abbrevs inline.
3396   Stream.EnterBlockInfoBlock();
3397 
3398   { // 8-bit fixed-width VST_CODE_ENTRY/VST_CODE_BBENTRY strings.
3399     auto Abbv = std::make_shared<BitCodeAbbrev>();
3400     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3));
3401     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3402     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3403     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
3404     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
3405         VST_ENTRY_8_ABBREV)
3406       llvm_unreachable("Unexpected abbrev ordering!");
3407   }
3408 
3409   { // 7-bit fixed width VST_CODE_ENTRY strings.
3410     auto Abbv = std::make_shared<BitCodeAbbrev>();
3411     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
3412     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3413     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3414     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
3415     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
3416         VST_ENTRY_7_ABBREV)
3417       llvm_unreachable("Unexpected abbrev ordering!");
3418   }
3419   { // 6-bit char6 VST_CODE_ENTRY strings.
3420     auto Abbv = std::make_shared<BitCodeAbbrev>();
3421     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
3422     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3423     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3424     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
3425     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
3426         VST_ENTRY_6_ABBREV)
3427       llvm_unreachable("Unexpected abbrev ordering!");
3428   }
3429   { // 6-bit char6 VST_CODE_BBENTRY strings.
3430     auto Abbv = std::make_shared<BitCodeAbbrev>();
3431     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY));
3432     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3433     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3434     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
3435     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
3436         VST_BBENTRY_6_ABBREV)
3437       llvm_unreachable("Unexpected abbrev ordering!");
3438   }
3439 
3440   { // SETTYPE abbrev for CONSTANTS_BLOCK.
3441     auto Abbv = std::make_shared<BitCodeAbbrev>();
3442     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_SETTYPE));
3443     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
3444                               VE.computeBitsRequiredForTypeIndicies()));
3445     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
3446         CONSTANTS_SETTYPE_ABBREV)
3447       llvm_unreachable("Unexpected abbrev ordering!");
3448   }
3449 
3450   { // INTEGER abbrev for CONSTANTS_BLOCK.
3451     auto Abbv = std::make_shared<BitCodeAbbrev>();
3452     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_INTEGER));
3453     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3454     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
3455         CONSTANTS_INTEGER_ABBREV)
3456       llvm_unreachable("Unexpected abbrev ordering!");
3457   }
3458 
3459   { // CE_CAST abbrev for CONSTANTS_BLOCK.
3460     auto Abbv = std::make_shared<BitCodeAbbrev>();
3461     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CE_CAST));
3462     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4));  // cast opc
3463     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,       // typeid
3464                               VE.computeBitsRequiredForTypeIndicies()));
3465     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));    // value id
3466 
3467     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
3468         CONSTANTS_CE_CAST_Abbrev)
3469       llvm_unreachable("Unexpected abbrev ordering!");
3470   }
3471   { // NULL abbrev for CONSTANTS_BLOCK.
3472     auto Abbv = std::make_shared<BitCodeAbbrev>();
3473     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_NULL));
3474     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
3475         CONSTANTS_NULL_Abbrev)
3476       llvm_unreachable("Unexpected abbrev ordering!");
3477   }
3478 
3479   // FIXME: This should only use space for first class types!
3480 
3481   { // INST_LOAD abbrev for FUNCTION_BLOCK.
3482     auto Abbv = std::make_shared<BitCodeAbbrev>();
3483     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_LOAD));
3484     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Ptr
3485     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,    // dest ty
3486                               VE.computeBitsRequiredForTypeIndicies()));
3487     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align
3488     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile
3489     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3490         FUNCTION_INST_LOAD_ABBREV)
3491       llvm_unreachable("Unexpected abbrev ordering!");
3492   }
3493   { // INST_UNOP abbrev for FUNCTION_BLOCK.
3494     auto Abbv = std::make_shared<BitCodeAbbrev>();
3495     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNOP));
3496     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
3497     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3498     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3499         FUNCTION_INST_UNOP_ABBREV)
3500       llvm_unreachable("Unexpected abbrev ordering!");
3501   }
3502   { // INST_UNOP_FLAGS abbrev for FUNCTION_BLOCK.
3503     auto Abbv = std::make_shared<BitCodeAbbrev>();
3504     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNOP));
3505     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
3506     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3507     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); // flags
3508     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3509         FUNCTION_INST_UNOP_FLAGS_ABBREV)
3510       llvm_unreachable("Unexpected abbrev ordering!");
3511   }
3512   { // INST_BINOP abbrev for FUNCTION_BLOCK.
3513     auto Abbv = std::make_shared<BitCodeAbbrev>();
3514     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
3515     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
3516     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
3517     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3518     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3519         FUNCTION_INST_BINOP_ABBREV)
3520       llvm_unreachable("Unexpected abbrev ordering!");
3521   }
3522   { // INST_BINOP_FLAGS abbrev for FUNCTION_BLOCK.
3523     auto Abbv = std::make_shared<BitCodeAbbrev>();
3524     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
3525     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
3526     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
3527     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3528     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); // flags
3529     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3530         FUNCTION_INST_BINOP_FLAGS_ABBREV)
3531       llvm_unreachable("Unexpected abbrev ordering!");
3532   }
3533   { // INST_CAST abbrev for FUNCTION_BLOCK.
3534     auto Abbv = std::make_shared<BitCodeAbbrev>();
3535     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST));
3536     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));    // OpVal
3537     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,       // dest ty
3538                               VE.computeBitsRequiredForTypeIndicies()));
3539     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4));  // opc
3540     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3541         FUNCTION_INST_CAST_ABBREV)
3542       llvm_unreachable("Unexpected abbrev ordering!");
3543   }
3544 
3545   { // INST_RET abbrev for FUNCTION_BLOCK.
3546     auto Abbv = std::make_shared<BitCodeAbbrev>();
3547     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
3548     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3549         FUNCTION_INST_RET_VOID_ABBREV)
3550       llvm_unreachable("Unexpected abbrev ordering!");
3551   }
3552   { // INST_RET abbrev for FUNCTION_BLOCK.
3553     auto Abbv = std::make_shared<BitCodeAbbrev>();
3554     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
3555     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ValID
3556     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3557         FUNCTION_INST_RET_VAL_ABBREV)
3558       llvm_unreachable("Unexpected abbrev ordering!");
3559   }
3560   { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK.
3561     auto Abbv = std::make_shared<BitCodeAbbrev>();
3562     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNREACHABLE));
3563     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3564         FUNCTION_INST_UNREACHABLE_ABBREV)
3565       llvm_unreachable("Unexpected abbrev ordering!");
3566   }
3567   {
3568     auto Abbv = std::make_shared<BitCodeAbbrev>();
3569     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_GEP));
3570     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
3571     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
3572                               Log2_32_Ceil(VE.getTypes().size() + 1)));
3573     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3574     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
3575     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3576         FUNCTION_INST_GEP_ABBREV)
3577       llvm_unreachable("Unexpected abbrev ordering!");
3578   }
3579 
3580   Stream.ExitBlock();
3581 }
3582 
3583 /// Write the module path strings, currently only used when generating
3584 /// a combined index file.
3585 void IndexBitcodeWriter::writeModStrings() {
3586   Stream.EnterSubblock(bitc::MODULE_STRTAB_BLOCK_ID, 3);
3587 
3588   // TODO: See which abbrev sizes we actually need to emit
3589 
3590   // 8-bit fixed-width MST_ENTRY strings.
3591   auto Abbv = std::make_shared<BitCodeAbbrev>();
3592   Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
3593   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3594   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3595   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
3596   unsigned Abbrev8Bit = Stream.EmitAbbrev(std::move(Abbv));
3597 
3598   // 7-bit fixed width MST_ENTRY strings.
3599   Abbv = std::make_shared<BitCodeAbbrev>();
3600   Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
3601   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3602   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3603   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
3604   unsigned Abbrev7Bit = Stream.EmitAbbrev(std::move(Abbv));
3605 
3606   // 6-bit char6 MST_ENTRY strings.
3607   Abbv = std::make_shared<BitCodeAbbrev>();
3608   Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
3609   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3610   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3611   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
3612   unsigned Abbrev6Bit = Stream.EmitAbbrev(std::move(Abbv));
3613 
3614   // Module Hash, 160 bits SHA1. Optionally, emitted after each MST_CODE_ENTRY.
3615   Abbv = std::make_shared<BitCodeAbbrev>();
3616   Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_HASH));
3617   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3618   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3619   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3620   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3621   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3622   unsigned AbbrevHash = Stream.EmitAbbrev(std::move(Abbv));
3623 
3624   SmallVector<unsigned, 64> Vals;
3625   forEachModule(
3626       [&](const StringMapEntry<std::pair<uint64_t, ModuleHash>> &MPSE) {
3627         StringRef Key = MPSE.getKey();
3628         const auto &Value = MPSE.getValue();
3629         StringEncoding Bits = getStringEncoding(Key);
3630         unsigned AbbrevToUse = Abbrev8Bit;
3631         if (Bits == SE_Char6)
3632           AbbrevToUse = Abbrev6Bit;
3633         else if (Bits == SE_Fixed7)
3634           AbbrevToUse = Abbrev7Bit;
3635 
3636         Vals.push_back(Value.first);
3637         Vals.append(Key.begin(), Key.end());
3638 
3639         // Emit the finished record.
3640         Stream.EmitRecord(bitc::MST_CODE_ENTRY, Vals, AbbrevToUse);
3641 
3642         // Emit an optional hash for the module now
3643         const auto &Hash = Value.second;
3644         if (llvm::any_of(Hash, [](uint32_t H) { return H; })) {
3645           Vals.assign(Hash.begin(), Hash.end());
3646           // Emit the hash record.
3647           Stream.EmitRecord(bitc::MST_CODE_HASH, Vals, AbbrevHash);
3648         }
3649 
3650         Vals.clear();
3651       });
3652   Stream.ExitBlock();
3653 }
3654 
3655 /// Write the function type metadata related records that need to appear before
3656 /// a function summary entry (whether per-module or combined).
3657 template <typename Fn>
3658 static void writeFunctionTypeMetadataRecords(BitstreamWriter &Stream,
3659                                              FunctionSummary *FS,
3660                                              Fn GetValueID) {
3661   if (!FS->type_tests().empty())
3662     Stream.EmitRecord(bitc::FS_TYPE_TESTS, FS->type_tests());
3663 
3664   SmallVector<uint64_t, 64> Record;
3665 
3666   auto WriteVFuncIdVec = [&](uint64_t Ty,
3667                              ArrayRef<FunctionSummary::VFuncId> VFs) {
3668     if (VFs.empty())
3669       return;
3670     Record.clear();
3671     for (auto &VF : VFs) {
3672       Record.push_back(VF.GUID);
3673       Record.push_back(VF.Offset);
3674     }
3675     Stream.EmitRecord(Ty, Record);
3676   };
3677 
3678   WriteVFuncIdVec(bitc::FS_TYPE_TEST_ASSUME_VCALLS,
3679                   FS->type_test_assume_vcalls());
3680   WriteVFuncIdVec(bitc::FS_TYPE_CHECKED_LOAD_VCALLS,
3681                   FS->type_checked_load_vcalls());
3682 
3683   auto WriteConstVCallVec = [&](uint64_t Ty,
3684                                 ArrayRef<FunctionSummary::ConstVCall> VCs) {
3685     for (auto &VC : VCs) {
3686       Record.clear();
3687       Record.push_back(VC.VFunc.GUID);
3688       Record.push_back(VC.VFunc.Offset);
3689       llvm::append_range(Record, VC.Args);
3690       Stream.EmitRecord(Ty, Record);
3691     }
3692   };
3693 
3694   WriteConstVCallVec(bitc::FS_TYPE_TEST_ASSUME_CONST_VCALL,
3695                      FS->type_test_assume_const_vcalls());
3696   WriteConstVCallVec(bitc::FS_TYPE_CHECKED_LOAD_CONST_VCALL,
3697                      FS->type_checked_load_const_vcalls());
3698 
3699   auto WriteRange = [&](ConstantRange Range) {
3700     Range = Range.sextOrTrunc(FunctionSummary::ParamAccess::RangeWidth);
3701     assert(Range.getLower().getNumWords() == 1);
3702     assert(Range.getUpper().getNumWords() == 1);
3703     emitSignedInt64(Record, *Range.getLower().getRawData());
3704     emitSignedInt64(Record, *Range.getUpper().getRawData());
3705   };
3706 
3707   if (!FS->paramAccesses().empty()) {
3708     Record.clear();
3709     for (auto &Arg : FS->paramAccesses()) {
3710       size_t UndoSize = Record.size();
3711       Record.push_back(Arg.ParamNo);
3712       WriteRange(Arg.Use);
3713       Record.push_back(Arg.Calls.size());
3714       for (auto &Call : Arg.Calls) {
3715         Record.push_back(Call.ParamNo);
3716         Optional<unsigned> ValueID = GetValueID(Call.Callee);
3717         if (!ValueID) {
3718           // If ValueID is unknown we can't drop just this call, we must drop
3719           // entire parameter.
3720           Record.resize(UndoSize);
3721           break;
3722         }
3723         Record.push_back(*ValueID);
3724         WriteRange(Call.Offsets);
3725       }
3726     }
3727     if (!Record.empty())
3728       Stream.EmitRecord(bitc::FS_PARAM_ACCESS, Record);
3729   }
3730 }
3731 
3732 /// Collect type IDs from type tests used by function.
3733 static void
3734 getReferencedTypeIds(FunctionSummary *FS,
3735                      std::set<GlobalValue::GUID> &ReferencedTypeIds) {
3736   if (!FS->type_tests().empty())
3737     for (auto &TT : FS->type_tests())
3738       ReferencedTypeIds.insert(TT);
3739 
3740   auto GetReferencedTypesFromVFuncIdVec =
3741       [&](ArrayRef<FunctionSummary::VFuncId> VFs) {
3742         for (auto &VF : VFs)
3743           ReferencedTypeIds.insert(VF.GUID);
3744       };
3745 
3746   GetReferencedTypesFromVFuncIdVec(FS->type_test_assume_vcalls());
3747   GetReferencedTypesFromVFuncIdVec(FS->type_checked_load_vcalls());
3748 
3749   auto GetReferencedTypesFromConstVCallVec =
3750       [&](ArrayRef<FunctionSummary::ConstVCall> VCs) {
3751         for (auto &VC : VCs)
3752           ReferencedTypeIds.insert(VC.VFunc.GUID);
3753       };
3754 
3755   GetReferencedTypesFromConstVCallVec(FS->type_test_assume_const_vcalls());
3756   GetReferencedTypesFromConstVCallVec(FS->type_checked_load_const_vcalls());
3757 }
3758 
3759 static void writeWholeProgramDevirtResolutionByArg(
3760     SmallVector<uint64_t, 64> &NameVals, const std::vector<uint64_t> &args,
3761     const WholeProgramDevirtResolution::ByArg &ByArg) {
3762   NameVals.push_back(args.size());
3763   llvm::append_range(NameVals, args);
3764 
3765   NameVals.push_back(ByArg.TheKind);
3766   NameVals.push_back(ByArg.Info);
3767   NameVals.push_back(ByArg.Byte);
3768   NameVals.push_back(ByArg.Bit);
3769 }
3770 
3771 static void writeWholeProgramDevirtResolution(
3772     SmallVector<uint64_t, 64> &NameVals, StringTableBuilder &StrtabBuilder,
3773     uint64_t Id, const WholeProgramDevirtResolution &Wpd) {
3774   NameVals.push_back(Id);
3775 
3776   NameVals.push_back(Wpd.TheKind);
3777   NameVals.push_back(StrtabBuilder.add(Wpd.SingleImplName));
3778   NameVals.push_back(Wpd.SingleImplName.size());
3779 
3780   NameVals.push_back(Wpd.ResByArg.size());
3781   for (auto &A : Wpd.ResByArg)
3782     writeWholeProgramDevirtResolutionByArg(NameVals, A.first, A.second);
3783 }
3784 
3785 static void writeTypeIdSummaryRecord(SmallVector<uint64_t, 64> &NameVals,
3786                                      StringTableBuilder &StrtabBuilder,
3787                                      const std::string &Id,
3788                                      const TypeIdSummary &Summary) {
3789   NameVals.push_back(StrtabBuilder.add(Id));
3790   NameVals.push_back(Id.size());
3791 
3792   NameVals.push_back(Summary.TTRes.TheKind);
3793   NameVals.push_back(Summary.TTRes.SizeM1BitWidth);
3794   NameVals.push_back(Summary.TTRes.AlignLog2);
3795   NameVals.push_back(Summary.TTRes.SizeM1);
3796   NameVals.push_back(Summary.TTRes.BitMask);
3797   NameVals.push_back(Summary.TTRes.InlineBits);
3798 
3799   for (auto &W : Summary.WPDRes)
3800     writeWholeProgramDevirtResolution(NameVals, StrtabBuilder, W.first,
3801                                       W.second);
3802 }
3803 
3804 static void writeTypeIdCompatibleVtableSummaryRecord(
3805     SmallVector<uint64_t, 64> &NameVals, StringTableBuilder &StrtabBuilder,
3806     const std::string &Id, const TypeIdCompatibleVtableInfo &Summary,
3807     ValueEnumerator &VE) {
3808   NameVals.push_back(StrtabBuilder.add(Id));
3809   NameVals.push_back(Id.size());
3810 
3811   for (auto &P : Summary) {
3812     NameVals.push_back(P.AddressPointOffset);
3813     NameVals.push_back(VE.getValueID(P.VTableVI.getValue()));
3814   }
3815 }
3816 
3817 // Helper to emit a single function summary record.
3818 void ModuleBitcodeWriterBase::writePerModuleFunctionSummaryRecord(
3819     SmallVector<uint64_t, 64> &NameVals, GlobalValueSummary *Summary,
3820     unsigned ValueID, unsigned FSCallsAbbrev, unsigned FSCallsProfileAbbrev,
3821     const Function &F) {
3822   NameVals.push_back(ValueID);
3823 
3824   FunctionSummary *FS = cast<FunctionSummary>(Summary);
3825 
3826   writeFunctionTypeMetadataRecords(
3827       Stream, FS, [&](const ValueInfo &VI) -> Optional<unsigned> {
3828         return {VE.getValueID(VI.getValue())};
3829       });
3830 
3831   auto SpecialRefCnts = FS->specialRefCounts();
3832   NameVals.push_back(getEncodedGVSummaryFlags(FS->flags()));
3833   NameVals.push_back(FS->instCount());
3834   NameVals.push_back(getEncodedFFlags(FS->fflags()));
3835   NameVals.push_back(FS->refs().size());
3836   NameVals.push_back(SpecialRefCnts.first);  // rorefcnt
3837   NameVals.push_back(SpecialRefCnts.second); // worefcnt
3838 
3839   for (auto &RI : FS->refs())
3840     NameVals.push_back(VE.getValueID(RI.getValue()));
3841 
3842   bool HasProfileData =
3843       F.hasProfileData() || ForceSummaryEdgesCold != FunctionSummary::FSHT_None;
3844   for (auto &ECI : FS->calls()) {
3845     NameVals.push_back(getValueId(ECI.first));
3846     if (HasProfileData)
3847       NameVals.push_back(static_cast<uint8_t>(ECI.second.Hotness));
3848     else if (WriteRelBFToSummary)
3849       NameVals.push_back(ECI.second.RelBlockFreq);
3850   }
3851 
3852   unsigned FSAbbrev = (HasProfileData ? FSCallsProfileAbbrev : FSCallsAbbrev);
3853   unsigned Code =
3854       (HasProfileData ? bitc::FS_PERMODULE_PROFILE
3855                       : (WriteRelBFToSummary ? bitc::FS_PERMODULE_RELBF
3856                                              : bitc::FS_PERMODULE));
3857 
3858   // Emit the finished record.
3859   Stream.EmitRecord(Code, NameVals, FSAbbrev);
3860   NameVals.clear();
3861 }
3862 
3863 // Collect the global value references in the given variable's initializer,
3864 // and emit them in a summary record.
3865 void ModuleBitcodeWriterBase::writeModuleLevelReferences(
3866     const GlobalVariable &V, SmallVector<uint64_t, 64> &NameVals,
3867     unsigned FSModRefsAbbrev, unsigned FSModVTableRefsAbbrev) {
3868   auto VI = Index->getValueInfo(V.getGUID());
3869   if (!VI || VI.getSummaryList().empty()) {
3870     // Only declarations should not have a summary (a declaration might however
3871     // have a summary if the def was in module level asm).
3872     assert(V.isDeclaration());
3873     return;
3874   }
3875   auto *Summary = VI.getSummaryList()[0].get();
3876   NameVals.push_back(VE.getValueID(&V));
3877   GlobalVarSummary *VS = cast<GlobalVarSummary>(Summary);
3878   NameVals.push_back(getEncodedGVSummaryFlags(VS->flags()));
3879   NameVals.push_back(getEncodedGVarFlags(VS->varflags()));
3880 
3881   auto VTableFuncs = VS->vTableFuncs();
3882   if (!VTableFuncs.empty())
3883     NameVals.push_back(VS->refs().size());
3884 
3885   unsigned SizeBeforeRefs = NameVals.size();
3886   for (auto &RI : VS->refs())
3887     NameVals.push_back(VE.getValueID(RI.getValue()));
3888   // Sort the refs for determinism output, the vector returned by FS->refs() has
3889   // been initialized from a DenseSet.
3890   llvm::sort(drop_begin(NameVals, SizeBeforeRefs));
3891 
3892   if (VTableFuncs.empty())
3893     Stream.EmitRecord(bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS, NameVals,
3894                       FSModRefsAbbrev);
3895   else {
3896     // VTableFuncs pairs should already be sorted by offset.
3897     for (auto &P : VTableFuncs) {
3898       NameVals.push_back(VE.getValueID(P.FuncVI.getValue()));
3899       NameVals.push_back(P.VTableOffset);
3900     }
3901 
3902     Stream.EmitRecord(bitc::FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS, NameVals,
3903                       FSModVTableRefsAbbrev);
3904   }
3905   NameVals.clear();
3906 }
3907 
3908 /// Emit the per-module summary section alongside the rest of
3909 /// the module's bitcode.
3910 void ModuleBitcodeWriterBase::writePerModuleGlobalValueSummary() {
3911   // By default we compile with ThinLTO if the module has a summary, but the
3912   // client can request full LTO with a module flag.
3913   bool IsThinLTO = true;
3914   if (auto *MD =
3915           mdconst::extract_or_null<ConstantInt>(M.getModuleFlag("ThinLTO")))
3916     IsThinLTO = MD->getZExtValue();
3917   Stream.EnterSubblock(IsThinLTO ? bitc::GLOBALVAL_SUMMARY_BLOCK_ID
3918                                  : bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID,
3919                        4);
3920 
3921   Stream.EmitRecord(
3922       bitc::FS_VERSION,
3923       ArrayRef<uint64_t>{ModuleSummaryIndex::BitcodeSummaryVersion});
3924 
3925   // Write the index flags.
3926   uint64_t Flags = 0;
3927   // Bits 1-3 are set only in the combined index, skip them.
3928   if (Index->enableSplitLTOUnit())
3929     Flags |= 0x8;
3930   Stream.EmitRecord(bitc::FS_FLAGS, ArrayRef<uint64_t>{Flags});
3931 
3932   if (Index->begin() == Index->end()) {
3933     Stream.ExitBlock();
3934     return;
3935   }
3936 
3937   for (const auto &GVI : valueIds()) {
3938     Stream.EmitRecord(bitc::FS_VALUE_GUID,
3939                       ArrayRef<uint64_t>{GVI.second, GVI.first});
3940   }
3941 
3942   // Abbrev for FS_PERMODULE_PROFILE.
3943   auto Abbv = std::make_shared<BitCodeAbbrev>();
3944   Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_PROFILE));
3945   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // valueid
3946   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // flags
3947   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // instcount
3948   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // fflags
3949   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // numrefs
3950   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // rorefcnt
3951   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // worefcnt
3952   // numrefs x valueid, n x (valueid, hotness)
3953   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3954   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3955   unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3956 
3957   // Abbrev for FS_PERMODULE or FS_PERMODULE_RELBF.
3958   Abbv = std::make_shared<BitCodeAbbrev>();
3959   if (WriteRelBFToSummary)
3960     Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_RELBF));
3961   else
3962     Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE));
3963   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // valueid
3964   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // flags
3965   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // instcount
3966   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // fflags
3967   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // numrefs
3968   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // rorefcnt
3969   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // worefcnt
3970   // numrefs x valueid, n x (valueid [, rel_block_freq])
3971   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3972   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3973   unsigned FSCallsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3974 
3975   // Abbrev for FS_PERMODULE_GLOBALVAR_INIT_REFS.
3976   Abbv = std::make_shared<BitCodeAbbrev>();
3977   Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS));
3978   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
3979   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
3980   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));  // valueids
3981   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3982   unsigned FSModRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3983 
3984   // Abbrev for FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS.
3985   Abbv = std::make_shared<BitCodeAbbrev>();
3986   Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS));
3987   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
3988   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
3989   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
3990   // numrefs x valueid, n x (valueid , offset)
3991   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3992   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3993   unsigned FSModVTableRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3994 
3995   // Abbrev for FS_ALIAS.
3996   Abbv = std::make_shared<BitCodeAbbrev>();
3997   Abbv->Add(BitCodeAbbrevOp(bitc::FS_ALIAS));
3998   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // valueid
3999   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // flags
4000   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // valueid
4001   unsigned FSAliasAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4002 
4003   // Abbrev for FS_TYPE_ID_METADATA
4004   Abbv = std::make_shared<BitCodeAbbrev>();
4005   Abbv->Add(BitCodeAbbrevOp(bitc::FS_TYPE_ID_METADATA));
4006   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // typeid strtab index
4007   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // typeid length
4008   // n x (valueid , offset)
4009   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4010   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4011   unsigned TypeIdCompatibleVtableAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4012 
4013   SmallVector<uint64_t, 64> NameVals;
4014   // Iterate over the list of functions instead of the Index to
4015   // ensure the ordering is stable.
4016   for (const Function &F : M) {
4017     // Summary emission does not support anonymous functions, they have to
4018     // renamed using the anonymous function renaming pass.
4019     if (!F.hasName())
4020       report_fatal_error("Unexpected anonymous function when writing summary");
4021 
4022     ValueInfo VI = Index->getValueInfo(F.getGUID());
4023     if (!VI || VI.getSummaryList().empty()) {
4024       // Only declarations should not have a summary (a declaration might
4025       // however have a summary if the def was in module level asm).
4026       assert(F.isDeclaration());
4027       continue;
4028     }
4029     auto *Summary = VI.getSummaryList()[0].get();
4030     writePerModuleFunctionSummaryRecord(NameVals, Summary, VE.getValueID(&F),
4031                                         FSCallsAbbrev, FSCallsProfileAbbrev, F);
4032   }
4033 
4034   // Capture references from GlobalVariable initializers, which are outside
4035   // of a function scope.
4036   for (const GlobalVariable &G : M.globals())
4037     writeModuleLevelReferences(G, NameVals, FSModRefsAbbrev,
4038                                FSModVTableRefsAbbrev);
4039 
4040   for (const GlobalAlias &A : M.aliases()) {
4041     auto *Aliasee = A.getAliaseeObject();
4042     if (!Aliasee->hasName())
4043       // Nameless function don't have an entry in the summary, skip it.
4044       continue;
4045     auto AliasId = VE.getValueID(&A);
4046     auto AliaseeId = VE.getValueID(Aliasee);
4047     NameVals.push_back(AliasId);
4048     auto *Summary = Index->getGlobalValueSummary(A);
4049     AliasSummary *AS = cast<AliasSummary>(Summary);
4050     NameVals.push_back(getEncodedGVSummaryFlags(AS->flags()));
4051     NameVals.push_back(AliaseeId);
4052     Stream.EmitRecord(bitc::FS_ALIAS, NameVals, FSAliasAbbrev);
4053     NameVals.clear();
4054   }
4055 
4056   for (auto &S : Index->typeIdCompatibleVtableMap()) {
4057     writeTypeIdCompatibleVtableSummaryRecord(NameVals, StrtabBuilder, S.first,
4058                                              S.second, VE);
4059     Stream.EmitRecord(bitc::FS_TYPE_ID_METADATA, NameVals,
4060                       TypeIdCompatibleVtableAbbrev);
4061     NameVals.clear();
4062   }
4063 
4064   Stream.EmitRecord(bitc::FS_BLOCK_COUNT,
4065                     ArrayRef<uint64_t>{Index->getBlockCount()});
4066 
4067   Stream.ExitBlock();
4068 }
4069 
4070 /// Emit the combined summary section into the combined index file.
4071 void IndexBitcodeWriter::writeCombinedGlobalValueSummary() {
4072   Stream.EnterSubblock(bitc::GLOBALVAL_SUMMARY_BLOCK_ID, 3);
4073   Stream.EmitRecord(
4074       bitc::FS_VERSION,
4075       ArrayRef<uint64_t>{ModuleSummaryIndex::BitcodeSummaryVersion});
4076 
4077   // Write the index flags.
4078   Stream.EmitRecord(bitc::FS_FLAGS, ArrayRef<uint64_t>{Index.getFlags()});
4079 
4080   for (const auto &GVI : valueIds()) {
4081     Stream.EmitRecord(bitc::FS_VALUE_GUID,
4082                       ArrayRef<uint64_t>{GVI.second, GVI.first});
4083   }
4084 
4085   // Abbrev for FS_COMBINED.
4086   auto Abbv = std::make_shared<BitCodeAbbrev>();
4087   Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED));
4088   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // valueid
4089   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // modid
4090   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // flags
4091   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // instcount
4092   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // fflags
4093   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // entrycount
4094   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // numrefs
4095   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // rorefcnt
4096   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // worefcnt
4097   // numrefs x valueid, n x (valueid)
4098   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4099   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4100   unsigned FSCallsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4101 
4102   // Abbrev for FS_COMBINED_PROFILE.
4103   Abbv = std::make_shared<BitCodeAbbrev>();
4104   Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_PROFILE));
4105   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // valueid
4106   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // modid
4107   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // flags
4108   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // instcount
4109   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // fflags
4110   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // entrycount
4111   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // numrefs
4112   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // rorefcnt
4113   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // worefcnt
4114   // numrefs x valueid, n x (valueid, hotness)
4115   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4116   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4117   unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4118 
4119   // Abbrev for FS_COMBINED_GLOBALVAR_INIT_REFS.
4120   Abbv = std::make_shared<BitCodeAbbrev>();
4121   Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_GLOBALVAR_INIT_REFS));
4122   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // valueid
4123   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // modid
4124   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // flags
4125   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));    // valueids
4126   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4127   unsigned FSModRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4128 
4129   // Abbrev for FS_COMBINED_ALIAS.
4130   Abbv = std::make_shared<BitCodeAbbrev>();
4131   Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_ALIAS));
4132   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // valueid
4133   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // modid
4134   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // flags
4135   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // valueid
4136   unsigned FSAliasAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4137 
4138   // The aliases are emitted as a post-pass, and will point to the value
4139   // id of the aliasee. Save them in a vector for post-processing.
4140   SmallVector<AliasSummary *, 64> Aliases;
4141 
4142   // Save the value id for each summary for alias emission.
4143   DenseMap<const GlobalValueSummary *, unsigned> SummaryToValueIdMap;
4144 
4145   SmallVector<uint64_t, 64> NameVals;
4146 
4147   // Set that will be populated during call to writeFunctionTypeMetadataRecords
4148   // with the type ids referenced by this index file.
4149   std::set<GlobalValue::GUID> ReferencedTypeIds;
4150 
4151   // For local linkage, we also emit the original name separately
4152   // immediately after the record.
4153   auto MaybeEmitOriginalName = [&](GlobalValueSummary &S) {
4154     // We don't need to emit the original name if we are writing the index for
4155     // distributed backends (in which case ModuleToSummariesForIndex is
4156     // non-null). The original name is only needed during the thin link, since
4157     // for SamplePGO the indirect call targets for local functions have
4158     // have the original name annotated in profile.
4159     // Continue to emit it when writing out the entire combined index, which is
4160     // used in testing the thin link via llvm-lto.
4161     if (ModuleToSummariesForIndex || !GlobalValue::isLocalLinkage(S.linkage()))
4162       return;
4163     NameVals.push_back(S.getOriginalName());
4164     Stream.EmitRecord(bitc::FS_COMBINED_ORIGINAL_NAME, NameVals);
4165     NameVals.clear();
4166   };
4167 
4168   std::set<GlobalValue::GUID> DefOrUseGUIDs;
4169   forEachSummary([&](GVInfo I, bool IsAliasee) {
4170     GlobalValueSummary *S = I.second;
4171     assert(S);
4172     DefOrUseGUIDs.insert(I.first);
4173     for (const ValueInfo &VI : S->refs())
4174       DefOrUseGUIDs.insert(VI.getGUID());
4175 
4176     auto ValueId = getValueId(I.first);
4177     assert(ValueId);
4178     SummaryToValueIdMap[S] = *ValueId;
4179 
4180     // If this is invoked for an aliasee, we want to record the above
4181     // mapping, but then not emit a summary entry (if the aliasee is
4182     // to be imported, we will invoke this separately with IsAliasee=false).
4183     if (IsAliasee)
4184       return;
4185 
4186     if (auto *AS = dyn_cast<AliasSummary>(S)) {
4187       // Will process aliases as a post-pass because the reader wants all
4188       // global to be loaded first.
4189       Aliases.push_back(AS);
4190       return;
4191     }
4192 
4193     if (auto *VS = dyn_cast<GlobalVarSummary>(S)) {
4194       NameVals.push_back(*ValueId);
4195       NameVals.push_back(Index.getModuleId(VS->modulePath()));
4196       NameVals.push_back(getEncodedGVSummaryFlags(VS->flags()));
4197       NameVals.push_back(getEncodedGVarFlags(VS->varflags()));
4198       for (auto &RI : VS->refs()) {
4199         auto RefValueId = getValueId(RI.getGUID());
4200         if (!RefValueId)
4201           continue;
4202         NameVals.push_back(*RefValueId);
4203       }
4204 
4205       // Emit the finished record.
4206       Stream.EmitRecord(bitc::FS_COMBINED_GLOBALVAR_INIT_REFS, NameVals,
4207                         FSModRefsAbbrev);
4208       NameVals.clear();
4209       MaybeEmitOriginalName(*S);
4210       return;
4211     }
4212 
4213     auto GetValueId = [&](const ValueInfo &VI) -> Optional<unsigned> {
4214       return getValueId(VI.getGUID());
4215     };
4216 
4217     auto *FS = cast<FunctionSummary>(S);
4218     writeFunctionTypeMetadataRecords(Stream, FS, GetValueId);
4219     getReferencedTypeIds(FS, ReferencedTypeIds);
4220 
4221     NameVals.push_back(*ValueId);
4222     NameVals.push_back(Index.getModuleId(FS->modulePath()));
4223     NameVals.push_back(getEncodedGVSummaryFlags(FS->flags()));
4224     NameVals.push_back(FS->instCount());
4225     NameVals.push_back(getEncodedFFlags(FS->fflags()));
4226     NameVals.push_back(FS->entryCount());
4227 
4228     // Fill in below
4229     NameVals.push_back(0); // numrefs
4230     NameVals.push_back(0); // rorefcnt
4231     NameVals.push_back(0); // worefcnt
4232 
4233     unsigned Count = 0, RORefCnt = 0, WORefCnt = 0;
4234     for (auto &RI : FS->refs()) {
4235       auto RefValueId = getValueId(RI.getGUID());
4236       if (!RefValueId)
4237         continue;
4238       NameVals.push_back(*RefValueId);
4239       if (RI.isReadOnly())
4240         RORefCnt++;
4241       else if (RI.isWriteOnly())
4242         WORefCnt++;
4243       Count++;
4244     }
4245     NameVals[6] = Count;
4246     NameVals[7] = RORefCnt;
4247     NameVals[8] = WORefCnt;
4248 
4249     bool HasProfileData = false;
4250     for (auto &EI : FS->calls()) {
4251       HasProfileData |=
4252           EI.second.getHotness() != CalleeInfo::HotnessType::Unknown;
4253       if (HasProfileData)
4254         break;
4255     }
4256 
4257     for (auto &EI : FS->calls()) {
4258       // If this GUID doesn't have a value id, it doesn't have a function
4259       // summary and we don't need to record any calls to it.
4260       Optional<unsigned> CallValueId = GetValueId(EI.first);
4261       if (!CallValueId)
4262         continue;
4263       NameVals.push_back(*CallValueId);
4264       if (HasProfileData)
4265         NameVals.push_back(static_cast<uint8_t>(EI.second.Hotness));
4266     }
4267 
4268     unsigned FSAbbrev = (HasProfileData ? FSCallsProfileAbbrev : FSCallsAbbrev);
4269     unsigned Code =
4270         (HasProfileData ? bitc::FS_COMBINED_PROFILE : bitc::FS_COMBINED);
4271 
4272     // Emit the finished record.
4273     Stream.EmitRecord(Code, NameVals, FSAbbrev);
4274     NameVals.clear();
4275     MaybeEmitOriginalName(*S);
4276   });
4277 
4278   for (auto *AS : Aliases) {
4279     auto AliasValueId = SummaryToValueIdMap[AS];
4280     assert(AliasValueId);
4281     NameVals.push_back(AliasValueId);
4282     NameVals.push_back(Index.getModuleId(AS->modulePath()));
4283     NameVals.push_back(getEncodedGVSummaryFlags(AS->flags()));
4284     auto AliaseeValueId = SummaryToValueIdMap[&AS->getAliasee()];
4285     assert(AliaseeValueId);
4286     NameVals.push_back(AliaseeValueId);
4287 
4288     // Emit the finished record.
4289     Stream.EmitRecord(bitc::FS_COMBINED_ALIAS, NameVals, FSAliasAbbrev);
4290     NameVals.clear();
4291     MaybeEmitOriginalName(*AS);
4292 
4293     if (auto *FS = dyn_cast<FunctionSummary>(&AS->getAliasee()))
4294       getReferencedTypeIds(FS, ReferencedTypeIds);
4295   }
4296 
4297   if (!Index.cfiFunctionDefs().empty()) {
4298     for (auto &S : Index.cfiFunctionDefs()) {
4299       if (DefOrUseGUIDs.count(
4300               GlobalValue::getGUID(GlobalValue::dropLLVMManglingEscape(S)))) {
4301         NameVals.push_back(StrtabBuilder.add(S));
4302         NameVals.push_back(S.size());
4303       }
4304     }
4305     if (!NameVals.empty()) {
4306       Stream.EmitRecord(bitc::FS_CFI_FUNCTION_DEFS, NameVals);
4307       NameVals.clear();
4308     }
4309   }
4310 
4311   if (!Index.cfiFunctionDecls().empty()) {
4312     for (auto &S : Index.cfiFunctionDecls()) {
4313       if (DefOrUseGUIDs.count(
4314               GlobalValue::getGUID(GlobalValue::dropLLVMManglingEscape(S)))) {
4315         NameVals.push_back(StrtabBuilder.add(S));
4316         NameVals.push_back(S.size());
4317       }
4318     }
4319     if (!NameVals.empty()) {
4320       Stream.EmitRecord(bitc::FS_CFI_FUNCTION_DECLS, NameVals);
4321       NameVals.clear();
4322     }
4323   }
4324 
4325   // Walk the GUIDs that were referenced, and write the
4326   // corresponding type id records.
4327   for (auto &T : ReferencedTypeIds) {
4328     auto TidIter = Index.typeIds().equal_range(T);
4329     for (auto It = TidIter.first; It != TidIter.second; ++It) {
4330       writeTypeIdSummaryRecord(NameVals, StrtabBuilder, It->second.first,
4331                                It->second.second);
4332       Stream.EmitRecord(bitc::FS_TYPE_ID, NameVals);
4333       NameVals.clear();
4334     }
4335   }
4336 
4337   Stream.EmitRecord(bitc::FS_BLOCK_COUNT,
4338                     ArrayRef<uint64_t>{Index.getBlockCount()});
4339 
4340   Stream.ExitBlock();
4341 }
4342 
4343 /// Create the "IDENTIFICATION_BLOCK_ID" containing a single string with the
4344 /// current llvm version, and a record for the epoch number.
4345 static void writeIdentificationBlock(BitstreamWriter &Stream) {
4346   Stream.EnterSubblock(bitc::IDENTIFICATION_BLOCK_ID, 5);
4347 
4348   // Write the "user readable" string identifying the bitcode producer
4349   auto Abbv = std::make_shared<BitCodeAbbrev>();
4350   Abbv->Add(BitCodeAbbrevOp(bitc::IDENTIFICATION_CODE_STRING));
4351   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4352   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
4353   auto StringAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4354   writeStringRecord(Stream, bitc::IDENTIFICATION_CODE_STRING,
4355                     "LLVM" LLVM_VERSION_STRING, StringAbbrev);
4356 
4357   // Write the epoch version
4358   Abbv = std::make_shared<BitCodeAbbrev>();
4359   Abbv->Add(BitCodeAbbrevOp(bitc::IDENTIFICATION_CODE_EPOCH));
4360   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
4361   auto EpochAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4362   constexpr std::array<unsigned, 1> Vals = {{bitc::BITCODE_CURRENT_EPOCH}};
4363   Stream.EmitRecord(bitc::IDENTIFICATION_CODE_EPOCH, Vals, EpochAbbrev);
4364   Stream.ExitBlock();
4365 }
4366 
4367 void ModuleBitcodeWriter::writeModuleHash(size_t BlockStartPos) {
4368   // Emit the module's hash.
4369   // MODULE_CODE_HASH: [5*i32]
4370   if (GenerateHash) {
4371     uint32_t Vals[5];
4372     Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&(Buffer)[BlockStartPos],
4373                                     Buffer.size() - BlockStartPos));
4374     StringRef Hash = Hasher.result();
4375     for (int Pos = 0; Pos < 20; Pos += 4) {
4376       Vals[Pos / 4] = support::endian::read32be(Hash.data() + Pos);
4377     }
4378 
4379     // Emit the finished record.
4380     Stream.EmitRecord(bitc::MODULE_CODE_HASH, Vals);
4381 
4382     if (ModHash)
4383       // Save the written hash value.
4384       llvm::copy(Vals, std::begin(*ModHash));
4385   }
4386 }
4387 
4388 void ModuleBitcodeWriter::write() {
4389   writeIdentificationBlock(Stream);
4390 
4391   Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
4392   size_t BlockStartPos = Buffer.size();
4393 
4394   writeModuleVersion();
4395 
4396   // Emit blockinfo, which defines the standard abbreviations etc.
4397   writeBlockInfo();
4398 
4399   // Emit information describing all of the types in the module.
4400   writeTypeTable();
4401 
4402   // Emit information about attribute groups.
4403   writeAttributeGroupTable();
4404 
4405   // Emit information about parameter attributes.
4406   writeAttributeTable();
4407 
4408   writeComdats();
4409 
4410   // Emit top-level description of module, including target triple, inline asm,
4411   // descriptors for global variables, and function prototype info.
4412   writeModuleInfo();
4413 
4414   // Emit constants.
4415   writeModuleConstants();
4416 
4417   // Emit metadata kind names.
4418   writeModuleMetadataKinds();
4419 
4420   // Emit metadata.
4421   writeModuleMetadata();
4422 
4423   // Emit module-level use-lists.
4424   if (VE.shouldPreserveUseListOrder())
4425     writeUseListBlock(nullptr);
4426 
4427   writeOperandBundleTags();
4428   writeSyncScopeNames();
4429 
4430   // Emit function bodies.
4431   DenseMap<const Function *, uint64_t> FunctionToBitcodeIndex;
4432   for (Module::const_iterator F = M.begin(), E = M.end(); F != E; ++F)
4433     if (!F->isDeclaration())
4434       writeFunction(*F, FunctionToBitcodeIndex);
4435 
4436   // Need to write after the above call to WriteFunction which populates
4437   // the summary information in the index.
4438   if (Index)
4439     writePerModuleGlobalValueSummary();
4440 
4441   writeGlobalValueSymbolTable(FunctionToBitcodeIndex);
4442 
4443   writeModuleHash(BlockStartPos);
4444 
4445   Stream.ExitBlock();
4446 }
4447 
4448 static void writeInt32ToBuffer(uint32_t Value, SmallVectorImpl<char> &Buffer,
4449                                uint32_t &Position) {
4450   support::endian::write32le(&Buffer[Position], Value);
4451   Position += 4;
4452 }
4453 
4454 /// If generating a bc file on darwin, we have to emit a
4455 /// header and trailer to make it compatible with the system archiver.  To do
4456 /// this we emit the following header, and then emit a trailer that pads the
4457 /// file out to be a multiple of 16 bytes.
4458 ///
4459 /// struct bc_header {
4460 ///   uint32_t Magic;         // 0x0B17C0DE
4461 ///   uint32_t Version;       // Version, currently always 0.
4462 ///   uint32_t BitcodeOffset; // Offset to traditional bitcode file.
4463 ///   uint32_t BitcodeSize;   // Size of traditional bitcode file.
4464 ///   uint32_t CPUType;       // CPU specifier.
4465 ///   ... potentially more later ...
4466 /// };
4467 static void emitDarwinBCHeaderAndTrailer(SmallVectorImpl<char> &Buffer,
4468                                          const Triple &TT) {
4469   unsigned CPUType = ~0U;
4470 
4471   // Match x86_64-*, i[3-9]86-*, powerpc-*, powerpc64-*, arm-*, thumb-*,
4472   // armv[0-9]-*, thumbv[0-9]-*, armv5te-*, or armv6t2-*. The CPUType is a magic
4473   // number from /usr/include/mach/machine.h.  It is ok to reproduce the
4474   // specific constants here because they are implicitly part of the Darwin ABI.
4475   enum {
4476     DARWIN_CPU_ARCH_ABI64      = 0x01000000,
4477     DARWIN_CPU_TYPE_X86        = 7,
4478     DARWIN_CPU_TYPE_ARM        = 12,
4479     DARWIN_CPU_TYPE_POWERPC    = 18
4480   };
4481 
4482   Triple::ArchType Arch = TT.getArch();
4483   if (Arch == Triple::x86_64)
4484     CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64;
4485   else if (Arch == Triple::x86)
4486     CPUType = DARWIN_CPU_TYPE_X86;
4487   else if (Arch == Triple::ppc)
4488     CPUType = DARWIN_CPU_TYPE_POWERPC;
4489   else if (Arch == Triple::ppc64)
4490     CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64;
4491   else if (Arch == Triple::arm || Arch == Triple::thumb)
4492     CPUType = DARWIN_CPU_TYPE_ARM;
4493 
4494   // Traditional Bitcode starts after header.
4495   assert(Buffer.size() >= BWH_HeaderSize &&
4496          "Expected header size to be reserved");
4497   unsigned BCOffset = BWH_HeaderSize;
4498   unsigned BCSize = Buffer.size() - BWH_HeaderSize;
4499 
4500   // Write the magic and version.
4501   unsigned Position = 0;
4502   writeInt32ToBuffer(0x0B17C0DE, Buffer, Position);
4503   writeInt32ToBuffer(0, Buffer, Position); // Version.
4504   writeInt32ToBuffer(BCOffset, Buffer, Position);
4505   writeInt32ToBuffer(BCSize, Buffer, Position);
4506   writeInt32ToBuffer(CPUType, Buffer, Position);
4507 
4508   // If the file is not a multiple of 16 bytes, insert dummy padding.
4509   while (Buffer.size() & 15)
4510     Buffer.push_back(0);
4511 }
4512 
4513 /// Helper to write the header common to all bitcode files.
4514 static void writeBitcodeHeader(BitstreamWriter &Stream) {
4515   // Emit the file header.
4516   Stream.Emit((unsigned)'B', 8);
4517   Stream.Emit((unsigned)'C', 8);
4518   Stream.Emit(0x0, 4);
4519   Stream.Emit(0xC, 4);
4520   Stream.Emit(0xE, 4);
4521   Stream.Emit(0xD, 4);
4522 }
4523 
4524 BitcodeWriter::BitcodeWriter(SmallVectorImpl<char> &Buffer, raw_fd_stream *FS)
4525     : Buffer(Buffer), Stream(new BitstreamWriter(Buffer, FS, FlushThreshold)) {
4526   writeBitcodeHeader(*Stream);
4527 }
4528 
4529 BitcodeWriter::~BitcodeWriter() { assert(WroteStrtab); }
4530 
4531 void BitcodeWriter::writeBlob(unsigned Block, unsigned Record, StringRef Blob) {
4532   Stream->EnterSubblock(Block, 3);
4533 
4534   auto Abbv = std::make_shared<BitCodeAbbrev>();
4535   Abbv->Add(BitCodeAbbrevOp(Record));
4536   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
4537   auto AbbrevNo = Stream->EmitAbbrev(std::move(Abbv));
4538 
4539   Stream->EmitRecordWithBlob(AbbrevNo, ArrayRef<uint64_t>{Record}, Blob);
4540 
4541   Stream->ExitBlock();
4542 }
4543 
4544 void BitcodeWriter::writeSymtab() {
4545   assert(!WroteStrtab && !WroteSymtab);
4546 
4547   // If any module has module-level inline asm, we will require a registered asm
4548   // parser for the target so that we can create an accurate symbol table for
4549   // the module.
4550   for (Module *M : Mods) {
4551     if (M->getModuleInlineAsm().empty())
4552       continue;
4553 
4554     std::string Err;
4555     const Triple TT(M->getTargetTriple());
4556     const Target *T = TargetRegistry::lookupTarget(TT.str(), Err);
4557     if (!T || !T->hasMCAsmParser())
4558       return;
4559   }
4560 
4561   WroteSymtab = true;
4562   SmallVector<char, 0> Symtab;
4563   // The irsymtab::build function may be unable to create a symbol table if the
4564   // module is malformed (e.g. it contains an invalid alias). Writing a symbol
4565   // table is not required for correctness, but we still want to be able to
4566   // write malformed modules to bitcode files, so swallow the error.
4567   if (Error E = irsymtab::build(Mods, Symtab, StrtabBuilder, Alloc)) {
4568     consumeError(std::move(E));
4569     return;
4570   }
4571 
4572   writeBlob(bitc::SYMTAB_BLOCK_ID, bitc::SYMTAB_BLOB,
4573             {Symtab.data(), Symtab.size()});
4574 }
4575 
4576 void BitcodeWriter::writeStrtab() {
4577   assert(!WroteStrtab);
4578 
4579   std::vector<char> Strtab;
4580   StrtabBuilder.finalizeInOrder();
4581   Strtab.resize(StrtabBuilder.getSize());
4582   StrtabBuilder.write((uint8_t *)Strtab.data());
4583 
4584   writeBlob(bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB,
4585             {Strtab.data(), Strtab.size()});
4586 
4587   WroteStrtab = true;
4588 }
4589 
4590 void BitcodeWriter::copyStrtab(StringRef Strtab) {
4591   writeBlob(bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB, Strtab);
4592   WroteStrtab = true;
4593 }
4594 
4595 void BitcodeWriter::writeModule(const Module &M,
4596                                 bool ShouldPreserveUseListOrder,
4597                                 const ModuleSummaryIndex *Index,
4598                                 bool GenerateHash, ModuleHash *ModHash) {
4599   assert(!WroteStrtab);
4600 
4601   // The Mods vector is used by irsymtab::build, which requires non-const
4602   // Modules in case it needs to materialize metadata. But the bitcode writer
4603   // requires that the module is materialized, so we can cast to non-const here,
4604   // after checking that it is in fact materialized.
4605   assert(M.isMaterialized());
4606   Mods.push_back(const_cast<Module *>(&M));
4607 
4608   ModuleBitcodeWriter ModuleWriter(M, Buffer, StrtabBuilder, *Stream,
4609                                    ShouldPreserveUseListOrder, Index,
4610                                    GenerateHash, ModHash);
4611   ModuleWriter.write();
4612 }
4613 
4614 void BitcodeWriter::writeIndex(
4615     const ModuleSummaryIndex *Index,
4616     const std::map<std::string, GVSummaryMapTy> *ModuleToSummariesForIndex) {
4617   IndexBitcodeWriter IndexWriter(*Stream, StrtabBuilder, *Index,
4618                                  ModuleToSummariesForIndex);
4619   IndexWriter.write();
4620 }
4621 
4622 /// Write the specified module to the specified output stream.
4623 void llvm::WriteBitcodeToFile(const Module &M, raw_ostream &Out,
4624                               bool ShouldPreserveUseListOrder,
4625                               const ModuleSummaryIndex *Index,
4626                               bool GenerateHash, ModuleHash *ModHash) {
4627   SmallVector<char, 0> Buffer;
4628   Buffer.reserve(256*1024);
4629 
4630   // If this is darwin or another generic macho target, reserve space for the
4631   // header.
4632   Triple TT(M.getTargetTriple());
4633   if (TT.isOSDarwin() || TT.isOSBinFormatMachO())
4634     Buffer.insert(Buffer.begin(), BWH_HeaderSize, 0);
4635 
4636   BitcodeWriter Writer(Buffer, dyn_cast<raw_fd_stream>(&Out));
4637   Writer.writeModule(M, ShouldPreserveUseListOrder, Index, GenerateHash,
4638                      ModHash);
4639   Writer.writeSymtab();
4640   Writer.writeStrtab();
4641 
4642   if (TT.isOSDarwin() || TT.isOSBinFormatMachO())
4643     emitDarwinBCHeaderAndTrailer(Buffer, TT);
4644 
4645   // Write the generated bitstream to "Out".
4646   if (!Buffer.empty())
4647     Out.write((char *)&Buffer.front(), Buffer.size());
4648 }
4649 
4650 void IndexBitcodeWriter::write() {
4651   Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
4652 
4653   writeModuleVersion();
4654 
4655   // Write the module paths in the combined index.
4656   writeModStrings();
4657 
4658   // Write the summary combined index records.
4659   writeCombinedGlobalValueSummary();
4660 
4661   Stream.ExitBlock();
4662 }
4663 
4664 // Write the specified module summary index to the given raw output stream,
4665 // where it will be written in a new bitcode block. This is used when
4666 // writing the combined index file for ThinLTO. When writing a subset of the
4667 // index for a distributed backend, provide a \p ModuleToSummariesForIndex map.
4668 void llvm::WriteIndexToFile(
4669     const ModuleSummaryIndex &Index, raw_ostream &Out,
4670     const std::map<std::string, GVSummaryMapTy> *ModuleToSummariesForIndex) {
4671   SmallVector<char, 0> Buffer;
4672   Buffer.reserve(256 * 1024);
4673 
4674   BitcodeWriter Writer(Buffer);
4675   Writer.writeIndex(&Index, ModuleToSummariesForIndex);
4676   Writer.writeStrtab();
4677 
4678   Out.write((char *)&Buffer.front(), Buffer.size());
4679 }
4680 
4681 namespace {
4682 
4683 /// Class to manage the bitcode writing for a thin link bitcode file.
4684 class ThinLinkBitcodeWriter : public ModuleBitcodeWriterBase {
4685   /// ModHash is for use in ThinLTO incremental build, generated while writing
4686   /// the module bitcode file.
4687   const ModuleHash *ModHash;
4688 
4689 public:
4690   ThinLinkBitcodeWriter(const Module &M, StringTableBuilder &StrtabBuilder,
4691                         BitstreamWriter &Stream,
4692                         const ModuleSummaryIndex &Index,
4693                         const ModuleHash &ModHash)
4694       : ModuleBitcodeWriterBase(M, StrtabBuilder, Stream,
4695                                 /*ShouldPreserveUseListOrder=*/false, &Index),
4696         ModHash(&ModHash) {}
4697 
4698   void write();
4699 
4700 private:
4701   void writeSimplifiedModuleInfo();
4702 };
4703 
4704 } // end anonymous namespace
4705 
4706 // This function writes a simpilified module info for thin link bitcode file.
4707 // It only contains the source file name along with the name(the offset and
4708 // size in strtab) and linkage for global values. For the global value info
4709 // entry, in order to keep linkage at offset 5, there are three zeros used
4710 // as padding.
4711 void ThinLinkBitcodeWriter::writeSimplifiedModuleInfo() {
4712   SmallVector<unsigned, 64> Vals;
4713   // Emit the module's source file name.
4714   {
4715     StringEncoding Bits = getStringEncoding(M.getSourceFileName());
4716     BitCodeAbbrevOp AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8);
4717     if (Bits == SE_Char6)
4718       AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Char6);
4719     else if (Bits == SE_Fixed7)
4720       AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7);
4721 
4722     // MODULE_CODE_SOURCE_FILENAME: [namechar x N]
4723     auto Abbv = std::make_shared<BitCodeAbbrev>();
4724     Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_SOURCE_FILENAME));
4725     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4726     Abbv->Add(AbbrevOpToUse);
4727     unsigned FilenameAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4728 
4729     for (const auto P : M.getSourceFileName())
4730       Vals.push_back((unsigned char)P);
4731 
4732     Stream.EmitRecord(bitc::MODULE_CODE_SOURCE_FILENAME, Vals, FilenameAbbrev);
4733     Vals.clear();
4734   }
4735 
4736   // Emit the global variable information.
4737   for (const GlobalVariable &GV : M.globals()) {
4738     // GLOBALVAR: [strtab offset, strtab size, 0, 0, 0, linkage]
4739     Vals.push_back(StrtabBuilder.add(GV.getName()));
4740     Vals.push_back(GV.getName().size());
4741     Vals.push_back(0);
4742     Vals.push_back(0);
4743     Vals.push_back(0);
4744     Vals.push_back(getEncodedLinkage(GV));
4745 
4746     Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals);
4747     Vals.clear();
4748   }
4749 
4750   // Emit the function proto information.
4751   for (const Function &F : M) {
4752     // FUNCTION:  [strtab offset, strtab size, 0, 0, 0, linkage]
4753     Vals.push_back(StrtabBuilder.add(F.getName()));
4754     Vals.push_back(F.getName().size());
4755     Vals.push_back(0);
4756     Vals.push_back(0);
4757     Vals.push_back(0);
4758     Vals.push_back(getEncodedLinkage(F));
4759 
4760     Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals);
4761     Vals.clear();
4762   }
4763 
4764   // Emit the alias information.
4765   for (const GlobalAlias &A : M.aliases()) {
4766     // ALIAS: [strtab offset, strtab size, 0, 0, 0, linkage]
4767     Vals.push_back(StrtabBuilder.add(A.getName()));
4768     Vals.push_back(A.getName().size());
4769     Vals.push_back(0);
4770     Vals.push_back(0);
4771     Vals.push_back(0);
4772     Vals.push_back(getEncodedLinkage(A));
4773 
4774     Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals);
4775     Vals.clear();
4776   }
4777 
4778   // Emit the ifunc information.
4779   for (const GlobalIFunc &I : M.ifuncs()) {
4780     // IFUNC: [strtab offset, strtab size, 0, 0, 0, linkage]
4781     Vals.push_back(StrtabBuilder.add(I.getName()));
4782     Vals.push_back(I.getName().size());
4783     Vals.push_back(0);
4784     Vals.push_back(0);
4785     Vals.push_back(0);
4786     Vals.push_back(getEncodedLinkage(I));
4787 
4788     Stream.EmitRecord(bitc::MODULE_CODE_IFUNC, Vals);
4789     Vals.clear();
4790   }
4791 }
4792 
4793 void ThinLinkBitcodeWriter::write() {
4794   Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
4795 
4796   writeModuleVersion();
4797 
4798   writeSimplifiedModuleInfo();
4799 
4800   writePerModuleGlobalValueSummary();
4801 
4802   // Write module hash.
4803   Stream.EmitRecord(bitc::MODULE_CODE_HASH, ArrayRef<uint32_t>(*ModHash));
4804 
4805   Stream.ExitBlock();
4806 }
4807 
4808 void BitcodeWriter::writeThinLinkBitcode(const Module &M,
4809                                          const ModuleSummaryIndex &Index,
4810                                          const ModuleHash &ModHash) {
4811   assert(!WroteStrtab);
4812 
4813   // The Mods vector is used by irsymtab::build, which requires non-const
4814   // Modules in case it needs to materialize metadata. But the bitcode writer
4815   // requires that the module is materialized, so we can cast to non-const here,
4816   // after checking that it is in fact materialized.
4817   assert(M.isMaterialized());
4818   Mods.push_back(const_cast<Module *>(&M));
4819 
4820   ThinLinkBitcodeWriter ThinLinkWriter(M, StrtabBuilder, *Stream, Index,
4821                                        ModHash);
4822   ThinLinkWriter.write();
4823 }
4824 
4825 // Write the specified thin link bitcode file to the given raw output stream,
4826 // where it will be written in a new bitcode block. This is used when
4827 // writing the per-module index file for ThinLTO.
4828 void llvm::WriteThinLinkBitcodeToFile(const Module &M, raw_ostream &Out,
4829                                       const ModuleSummaryIndex &Index,
4830                                       const ModuleHash &ModHash) {
4831   SmallVector<char, 0> Buffer;
4832   Buffer.reserve(256 * 1024);
4833 
4834   BitcodeWriter Writer(Buffer);
4835   Writer.writeThinLinkBitcode(M, Index, ModHash);
4836   Writer.writeSymtab();
4837   Writer.writeStrtab();
4838 
4839   Out.write((char *)&Buffer.front(), Buffer.size());
4840 }
4841 
4842 static const char *getSectionNameForBitcode(const Triple &T) {
4843   switch (T.getObjectFormat()) {
4844   case Triple::MachO:
4845     return "__LLVM,__bitcode";
4846   case Triple::COFF:
4847   case Triple::ELF:
4848   case Triple::Wasm:
4849   case Triple::UnknownObjectFormat:
4850     return ".llvmbc";
4851   case Triple::GOFF:
4852     llvm_unreachable("GOFF is not yet implemented");
4853     break;
4854   case Triple::XCOFF:
4855     llvm_unreachable("XCOFF is not yet implemented");
4856     break;
4857   }
4858   llvm_unreachable("Unimplemented ObjectFormatType");
4859 }
4860 
4861 static const char *getSectionNameForCommandline(const Triple &T) {
4862   switch (T.getObjectFormat()) {
4863   case Triple::MachO:
4864     return "__LLVM,__cmdline";
4865   case Triple::COFF:
4866   case Triple::ELF:
4867   case Triple::Wasm:
4868   case Triple::UnknownObjectFormat:
4869     return ".llvmcmd";
4870   case Triple::GOFF:
4871     llvm_unreachable("GOFF is not yet implemented");
4872     break;
4873   case Triple::XCOFF:
4874     llvm_unreachable("XCOFF is not yet implemented");
4875     break;
4876   }
4877   llvm_unreachable("Unimplemented ObjectFormatType");
4878 }
4879 
4880 void llvm::EmbedBitcodeInModule(llvm::Module &M, llvm::MemoryBufferRef Buf,
4881                                 bool EmbedBitcode, bool EmbedCmdline,
4882                                 const std::vector<uint8_t> &CmdArgs) {
4883   // Save llvm.compiler.used and remove it.
4884   SmallVector<Constant *, 2> UsedArray;
4885   SmallVector<GlobalValue *, 4> UsedGlobals;
4886   Type *UsedElementType = Type::getInt8Ty(M.getContext())->getPointerTo(0);
4887   GlobalVariable *Used = collectUsedGlobalVariables(M, UsedGlobals, true);
4888   for (auto *GV : UsedGlobals) {
4889     if (GV->getName() != "llvm.embedded.module" &&
4890         GV->getName() != "llvm.cmdline")
4891       UsedArray.push_back(
4892           ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
4893   }
4894   if (Used)
4895     Used->eraseFromParent();
4896 
4897   // Embed the bitcode for the llvm module.
4898   std::string Data;
4899   ArrayRef<uint8_t> ModuleData;
4900   Triple T(M.getTargetTriple());
4901 
4902   if (EmbedBitcode) {
4903     if (Buf.getBufferSize() == 0 ||
4904         !isBitcode((const unsigned char *)Buf.getBufferStart(),
4905                    (const unsigned char *)Buf.getBufferEnd())) {
4906       // If the input is LLVM Assembly, bitcode is produced by serializing
4907       // the module. Use-lists order need to be preserved in this case.
4908       llvm::raw_string_ostream OS(Data);
4909       llvm::WriteBitcodeToFile(M, OS, /* ShouldPreserveUseListOrder */ true);
4910       ModuleData =
4911           ArrayRef<uint8_t>((const uint8_t *)OS.str().data(), OS.str().size());
4912     } else
4913       // If the input is LLVM bitcode, write the input byte stream directly.
4914       ModuleData = ArrayRef<uint8_t>((const uint8_t *)Buf.getBufferStart(),
4915                                      Buf.getBufferSize());
4916   }
4917   llvm::Constant *ModuleConstant =
4918       llvm::ConstantDataArray::get(M.getContext(), ModuleData);
4919   llvm::GlobalVariable *GV = new llvm::GlobalVariable(
4920       M, ModuleConstant->getType(), true, llvm::GlobalValue::PrivateLinkage,
4921       ModuleConstant);
4922   GV->setSection(getSectionNameForBitcode(T));
4923   // Set alignment to 1 to prevent padding between two contributions from input
4924   // sections after linking.
4925   GV->setAlignment(Align(1));
4926   UsedArray.push_back(
4927       ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
4928   if (llvm::GlobalVariable *Old =
4929           M.getGlobalVariable("llvm.embedded.module", true)) {
4930     assert(Old->hasOneUse() &&
4931            "llvm.embedded.module can only be used once in llvm.compiler.used");
4932     GV->takeName(Old);
4933     Old->eraseFromParent();
4934   } else {
4935     GV->setName("llvm.embedded.module");
4936   }
4937 
4938   // Skip if only bitcode needs to be embedded.
4939   if (EmbedCmdline) {
4940     // Embed command-line options.
4941     ArrayRef<uint8_t> CmdData(const_cast<uint8_t *>(CmdArgs.data()),
4942                               CmdArgs.size());
4943     llvm::Constant *CmdConstant =
4944         llvm::ConstantDataArray::get(M.getContext(), CmdData);
4945     GV = new llvm::GlobalVariable(M, CmdConstant->getType(), true,
4946                                   llvm::GlobalValue::PrivateLinkage,
4947                                   CmdConstant);
4948     GV->setSection(getSectionNameForCommandline(T));
4949     GV->setAlignment(Align(1));
4950     UsedArray.push_back(
4951         ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
4952     if (llvm::GlobalVariable *Old = M.getGlobalVariable("llvm.cmdline", true)) {
4953       assert(Old->hasOneUse() &&
4954              "llvm.cmdline can only be used once in llvm.compiler.used");
4955       GV->takeName(Old);
4956       Old->eraseFromParent();
4957     } else {
4958       GV->setName("llvm.cmdline");
4959     }
4960   }
4961 
4962   if (UsedArray.empty())
4963     return;
4964 
4965   // Recreate llvm.compiler.used.
4966   ArrayType *ATy = ArrayType::get(UsedElementType, UsedArray.size());
4967   auto *NewUsed = new GlobalVariable(
4968       M, ATy, false, llvm::GlobalValue::AppendingLinkage,
4969       llvm::ConstantArray::get(ATy, UsedArray), "llvm.compiler.used");
4970   NewUsed->setSection("llvm.metadata");
4971 }
4972