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