xref: /freebsd-src/contrib/llvm-project/llvm/lib/Bitcode/Writer/BitcodeWriter.cpp (revision 0fca6ea1d4eea4c934cfff25ac9ee8ad6fe95583)
10b57cec5SDimitry Andric //===- Bitcode/Writer/BitcodeWriter.cpp - Bitcode Writer ------------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // Bitcode writer implementation.
100b57cec5SDimitry Andric //
110b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
120b57cec5SDimitry Andric 
130b57cec5SDimitry Andric #include "llvm/Bitcode/BitcodeWriter.h"
140b57cec5SDimitry Andric #include "ValueEnumerator.h"
150b57cec5SDimitry Andric #include "llvm/ADT/APFloat.h"
160b57cec5SDimitry Andric #include "llvm/ADT/APInt.h"
170b57cec5SDimitry Andric #include "llvm/ADT/ArrayRef.h"
180b57cec5SDimitry Andric #include "llvm/ADT/DenseMap.h"
190b57cec5SDimitry Andric #include "llvm/ADT/STLExtras.h"
2081ad6265SDimitry Andric #include "llvm/ADT/SetVector.h"
2181ad6265SDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
220b57cec5SDimitry Andric #include "llvm/ADT/SmallString.h"
230b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h"
240b57cec5SDimitry Andric #include "llvm/ADT/StringMap.h"
250b57cec5SDimitry Andric #include "llvm/ADT/StringRef.h"
26e8d8bef9SDimitry Andric #include "llvm/Bitcode/BitcodeCommon.h"
27480093f4SDimitry Andric #include "llvm/Bitcode/BitcodeReader.h"
28480093f4SDimitry Andric #include "llvm/Bitcode/LLVMBitCodes.h"
290b57cec5SDimitry Andric #include "llvm/Bitstream/BitCodes.h"
300b57cec5SDimitry Andric #include "llvm/Bitstream/BitstreamWriter.h"
310b57cec5SDimitry Andric #include "llvm/Config/llvm-config.h"
320b57cec5SDimitry Andric #include "llvm/IR/Attributes.h"
330b57cec5SDimitry Andric #include "llvm/IR/BasicBlock.h"
340b57cec5SDimitry Andric #include "llvm/IR/Comdat.h"
350b57cec5SDimitry Andric #include "llvm/IR/Constant.h"
36*0fca6ea1SDimitry Andric #include "llvm/IR/ConstantRangeList.h"
370b57cec5SDimitry Andric #include "llvm/IR/Constants.h"
380b57cec5SDimitry Andric #include "llvm/IR/DebugInfoMetadata.h"
390b57cec5SDimitry Andric #include "llvm/IR/DebugLoc.h"
400b57cec5SDimitry Andric #include "llvm/IR/DerivedTypes.h"
410b57cec5SDimitry Andric #include "llvm/IR/Function.h"
420b57cec5SDimitry Andric #include "llvm/IR/GlobalAlias.h"
430b57cec5SDimitry Andric #include "llvm/IR/GlobalIFunc.h"
440b57cec5SDimitry Andric #include "llvm/IR/GlobalObject.h"
450b57cec5SDimitry Andric #include "llvm/IR/GlobalValue.h"
460b57cec5SDimitry Andric #include "llvm/IR/GlobalVariable.h"
470b57cec5SDimitry Andric #include "llvm/IR/InlineAsm.h"
480b57cec5SDimitry Andric #include "llvm/IR/InstrTypes.h"
490b57cec5SDimitry Andric #include "llvm/IR/Instruction.h"
500b57cec5SDimitry Andric #include "llvm/IR/Instructions.h"
510b57cec5SDimitry Andric #include "llvm/IR/LLVMContext.h"
520b57cec5SDimitry Andric #include "llvm/IR/Metadata.h"
530b57cec5SDimitry Andric #include "llvm/IR/Module.h"
540b57cec5SDimitry Andric #include "llvm/IR/ModuleSummaryIndex.h"
550b57cec5SDimitry Andric #include "llvm/IR/Operator.h"
560b57cec5SDimitry Andric #include "llvm/IR/Type.h"
570b57cec5SDimitry Andric #include "llvm/IR/UseListOrder.h"
580b57cec5SDimitry Andric #include "llvm/IR/Value.h"
590b57cec5SDimitry Andric #include "llvm/IR/ValueSymbolTable.h"
600b57cec5SDimitry Andric #include "llvm/MC/StringTableBuilder.h"
61349cc55cSDimitry Andric #include "llvm/MC/TargetRegistry.h"
620b57cec5SDimitry Andric #include "llvm/Object/IRSymtab.h"
630b57cec5SDimitry Andric #include "llvm/Support/AtomicOrdering.h"
640b57cec5SDimitry Andric #include "llvm/Support/Casting.h"
650b57cec5SDimitry Andric #include "llvm/Support/CommandLine.h"
660b57cec5SDimitry Andric #include "llvm/Support/Endian.h"
670b57cec5SDimitry Andric #include "llvm/Support/Error.h"
680b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h"
690b57cec5SDimitry Andric #include "llvm/Support/MathExtras.h"
700b57cec5SDimitry Andric #include "llvm/Support/SHA1.h"
710b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
7206c3fb27SDimitry Andric #include "llvm/TargetParser/Triple.h"
730b57cec5SDimitry Andric #include <algorithm>
740b57cec5SDimitry Andric #include <cassert>
750b57cec5SDimitry Andric #include <cstddef>
760b57cec5SDimitry Andric #include <cstdint>
770b57cec5SDimitry Andric #include <iterator>
780b57cec5SDimitry Andric #include <map>
790b57cec5SDimitry Andric #include <memory>
80bdd1243dSDimitry Andric #include <optional>
810b57cec5SDimitry Andric #include <string>
820b57cec5SDimitry Andric #include <utility>
830b57cec5SDimitry Andric #include <vector>
840b57cec5SDimitry Andric 
850b57cec5SDimitry Andric using namespace llvm;
860b57cec5SDimitry Andric 
870b57cec5SDimitry Andric static cl::opt<unsigned>
880b57cec5SDimitry Andric     IndexThreshold("bitcode-mdindex-threshold", cl::Hidden, cl::init(25),
890b57cec5SDimitry Andric                    cl::desc("Number of metadatas above which we emit an index "
900b57cec5SDimitry Andric                             "to enable lazy-loading"));
91e8d8bef9SDimitry Andric static cl::opt<uint32_t> FlushThreshold(
92e8d8bef9SDimitry Andric     "bitcode-flush-threshold", cl::Hidden, cl::init(512),
93e8d8bef9SDimitry Andric     cl::desc("The threshold (unit M) for flushing LLVM bitcode."));
940b57cec5SDimitry Andric 
958bcb0991SDimitry Andric static cl::opt<bool> WriteRelBFToSummary(
960b57cec5SDimitry Andric     "write-relbf-to-summary", cl::Hidden, cl::init(false),
970b57cec5SDimitry Andric     cl::desc("Write relative block frequency to function summary "));
980b57cec5SDimitry Andric 
99bdd1243dSDimitry Andric namespace llvm {
1000b57cec5SDimitry Andric extern FunctionSummary::ForceSummaryHotnessType ForceSummaryEdgesCold;
101bdd1243dSDimitry Andric }
1020b57cec5SDimitry Andric 
103*0fca6ea1SDimitry Andric extern bool WriteNewDbgInfoFormatToBitcode;
104*0fca6ea1SDimitry Andric extern llvm::cl::opt<bool> UseNewDbgInfoFormat;
105*0fca6ea1SDimitry Andric 
1060b57cec5SDimitry Andric namespace {
1070b57cec5SDimitry Andric 
1080b57cec5SDimitry Andric /// These are manifest constants used by the bitcode writer. They do not need to
1090b57cec5SDimitry Andric /// be kept in sync with the reader, but need to be consistent within this file.
1100b57cec5SDimitry Andric enum {
1110b57cec5SDimitry Andric   // VALUE_SYMTAB_BLOCK abbrev id's.
1120b57cec5SDimitry Andric   VST_ENTRY_8_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
1130b57cec5SDimitry Andric   VST_ENTRY_7_ABBREV,
1140b57cec5SDimitry Andric   VST_ENTRY_6_ABBREV,
1150b57cec5SDimitry Andric   VST_BBENTRY_6_ABBREV,
1160b57cec5SDimitry Andric 
1170b57cec5SDimitry Andric   // CONSTANTS_BLOCK abbrev id's.
1180b57cec5SDimitry Andric   CONSTANTS_SETTYPE_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
1190b57cec5SDimitry Andric   CONSTANTS_INTEGER_ABBREV,
1200b57cec5SDimitry Andric   CONSTANTS_CE_CAST_Abbrev,
1210b57cec5SDimitry Andric   CONSTANTS_NULL_Abbrev,
1220b57cec5SDimitry Andric 
1230b57cec5SDimitry Andric   // FUNCTION_BLOCK abbrev id's.
1240b57cec5SDimitry Andric   FUNCTION_INST_LOAD_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
1250b57cec5SDimitry Andric   FUNCTION_INST_UNOP_ABBREV,
1260b57cec5SDimitry Andric   FUNCTION_INST_UNOP_FLAGS_ABBREV,
1270b57cec5SDimitry Andric   FUNCTION_INST_BINOP_ABBREV,
1280b57cec5SDimitry Andric   FUNCTION_INST_BINOP_FLAGS_ABBREV,
1290b57cec5SDimitry Andric   FUNCTION_INST_CAST_ABBREV,
1305f757f3fSDimitry Andric   FUNCTION_INST_CAST_FLAGS_ABBREV,
1310b57cec5SDimitry Andric   FUNCTION_INST_RET_VOID_ABBREV,
1320b57cec5SDimitry Andric   FUNCTION_INST_RET_VAL_ABBREV,
1330b57cec5SDimitry Andric   FUNCTION_INST_UNREACHABLE_ABBREV,
1340b57cec5SDimitry Andric   FUNCTION_INST_GEP_ABBREV,
135*0fca6ea1SDimitry Andric   FUNCTION_DEBUG_RECORD_VALUE_ABBREV,
1360b57cec5SDimitry Andric };
1370b57cec5SDimitry Andric 
1380b57cec5SDimitry Andric /// Abstract class to manage the bitcode writing, subclassed for each bitcode
1390b57cec5SDimitry Andric /// file type.
1400b57cec5SDimitry Andric class BitcodeWriterBase {
1410b57cec5SDimitry Andric protected:
1420b57cec5SDimitry Andric   /// The stream created and owned by the client.
1430b57cec5SDimitry Andric   BitstreamWriter &Stream;
1440b57cec5SDimitry Andric 
1450b57cec5SDimitry Andric   StringTableBuilder &StrtabBuilder;
1460b57cec5SDimitry Andric 
1470b57cec5SDimitry Andric public:
1480b57cec5SDimitry Andric   /// Constructs a BitcodeWriterBase object that writes to the provided
1490b57cec5SDimitry Andric   /// \p Stream.
1500b57cec5SDimitry Andric   BitcodeWriterBase(BitstreamWriter &Stream, StringTableBuilder &StrtabBuilder)
1510b57cec5SDimitry Andric       : Stream(Stream), StrtabBuilder(StrtabBuilder) {}
1520b57cec5SDimitry Andric 
1530b57cec5SDimitry Andric protected:
1540b57cec5SDimitry Andric   void writeModuleVersion();
1550b57cec5SDimitry Andric };
1560b57cec5SDimitry Andric 
1570b57cec5SDimitry Andric void BitcodeWriterBase::writeModuleVersion() {
1580b57cec5SDimitry Andric   // VERSION: [version#]
1590b57cec5SDimitry Andric   Stream.EmitRecord(bitc::MODULE_CODE_VERSION, ArrayRef<uint64_t>{2});
1600b57cec5SDimitry Andric }
1610b57cec5SDimitry Andric 
1620b57cec5SDimitry Andric /// Base class to manage the module bitcode writing, currently subclassed for
1630b57cec5SDimitry Andric /// ModuleBitcodeWriter and ThinLinkBitcodeWriter.
1640b57cec5SDimitry Andric class ModuleBitcodeWriterBase : public BitcodeWriterBase {
1650b57cec5SDimitry Andric protected:
1660b57cec5SDimitry Andric   /// The Module to write to bitcode.
1670b57cec5SDimitry Andric   const Module &M;
1680b57cec5SDimitry Andric 
1690b57cec5SDimitry Andric   /// Enumerates ids for all values in the module.
1700b57cec5SDimitry Andric   ValueEnumerator VE;
1710b57cec5SDimitry Andric 
1720b57cec5SDimitry Andric   /// Optional per-module index to write for ThinLTO.
1730b57cec5SDimitry Andric   const ModuleSummaryIndex *Index;
1740b57cec5SDimitry Andric 
1750b57cec5SDimitry Andric   /// Map that holds the correspondence between GUIDs in the summary index,
1760b57cec5SDimitry Andric   /// that came from indirect call profiles, and a value id generated by this
1770b57cec5SDimitry Andric   /// class to use in the VST and summary block records.
1780b57cec5SDimitry Andric   std::map<GlobalValue::GUID, unsigned> GUIDToValueIdMap;
1790b57cec5SDimitry Andric 
1800b57cec5SDimitry Andric   /// Tracks the last value id recorded in the GUIDToValueMap.
1810b57cec5SDimitry Andric   unsigned GlobalValueId;
1820b57cec5SDimitry Andric 
1830b57cec5SDimitry Andric   /// Saves the offset of the VSTOffset record that must eventually be
1840b57cec5SDimitry Andric   /// backpatched with the offset of the actual VST.
1850b57cec5SDimitry Andric   uint64_t VSTOffsetPlaceholder = 0;
1860b57cec5SDimitry Andric 
1870b57cec5SDimitry Andric public:
1880b57cec5SDimitry Andric   /// Constructs a ModuleBitcodeWriterBase object for the given Module,
1890b57cec5SDimitry Andric   /// writing to the provided \p Buffer.
1900b57cec5SDimitry Andric   ModuleBitcodeWriterBase(const Module &M, StringTableBuilder &StrtabBuilder,
1910b57cec5SDimitry Andric                           BitstreamWriter &Stream,
1920b57cec5SDimitry Andric                           bool ShouldPreserveUseListOrder,
1930b57cec5SDimitry Andric                           const ModuleSummaryIndex *Index)
1940b57cec5SDimitry Andric       : BitcodeWriterBase(Stream, StrtabBuilder), M(M),
1950b57cec5SDimitry Andric         VE(M, ShouldPreserveUseListOrder), Index(Index) {
1960b57cec5SDimitry Andric     // Assign ValueIds to any callee values in the index that came from
1970b57cec5SDimitry Andric     // indirect call profiles and were recorded as a GUID not a Value*
1980b57cec5SDimitry Andric     // (which would have been assigned an ID by the ValueEnumerator).
1990b57cec5SDimitry Andric     // The starting ValueId is just after the number of values in the
2000b57cec5SDimitry Andric     // ValueEnumerator, so that they can be emitted in the VST.
2010b57cec5SDimitry Andric     GlobalValueId = VE.getValues().size();
2020b57cec5SDimitry Andric     if (!Index)
2030b57cec5SDimitry Andric       return;
2040b57cec5SDimitry Andric     for (const auto &GUIDSummaryLists : *Index)
2050b57cec5SDimitry Andric       // Examine all summaries for this GUID.
2060b57cec5SDimitry Andric       for (auto &Summary : GUIDSummaryLists.second.SummaryList)
207*0fca6ea1SDimitry Andric         if (auto FS = dyn_cast<FunctionSummary>(Summary.get())) {
2080b57cec5SDimitry Andric           // For each call in the function summary, see if the call
2090b57cec5SDimitry Andric           // is to a GUID (which means it is for an indirect call,
2100b57cec5SDimitry Andric           // otherwise we would have a Value for it). If so, synthesize
2110b57cec5SDimitry Andric           // a value id.
2120b57cec5SDimitry Andric           for (auto &CallEdge : FS->calls())
2130b57cec5SDimitry Andric             if (!CallEdge.first.haveGVs() || !CallEdge.first.getValue())
2140b57cec5SDimitry Andric               assignValueId(CallEdge.first.getGUID());
215*0fca6ea1SDimitry Andric 
216*0fca6ea1SDimitry Andric           // For each referenced variables in the function summary, see if the
217*0fca6ea1SDimitry Andric           // variable is represented by a GUID (as opposed to a symbol to
218*0fca6ea1SDimitry Andric           // declarations or definitions in the module). If so, synthesize a
219*0fca6ea1SDimitry Andric           // value id.
220*0fca6ea1SDimitry Andric           for (auto &RefEdge : FS->refs())
221*0fca6ea1SDimitry Andric             if (!RefEdge.haveGVs() || !RefEdge.getValue())
222*0fca6ea1SDimitry Andric               assignValueId(RefEdge.getGUID());
223*0fca6ea1SDimitry Andric         }
2240b57cec5SDimitry Andric   }
2250b57cec5SDimitry Andric 
2260b57cec5SDimitry Andric protected:
2270b57cec5SDimitry Andric   void writePerModuleGlobalValueSummary();
2280b57cec5SDimitry Andric 
2290b57cec5SDimitry Andric private:
230bdd1243dSDimitry Andric   void writePerModuleFunctionSummaryRecord(
231bdd1243dSDimitry Andric       SmallVector<uint64_t, 64> &NameVals, GlobalValueSummary *Summary,
232bdd1243dSDimitry Andric       unsigned ValueID, unsigned FSCallsAbbrev, unsigned FSCallsProfileAbbrev,
233bdd1243dSDimitry Andric       unsigned CallsiteAbbrev, unsigned AllocAbbrev, const Function &F);
2340b57cec5SDimitry Andric   void writeModuleLevelReferences(const GlobalVariable &V,
2350b57cec5SDimitry Andric                                   SmallVector<uint64_t, 64> &NameVals,
2360b57cec5SDimitry Andric                                   unsigned FSModRefsAbbrev,
2370b57cec5SDimitry Andric                                   unsigned FSModVTableRefsAbbrev);
2380b57cec5SDimitry Andric 
2390b57cec5SDimitry Andric   void assignValueId(GlobalValue::GUID ValGUID) {
2400b57cec5SDimitry Andric     GUIDToValueIdMap[ValGUID] = ++GlobalValueId;
2410b57cec5SDimitry Andric   }
2420b57cec5SDimitry Andric 
2430b57cec5SDimitry Andric   unsigned getValueId(GlobalValue::GUID ValGUID) {
2440b57cec5SDimitry Andric     const auto &VMI = GUIDToValueIdMap.find(ValGUID);
2450b57cec5SDimitry Andric     // Expect that any GUID value had a value Id assigned by an
2460b57cec5SDimitry Andric     // earlier call to assignValueId.
2470b57cec5SDimitry Andric     assert(VMI != GUIDToValueIdMap.end() &&
2480b57cec5SDimitry Andric            "GUID does not have assigned value Id");
2490b57cec5SDimitry Andric     return VMI->second;
2500b57cec5SDimitry Andric   }
2510b57cec5SDimitry Andric 
2520b57cec5SDimitry Andric   // Helper to get the valueId for the type of value recorded in VI.
2530b57cec5SDimitry Andric   unsigned getValueId(ValueInfo VI) {
2540b57cec5SDimitry Andric     if (!VI.haveGVs() || !VI.getValue())
2550b57cec5SDimitry Andric       return getValueId(VI.getGUID());
2560b57cec5SDimitry Andric     return VE.getValueID(VI.getValue());
2570b57cec5SDimitry Andric   }
2580b57cec5SDimitry Andric 
2590b57cec5SDimitry Andric   std::map<GlobalValue::GUID, unsigned> &valueIds() { return GUIDToValueIdMap; }
2600b57cec5SDimitry Andric };
2610b57cec5SDimitry Andric 
2620b57cec5SDimitry Andric /// Class to manage the bitcode writing for a module.
2630b57cec5SDimitry Andric class ModuleBitcodeWriter : public ModuleBitcodeWriterBase {
2640b57cec5SDimitry Andric   /// True if a module hash record should be written.
2650b57cec5SDimitry Andric   bool GenerateHash;
2660b57cec5SDimitry Andric 
2670b57cec5SDimitry Andric   /// If non-null, when GenerateHash is true, the resulting hash is written
2680b57cec5SDimitry Andric   /// into ModHash.
2690b57cec5SDimitry Andric   ModuleHash *ModHash;
2700b57cec5SDimitry Andric 
2710b57cec5SDimitry Andric   SHA1 Hasher;
2720b57cec5SDimitry Andric 
2730b57cec5SDimitry Andric   /// The start bit of the identification block.
2740b57cec5SDimitry Andric   uint64_t BitcodeStartBit;
2750b57cec5SDimitry Andric 
2760b57cec5SDimitry Andric public:
2770b57cec5SDimitry Andric   /// Constructs a ModuleBitcodeWriter object for the given Module,
2780b57cec5SDimitry Andric   /// writing to the provided \p Buffer.
279*0fca6ea1SDimitry Andric   ModuleBitcodeWriter(const Module &M, StringTableBuilder &StrtabBuilder,
2800b57cec5SDimitry Andric                       BitstreamWriter &Stream, bool ShouldPreserveUseListOrder,
2810b57cec5SDimitry Andric                       const ModuleSummaryIndex *Index, bool GenerateHash,
2820b57cec5SDimitry Andric                       ModuleHash *ModHash = nullptr)
2830b57cec5SDimitry Andric       : ModuleBitcodeWriterBase(M, StrtabBuilder, Stream,
2840b57cec5SDimitry Andric                                 ShouldPreserveUseListOrder, Index),
285*0fca6ea1SDimitry Andric         GenerateHash(GenerateHash), ModHash(ModHash),
2860b57cec5SDimitry Andric         BitcodeStartBit(Stream.GetCurrentBitNo()) {}
2870b57cec5SDimitry Andric 
2880b57cec5SDimitry Andric   /// Emit the current module to the bitstream.
2890b57cec5SDimitry Andric   void write();
2900b57cec5SDimitry Andric 
2910b57cec5SDimitry Andric private:
2920b57cec5SDimitry Andric   uint64_t bitcodeStartBit() { return BitcodeStartBit; }
2930b57cec5SDimitry Andric 
2940b57cec5SDimitry Andric   size_t addToStrtab(StringRef Str);
2950b57cec5SDimitry Andric 
2960b57cec5SDimitry Andric   void writeAttributeGroupTable();
2970b57cec5SDimitry Andric   void writeAttributeTable();
2980b57cec5SDimitry Andric   void writeTypeTable();
2990b57cec5SDimitry Andric   void writeComdats();
3000b57cec5SDimitry Andric   void writeValueSymbolTableForwardDecl();
3010b57cec5SDimitry Andric   void writeModuleInfo();
3020b57cec5SDimitry Andric   void writeValueAsMetadata(const ValueAsMetadata *MD,
3030b57cec5SDimitry Andric                             SmallVectorImpl<uint64_t> &Record);
3040b57cec5SDimitry Andric   void writeMDTuple(const MDTuple *N, SmallVectorImpl<uint64_t> &Record,
3050b57cec5SDimitry Andric                     unsigned Abbrev);
3060b57cec5SDimitry Andric   unsigned createDILocationAbbrev();
3070b57cec5SDimitry Andric   void writeDILocation(const DILocation *N, SmallVectorImpl<uint64_t> &Record,
3080b57cec5SDimitry Andric                        unsigned &Abbrev);
3090b57cec5SDimitry Andric   unsigned createGenericDINodeAbbrev();
3100b57cec5SDimitry Andric   void writeGenericDINode(const GenericDINode *N,
3110b57cec5SDimitry Andric                           SmallVectorImpl<uint64_t> &Record, unsigned &Abbrev);
3120b57cec5SDimitry Andric   void writeDISubrange(const DISubrange *N, SmallVectorImpl<uint64_t> &Record,
3130b57cec5SDimitry Andric                        unsigned Abbrev);
314e8d8bef9SDimitry Andric   void writeDIGenericSubrange(const DIGenericSubrange *N,
315e8d8bef9SDimitry Andric                               SmallVectorImpl<uint64_t> &Record,
316e8d8bef9SDimitry Andric                               unsigned Abbrev);
3170b57cec5SDimitry Andric   void writeDIEnumerator(const DIEnumerator *N,
3180b57cec5SDimitry Andric                          SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
3190b57cec5SDimitry Andric   void writeDIBasicType(const DIBasicType *N, SmallVectorImpl<uint64_t> &Record,
3200b57cec5SDimitry Andric                         unsigned Abbrev);
321e8d8bef9SDimitry Andric   void writeDIStringType(const DIStringType *N,
322e8d8bef9SDimitry Andric                          SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
3230b57cec5SDimitry Andric   void writeDIDerivedType(const DIDerivedType *N,
3240b57cec5SDimitry Andric                           SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
3250b57cec5SDimitry Andric   void writeDICompositeType(const DICompositeType *N,
3260b57cec5SDimitry Andric                             SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
3270b57cec5SDimitry Andric   void writeDISubroutineType(const DISubroutineType *N,
3280b57cec5SDimitry Andric                              SmallVectorImpl<uint64_t> &Record,
3290b57cec5SDimitry Andric                              unsigned Abbrev);
3300b57cec5SDimitry Andric   void writeDIFile(const DIFile *N, SmallVectorImpl<uint64_t> &Record,
3310b57cec5SDimitry Andric                    unsigned Abbrev);
3320b57cec5SDimitry Andric   void writeDICompileUnit(const DICompileUnit *N,
3330b57cec5SDimitry Andric                           SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
3340b57cec5SDimitry Andric   void writeDISubprogram(const DISubprogram *N,
3350b57cec5SDimitry Andric                          SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
3360b57cec5SDimitry Andric   void writeDILexicalBlock(const DILexicalBlock *N,
3370b57cec5SDimitry Andric                            SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
3380b57cec5SDimitry Andric   void writeDILexicalBlockFile(const DILexicalBlockFile *N,
3390b57cec5SDimitry Andric                                SmallVectorImpl<uint64_t> &Record,
3400b57cec5SDimitry Andric                                unsigned Abbrev);
3410b57cec5SDimitry Andric   void writeDICommonBlock(const DICommonBlock *N,
3420b57cec5SDimitry Andric                           SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
3430b57cec5SDimitry Andric   void writeDINamespace(const DINamespace *N, SmallVectorImpl<uint64_t> &Record,
3440b57cec5SDimitry Andric                         unsigned Abbrev);
3450b57cec5SDimitry Andric   void writeDIMacro(const DIMacro *N, SmallVectorImpl<uint64_t> &Record,
3460b57cec5SDimitry Andric                     unsigned Abbrev);
3470b57cec5SDimitry Andric   void writeDIMacroFile(const DIMacroFile *N, SmallVectorImpl<uint64_t> &Record,
3480b57cec5SDimitry Andric                         unsigned Abbrev);
3495f757f3fSDimitry Andric   void writeDIArgList(const DIArgList *N, SmallVectorImpl<uint64_t> &Record);
3500b57cec5SDimitry Andric   void writeDIModule(const DIModule *N, SmallVectorImpl<uint64_t> &Record,
3510b57cec5SDimitry Andric                      unsigned Abbrev);
352bdd1243dSDimitry Andric   void writeDIAssignID(const DIAssignID *N, SmallVectorImpl<uint64_t> &Record,
353bdd1243dSDimitry Andric                        unsigned Abbrev);
3540b57cec5SDimitry Andric   void writeDITemplateTypeParameter(const DITemplateTypeParameter *N,
3550b57cec5SDimitry Andric                                     SmallVectorImpl<uint64_t> &Record,
3560b57cec5SDimitry Andric                                     unsigned Abbrev);
3570b57cec5SDimitry Andric   void writeDITemplateValueParameter(const DITemplateValueParameter *N,
3580b57cec5SDimitry Andric                                      SmallVectorImpl<uint64_t> &Record,
3590b57cec5SDimitry Andric                                      unsigned Abbrev);
3600b57cec5SDimitry Andric   void writeDIGlobalVariable(const DIGlobalVariable *N,
3610b57cec5SDimitry Andric                              SmallVectorImpl<uint64_t> &Record,
3620b57cec5SDimitry Andric                              unsigned Abbrev);
3630b57cec5SDimitry Andric   void writeDILocalVariable(const DILocalVariable *N,
3640b57cec5SDimitry Andric                             SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
3650b57cec5SDimitry Andric   void writeDILabel(const DILabel *N,
3660b57cec5SDimitry Andric                     SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
3670b57cec5SDimitry Andric   void writeDIExpression(const DIExpression *N,
3680b57cec5SDimitry Andric                          SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
3690b57cec5SDimitry Andric   void writeDIGlobalVariableExpression(const DIGlobalVariableExpression *N,
3700b57cec5SDimitry Andric                                        SmallVectorImpl<uint64_t> &Record,
3710b57cec5SDimitry Andric                                        unsigned Abbrev);
3720b57cec5SDimitry Andric   void writeDIObjCProperty(const DIObjCProperty *N,
3730b57cec5SDimitry Andric                            SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
3740b57cec5SDimitry Andric   void writeDIImportedEntity(const DIImportedEntity *N,
3750b57cec5SDimitry Andric                              SmallVectorImpl<uint64_t> &Record,
3760b57cec5SDimitry Andric                              unsigned Abbrev);
3770b57cec5SDimitry Andric   unsigned createNamedMetadataAbbrev();
3780b57cec5SDimitry Andric   void writeNamedMetadata(SmallVectorImpl<uint64_t> &Record);
3790b57cec5SDimitry Andric   unsigned createMetadataStringsAbbrev();
3800b57cec5SDimitry Andric   void writeMetadataStrings(ArrayRef<const Metadata *> Strings,
3810b57cec5SDimitry Andric                             SmallVectorImpl<uint64_t> &Record);
3820b57cec5SDimitry Andric   void writeMetadataRecords(ArrayRef<const Metadata *> MDs,
3830b57cec5SDimitry Andric                             SmallVectorImpl<uint64_t> &Record,
3840b57cec5SDimitry Andric                             std::vector<unsigned> *MDAbbrevs = nullptr,
3850b57cec5SDimitry Andric                             std::vector<uint64_t> *IndexPos = nullptr);
3860b57cec5SDimitry Andric   void writeModuleMetadata();
3870b57cec5SDimitry Andric   void writeFunctionMetadata(const Function &F);
3880b57cec5SDimitry Andric   void writeFunctionMetadataAttachment(const Function &F);
3890b57cec5SDimitry Andric   void pushGlobalMetadataAttachment(SmallVectorImpl<uint64_t> &Record,
3900b57cec5SDimitry Andric                                     const GlobalObject &GO);
3910b57cec5SDimitry Andric   void writeModuleMetadataKinds();
3920b57cec5SDimitry Andric   void writeOperandBundleTags();
3930b57cec5SDimitry Andric   void writeSyncScopeNames();
3940b57cec5SDimitry Andric   void writeConstants(unsigned FirstVal, unsigned LastVal, bool isGlobal);
3950b57cec5SDimitry Andric   void writeModuleConstants();
3960b57cec5SDimitry Andric   bool pushValueAndType(const Value *V, unsigned InstID,
3970b57cec5SDimitry Andric                         SmallVectorImpl<unsigned> &Vals);
3985ffd83dbSDimitry Andric   void writeOperandBundles(const CallBase &CB, unsigned InstID);
3990b57cec5SDimitry Andric   void pushValue(const Value *V, unsigned InstID,
4000b57cec5SDimitry Andric                  SmallVectorImpl<unsigned> &Vals);
4010b57cec5SDimitry Andric   void pushValueSigned(const Value *V, unsigned InstID,
4020b57cec5SDimitry Andric                        SmallVectorImpl<uint64_t> &Vals);
4030b57cec5SDimitry Andric   void writeInstruction(const Instruction &I, unsigned InstID,
4040b57cec5SDimitry Andric                         SmallVectorImpl<unsigned> &Vals);
4050b57cec5SDimitry Andric   void writeFunctionLevelValueSymbolTable(const ValueSymbolTable &VST);
4060b57cec5SDimitry Andric   void writeGlobalValueSymbolTable(
4070b57cec5SDimitry Andric       DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex);
4080b57cec5SDimitry Andric   void writeUseList(UseListOrder &&Order);
4090b57cec5SDimitry Andric   void writeUseListBlock(const Function *F);
4100b57cec5SDimitry Andric   void
4110b57cec5SDimitry Andric   writeFunction(const Function &F,
4120b57cec5SDimitry Andric                 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex);
4130b57cec5SDimitry Andric   void writeBlockInfo();
414*0fca6ea1SDimitry Andric   void writeModuleHash(StringRef View);
4150b57cec5SDimitry Andric 
4160b57cec5SDimitry Andric   unsigned getEncodedSyncScopeID(SyncScope::ID SSID) {
4170b57cec5SDimitry Andric     return unsigned(SSID);
4180b57cec5SDimitry Andric   }
419e8d8bef9SDimitry Andric 
420e8d8bef9SDimitry Andric   unsigned getEncodedAlign(MaybeAlign Alignment) { return encode(Alignment); }
4210b57cec5SDimitry Andric };
4220b57cec5SDimitry Andric 
4230b57cec5SDimitry Andric /// Class to manage the bitcode writing for a combined index.
4240b57cec5SDimitry Andric class IndexBitcodeWriter : public BitcodeWriterBase {
4250b57cec5SDimitry Andric   /// The combined index to write to bitcode.
4260b57cec5SDimitry Andric   const ModuleSummaryIndex &Index;
4270b57cec5SDimitry Andric 
428*0fca6ea1SDimitry Andric   /// When writing combined summaries, provides the set of global value
429*0fca6ea1SDimitry Andric   /// summaries for which the value (function, function alias, etc) should be
430*0fca6ea1SDimitry Andric   /// imported as a declaration.
431*0fca6ea1SDimitry Andric   const GVSummaryPtrSet *DecSummaries = nullptr;
432*0fca6ea1SDimitry Andric 
4330b57cec5SDimitry Andric   /// When writing a subset of the index for distributed backends, client
4340b57cec5SDimitry Andric   /// provides a map of modules to the corresponding GUIDs/summaries to write.
4350b57cec5SDimitry Andric   const std::map<std::string, GVSummaryMapTy> *ModuleToSummariesForIndex;
4360b57cec5SDimitry Andric 
4370b57cec5SDimitry Andric   /// Map that holds the correspondence between the GUID used in the combined
4380b57cec5SDimitry Andric   /// index and a value id generated by this class to use in references.
4390b57cec5SDimitry Andric   std::map<GlobalValue::GUID, unsigned> GUIDToValueIdMap;
4400b57cec5SDimitry Andric 
441*0fca6ea1SDimitry Andric   // The stack ids used by this index, which will be a subset of those in
442*0fca6ea1SDimitry Andric   // the full index in the case of distributed indexes.
443*0fca6ea1SDimitry Andric   std::vector<uint64_t> StackIds;
444*0fca6ea1SDimitry Andric 
445*0fca6ea1SDimitry Andric   // Keep a map of the stack id indices used by records being written for this
446*0fca6ea1SDimitry Andric   // index to the index of the corresponding stack id in the above StackIds
447*0fca6ea1SDimitry Andric   // vector. Ensures we write each referenced stack id once.
448*0fca6ea1SDimitry Andric   DenseMap<unsigned, unsigned> StackIdIndicesToIndex;
449bdd1243dSDimitry Andric 
4500b57cec5SDimitry Andric   /// Tracks the last value id recorded in the GUIDToValueMap.
4510b57cec5SDimitry Andric   unsigned GlobalValueId = 0;
4520b57cec5SDimitry Andric 
4535f757f3fSDimitry Andric   /// Tracks the assignment of module paths in the module path string table to
4545f757f3fSDimitry Andric   /// an id assigned for use in summary references to the module path.
4555f757f3fSDimitry Andric   DenseMap<StringRef, uint64_t> ModuleIdMap;
4565f757f3fSDimitry Andric 
4570b57cec5SDimitry Andric public:
4580b57cec5SDimitry Andric   /// Constructs a IndexBitcodeWriter object for the given combined index,
4590b57cec5SDimitry Andric   /// writing to the provided \p Buffer. When writing a subset of the index
4600b57cec5SDimitry Andric   /// for a distributed backend, provide a \p ModuleToSummariesForIndex map.
461*0fca6ea1SDimitry Andric   /// If provided, \p DecSummaries specifies the set of summaries for which
462*0fca6ea1SDimitry Andric   /// the corresponding functions or aliased functions should be imported as a
463*0fca6ea1SDimitry Andric   /// declaration (but not definition) for each module.
4640b57cec5SDimitry Andric   IndexBitcodeWriter(BitstreamWriter &Stream, StringTableBuilder &StrtabBuilder,
4650b57cec5SDimitry Andric                      const ModuleSummaryIndex &Index,
466*0fca6ea1SDimitry Andric                      const GVSummaryPtrSet *DecSummaries = nullptr,
4670b57cec5SDimitry Andric                      const std::map<std::string, GVSummaryMapTy>
4680b57cec5SDimitry Andric                          *ModuleToSummariesForIndex = nullptr)
4690b57cec5SDimitry Andric       : BitcodeWriterBase(Stream, StrtabBuilder), Index(Index),
470*0fca6ea1SDimitry Andric         DecSummaries(DecSummaries),
4710b57cec5SDimitry Andric         ModuleToSummariesForIndex(ModuleToSummariesForIndex) {
472*0fca6ea1SDimitry Andric 
473*0fca6ea1SDimitry Andric     // See if the StackIdIndex was already added to the StackId map and
474*0fca6ea1SDimitry Andric     // vector. If not, record it.
475*0fca6ea1SDimitry Andric     auto RecordStackIdReference = [&](unsigned StackIdIndex) {
476*0fca6ea1SDimitry Andric       // If the StackIdIndex is not yet in the map, the below insert ensures
477*0fca6ea1SDimitry Andric       // that it will point to the new StackIds vector entry we push to just
478*0fca6ea1SDimitry Andric       // below.
479*0fca6ea1SDimitry Andric       auto Inserted =
480*0fca6ea1SDimitry Andric           StackIdIndicesToIndex.insert({StackIdIndex, StackIds.size()});
481*0fca6ea1SDimitry Andric       if (Inserted.second)
482*0fca6ea1SDimitry Andric         StackIds.push_back(Index.getStackIdAtIndex(StackIdIndex));
483*0fca6ea1SDimitry Andric     };
484*0fca6ea1SDimitry Andric 
4850b57cec5SDimitry Andric     // Assign unique value ids to all summaries to be written, for use
4860b57cec5SDimitry Andric     // in writing out the call graph edges. Save the mapping from GUID
4870b57cec5SDimitry Andric     // to the new global value id to use when writing those edges, which
4880b57cec5SDimitry Andric     // are currently saved in the index in terms of GUID.
489bdd1243dSDimitry Andric     forEachSummary([&](GVInfo I, bool IsAliasee) {
4900b57cec5SDimitry Andric       GUIDToValueIdMap[I.first] = ++GlobalValueId;
491bdd1243dSDimitry Andric       if (IsAliasee)
492bdd1243dSDimitry Andric         return;
493bdd1243dSDimitry Andric       auto *FS = dyn_cast<FunctionSummary>(I.second);
494bdd1243dSDimitry Andric       if (!FS)
495bdd1243dSDimitry Andric         return;
496bdd1243dSDimitry Andric       // Record all stack id indices actually used in the summary entries being
497bdd1243dSDimitry Andric       // written, so that we can compact them in the case of distributed ThinLTO
498bdd1243dSDimitry Andric       // indexes.
499297eecfbSDimitry Andric       for (auto &CI : FS->callsites()) {
500297eecfbSDimitry Andric         // If the stack id list is empty, this callsite info was synthesized for
501297eecfbSDimitry Andric         // a missing tail call frame. Ensure that the callee's GUID gets a value
502297eecfbSDimitry Andric         // id. Normally we only generate these for defined summaries, which in
503297eecfbSDimitry Andric         // the case of distributed ThinLTO is only the functions already defined
504297eecfbSDimitry Andric         // in the module or that we want to import. We don't bother to include
505297eecfbSDimitry Andric         // all the callee symbols as they aren't normally needed in the backend.
506297eecfbSDimitry Andric         // However, for the synthesized callsite infos we do need the callee
507297eecfbSDimitry Andric         // GUID in the backend so that we can correlate the identified callee
508297eecfbSDimitry Andric         // with this callsite info (which for non-tail calls is done by the
509297eecfbSDimitry Andric         // ordering of the callsite infos and verified via stack ids).
510297eecfbSDimitry Andric         if (CI.StackIdIndices.empty()) {
511297eecfbSDimitry Andric           GUIDToValueIdMap[CI.Callee.getGUID()] = ++GlobalValueId;
512297eecfbSDimitry Andric           continue;
513297eecfbSDimitry Andric         }
514bdd1243dSDimitry Andric         for (auto Idx : CI.StackIdIndices)
515*0fca6ea1SDimitry Andric           RecordStackIdReference(Idx);
516297eecfbSDimitry Andric       }
517bdd1243dSDimitry Andric       for (auto &AI : FS->allocs())
518bdd1243dSDimitry Andric         for (auto &MIB : AI.MIBs)
519bdd1243dSDimitry Andric           for (auto Idx : MIB.StackIdIndices)
520*0fca6ea1SDimitry Andric             RecordStackIdReference(Idx);
5210b57cec5SDimitry Andric     });
5220b57cec5SDimitry Andric   }
5230b57cec5SDimitry Andric 
5240b57cec5SDimitry Andric   /// The below iterator returns the GUID and associated summary.
5250b57cec5SDimitry Andric   using GVInfo = std::pair<GlobalValue::GUID, GlobalValueSummary *>;
5260b57cec5SDimitry Andric 
5270b57cec5SDimitry Andric   /// Calls the callback for each value GUID and summary to be written to
5280b57cec5SDimitry Andric   /// bitcode. This hides the details of whether they are being pulled from the
5290b57cec5SDimitry Andric   /// entire index or just those in a provided ModuleToSummariesForIndex map.
5300b57cec5SDimitry Andric   template<typename Functor>
5310b57cec5SDimitry Andric   void forEachSummary(Functor Callback) {
5320b57cec5SDimitry Andric     if (ModuleToSummariesForIndex) {
5330b57cec5SDimitry Andric       for (auto &M : *ModuleToSummariesForIndex)
5340b57cec5SDimitry Andric         for (auto &Summary : M.second) {
5350b57cec5SDimitry Andric           Callback(Summary, false);
5360b57cec5SDimitry Andric           // Ensure aliasee is handled, e.g. for assigning a valueId,
5370b57cec5SDimitry Andric           // even if we are not importing the aliasee directly (the
5380b57cec5SDimitry Andric           // imported alias will contain a copy of aliasee).
5390b57cec5SDimitry Andric           if (auto *AS = dyn_cast<AliasSummary>(Summary.getSecond()))
5400b57cec5SDimitry Andric             Callback({AS->getAliaseeGUID(), &AS->getAliasee()}, true);
5410b57cec5SDimitry Andric         }
5420b57cec5SDimitry Andric     } else {
5430b57cec5SDimitry Andric       for (auto &Summaries : Index)
5440b57cec5SDimitry Andric         for (auto &Summary : Summaries.second.SummaryList)
5450b57cec5SDimitry Andric           Callback({Summaries.first, Summary.get()}, false);
5460b57cec5SDimitry Andric     }
5470b57cec5SDimitry Andric   }
5480b57cec5SDimitry Andric 
5490b57cec5SDimitry Andric   /// Calls the callback for each entry in the modulePaths StringMap that
5500b57cec5SDimitry Andric   /// should be written to the module path string table. This hides the details
5510b57cec5SDimitry Andric   /// of whether they are being pulled from the entire index or just those in a
5520b57cec5SDimitry Andric   /// provided ModuleToSummariesForIndex map.
5530b57cec5SDimitry Andric   template <typename Functor> void forEachModule(Functor Callback) {
5540b57cec5SDimitry Andric     if (ModuleToSummariesForIndex) {
5550b57cec5SDimitry Andric       for (const auto &M : *ModuleToSummariesForIndex) {
5560b57cec5SDimitry Andric         const auto &MPI = Index.modulePaths().find(M.first);
5570b57cec5SDimitry Andric         if (MPI == Index.modulePaths().end()) {
5580b57cec5SDimitry Andric           // This should only happen if the bitcode file was empty, in which
5590b57cec5SDimitry Andric           // case we shouldn't be importing (the ModuleToSummariesForIndex
5600b57cec5SDimitry Andric           // would only include the module we are writing and index for).
5610b57cec5SDimitry Andric           assert(ModuleToSummariesForIndex->size() == 1);
5620b57cec5SDimitry Andric           continue;
5630b57cec5SDimitry Andric         }
5640b57cec5SDimitry Andric         Callback(*MPI);
5650b57cec5SDimitry Andric       }
5660b57cec5SDimitry Andric     } else {
5675f757f3fSDimitry Andric       // Since StringMap iteration order isn't guaranteed, order by path string
5685f757f3fSDimitry Andric       // first.
5695f757f3fSDimitry Andric       // FIXME: Make this a vector of StringMapEntry instead to avoid the later
5705f757f3fSDimitry Andric       // map lookup.
5715f757f3fSDimitry Andric       std::vector<StringRef> ModulePaths;
5725f757f3fSDimitry Andric       for (auto &[ModPath, _] : Index.modulePaths())
5735f757f3fSDimitry Andric         ModulePaths.push_back(ModPath);
5745f757f3fSDimitry Andric       llvm::sort(ModulePaths.begin(), ModulePaths.end());
5755f757f3fSDimitry Andric       for (auto &ModPath : ModulePaths)
5765f757f3fSDimitry Andric         Callback(*Index.modulePaths().find(ModPath));
5770b57cec5SDimitry Andric     }
5780b57cec5SDimitry Andric   }
5790b57cec5SDimitry Andric 
5800b57cec5SDimitry Andric   /// Main entry point for writing a combined index to bitcode.
5810b57cec5SDimitry Andric   void write();
5820b57cec5SDimitry Andric 
5830b57cec5SDimitry Andric private:
5840b57cec5SDimitry Andric   void writeModStrings();
5850b57cec5SDimitry Andric   void writeCombinedGlobalValueSummary();
5860b57cec5SDimitry Andric 
587bdd1243dSDimitry Andric   std::optional<unsigned> getValueId(GlobalValue::GUID ValGUID) {
5880b57cec5SDimitry Andric     auto VMI = GUIDToValueIdMap.find(ValGUID);
5890b57cec5SDimitry Andric     if (VMI == GUIDToValueIdMap.end())
590bdd1243dSDimitry Andric       return std::nullopt;
5910b57cec5SDimitry Andric     return VMI->second;
5920b57cec5SDimitry Andric   }
5930b57cec5SDimitry Andric 
5940b57cec5SDimitry Andric   std::map<GlobalValue::GUID, unsigned> &valueIds() { return GUIDToValueIdMap; }
5950b57cec5SDimitry Andric };
5960b57cec5SDimitry Andric 
5970b57cec5SDimitry Andric } // end anonymous namespace
5980b57cec5SDimitry Andric 
5990b57cec5SDimitry Andric static unsigned getEncodedCastOpcode(unsigned Opcode) {
6000b57cec5SDimitry Andric   switch (Opcode) {
6010b57cec5SDimitry Andric   default: llvm_unreachable("Unknown cast instruction!");
6020b57cec5SDimitry Andric   case Instruction::Trunc   : return bitc::CAST_TRUNC;
6030b57cec5SDimitry Andric   case Instruction::ZExt    : return bitc::CAST_ZEXT;
6040b57cec5SDimitry Andric   case Instruction::SExt    : return bitc::CAST_SEXT;
6050b57cec5SDimitry Andric   case Instruction::FPToUI  : return bitc::CAST_FPTOUI;
6060b57cec5SDimitry Andric   case Instruction::FPToSI  : return bitc::CAST_FPTOSI;
6070b57cec5SDimitry Andric   case Instruction::UIToFP  : return bitc::CAST_UITOFP;
6080b57cec5SDimitry Andric   case Instruction::SIToFP  : return bitc::CAST_SITOFP;
6090b57cec5SDimitry Andric   case Instruction::FPTrunc : return bitc::CAST_FPTRUNC;
6100b57cec5SDimitry Andric   case Instruction::FPExt   : return bitc::CAST_FPEXT;
6110b57cec5SDimitry Andric   case Instruction::PtrToInt: return bitc::CAST_PTRTOINT;
6120b57cec5SDimitry Andric   case Instruction::IntToPtr: return bitc::CAST_INTTOPTR;
6130b57cec5SDimitry Andric   case Instruction::BitCast : return bitc::CAST_BITCAST;
6140b57cec5SDimitry Andric   case Instruction::AddrSpaceCast: return bitc::CAST_ADDRSPACECAST;
6150b57cec5SDimitry Andric   }
6160b57cec5SDimitry Andric }
6170b57cec5SDimitry Andric 
6180b57cec5SDimitry Andric static unsigned getEncodedUnaryOpcode(unsigned Opcode) {
6190b57cec5SDimitry Andric   switch (Opcode) {
6200b57cec5SDimitry Andric   default: llvm_unreachable("Unknown binary instruction!");
6218bcb0991SDimitry Andric   case Instruction::FNeg: return bitc::UNOP_FNEG;
6220b57cec5SDimitry Andric   }
6230b57cec5SDimitry Andric }
6240b57cec5SDimitry Andric 
6250b57cec5SDimitry Andric static unsigned getEncodedBinaryOpcode(unsigned Opcode) {
6260b57cec5SDimitry Andric   switch (Opcode) {
6270b57cec5SDimitry Andric   default: llvm_unreachable("Unknown binary instruction!");
6280b57cec5SDimitry Andric   case Instruction::Add:
6290b57cec5SDimitry Andric   case Instruction::FAdd: return bitc::BINOP_ADD;
6300b57cec5SDimitry Andric   case Instruction::Sub:
6310b57cec5SDimitry Andric   case Instruction::FSub: return bitc::BINOP_SUB;
6320b57cec5SDimitry Andric   case Instruction::Mul:
6330b57cec5SDimitry Andric   case Instruction::FMul: return bitc::BINOP_MUL;
6340b57cec5SDimitry Andric   case Instruction::UDiv: return bitc::BINOP_UDIV;
6350b57cec5SDimitry Andric   case Instruction::FDiv:
6360b57cec5SDimitry Andric   case Instruction::SDiv: return bitc::BINOP_SDIV;
6370b57cec5SDimitry Andric   case Instruction::URem: return bitc::BINOP_UREM;
6380b57cec5SDimitry Andric   case Instruction::FRem:
6390b57cec5SDimitry Andric   case Instruction::SRem: return bitc::BINOP_SREM;
6400b57cec5SDimitry Andric   case Instruction::Shl:  return bitc::BINOP_SHL;
6410b57cec5SDimitry Andric   case Instruction::LShr: return bitc::BINOP_LSHR;
6420b57cec5SDimitry Andric   case Instruction::AShr: return bitc::BINOP_ASHR;
6430b57cec5SDimitry Andric   case Instruction::And:  return bitc::BINOP_AND;
6440b57cec5SDimitry Andric   case Instruction::Or:   return bitc::BINOP_OR;
6450b57cec5SDimitry Andric   case Instruction::Xor:  return bitc::BINOP_XOR;
6460b57cec5SDimitry Andric   }
6470b57cec5SDimitry Andric }
6480b57cec5SDimitry Andric 
6490b57cec5SDimitry Andric static unsigned getEncodedRMWOperation(AtomicRMWInst::BinOp Op) {
6500b57cec5SDimitry Andric   switch (Op) {
6510b57cec5SDimitry Andric   default: llvm_unreachable("Unknown RMW operation!");
6520b57cec5SDimitry Andric   case AtomicRMWInst::Xchg: return bitc::RMW_XCHG;
6530b57cec5SDimitry Andric   case AtomicRMWInst::Add: return bitc::RMW_ADD;
6540b57cec5SDimitry Andric   case AtomicRMWInst::Sub: return bitc::RMW_SUB;
6550b57cec5SDimitry Andric   case AtomicRMWInst::And: return bitc::RMW_AND;
6560b57cec5SDimitry Andric   case AtomicRMWInst::Nand: return bitc::RMW_NAND;
6570b57cec5SDimitry Andric   case AtomicRMWInst::Or: return bitc::RMW_OR;
6580b57cec5SDimitry Andric   case AtomicRMWInst::Xor: return bitc::RMW_XOR;
6590b57cec5SDimitry Andric   case AtomicRMWInst::Max: return bitc::RMW_MAX;
6600b57cec5SDimitry Andric   case AtomicRMWInst::Min: return bitc::RMW_MIN;
6610b57cec5SDimitry Andric   case AtomicRMWInst::UMax: return bitc::RMW_UMAX;
6620b57cec5SDimitry Andric   case AtomicRMWInst::UMin: return bitc::RMW_UMIN;
6630b57cec5SDimitry Andric   case AtomicRMWInst::FAdd: return bitc::RMW_FADD;
6640b57cec5SDimitry Andric   case AtomicRMWInst::FSub: return bitc::RMW_FSUB;
665753f127fSDimitry Andric   case AtomicRMWInst::FMax: return bitc::RMW_FMAX;
666753f127fSDimitry Andric   case AtomicRMWInst::FMin: return bitc::RMW_FMIN;
667bdd1243dSDimitry Andric   case AtomicRMWInst::UIncWrap:
668bdd1243dSDimitry Andric     return bitc::RMW_UINC_WRAP;
669bdd1243dSDimitry Andric   case AtomicRMWInst::UDecWrap:
670bdd1243dSDimitry Andric     return bitc::RMW_UDEC_WRAP;
6710b57cec5SDimitry Andric   }
6720b57cec5SDimitry Andric }
6730b57cec5SDimitry Andric 
6740b57cec5SDimitry Andric static unsigned getEncodedOrdering(AtomicOrdering Ordering) {
6750b57cec5SDimitry Andric   switch (Ordering) {
6760b57cec5SDimitry Andric   case AtomicOrdering::NotAtomic: return bitc::ORDERING_NOTATOMIC;
6770b57cec5SDimitry Andric   case AtomicOrdering::Unordered: return bitc::ORDERING_UNORDERED;
6780b57cec5SDimitry Andric   case AtomicOrdering::Monotonic: return bitc::ORDERING_MONOTONIC;
6790b57cec5SDimitry Andric   case AtomicOrdering::Acquire: return bitc::ORDERING_ACQUIRE;
6800b57cec5SDimitry Andric   case AtomicOrdering::Release: return bitc::ORDERING_RELEASE;
6810b57cec5SDimitry Andric   case AtomicOrdering::AcquireRelease: return bitc::ORDERING_ACQREL;
6820b57cec5SDimitry Andric   case AtomicOrdering::SequentiallyConsistent: return bitc::ORDERING_SEQCST;
6830b57cec5SDimitry Andric   }
6840b57cec5SDimitry Andric   llvm_unreachable("Invalid ordering");
6850b57cec5SDimitry Andric }
6860b57cec5SDimitry Andric 
6870b57cec5SDimitry Andric static void writeStringRecord(BitstreamWriter &Stream, unsigned Code,
6880b57cec5SDimitry Andric                               StringRef Str, unsigned AbbrevToUse) {
6890b57cec5SDimitry Andric   SmallVector<unsigned, 64> Vals;
6900b57cec5SDimitry Andric 
6910b57cec5SDimitry Andric   // Code: [strchar x N]
6924824e7fdSDimitry Andric   for (char C : Str) {
6934824e7fdSDimitry Andric     if (AbbrevToUse && !BitCodeAbbrevOp::isChar6(C))
6940b57cec5SDimitry Andric       AbbrevToUse = 0;
6954824e7fdSDimitry Andric     Vals.push_back(C);
6960b57cec5SDimitry Andric   }
6970b57cec5SDimitry Andric 
6980b57cec5SDimitry Andric   // Emit the finished record.
6990b57cec5SDimitry Andric   Stream.EmitRecord(Code, Vals, AbbrevToUse);
7000b57cec5SDimitry Andric }
7010b57cec5SDimitry Andric 
7020b57cec5SDimitry Andric static uint64_t getAttrKindEncoding(Attribute::AttrKind Kind) {
7030b57cec5SDimitry Andric   switch (Kind) {
7040b57cec5SDimitry Andric   case Attribute::Alignment:
7050b57cec5SDimitry Andric     return bitc::ATTR_KIND_ALIGNMENT;
70681ad6265SDimitry Andric   case Attribute::AllocAlign:
70781ad6265SDimitry Andric     return bitc::ATTR_KIND_ALLOC_ALIGN;
7080b57cec5SDimitry Andric   case Attribute::AllocSize:
7090b57cec5SDimitry Andric     return bitc::ATTR_KIND_ALLOC_SIZE;
7100b57cec5SDimitry Andric   case Attribute::AlwaysInline:
7110b57cec5SDimitry Andric     return bitc::ATTR_KIND_ALWAYS_INLINE;
7120b57cec5SDimitry Andric   case Attribute::Builtin:
7130b57cec5SDimitry Andric     return bitc::ATTR_KIND_BUILTIN;
7140b57cec5SDimitry Andric   case Attribute::ByVal:
7150b57cec5SDimitry Andric     return bitc::ATTR_KIND_BY_VAL;
7160b57cec5SDimitry Andric   case Attribute::Convergent:
7170b57cec5SDimitry Andric     return bitc::ATTR_KIND_CONVERGENT;
7180b57cec5SDimitry Andric   case Attribute::InAlloca:
7190b57cec5SDimitry Andric     return bitc::ATTR_KIND_IN_ALLOCA;
7200b57cec5SDimitry Andric   case Attribute::Cold:
7210b57cec5SDimitry Andric     return bitc::ATTR_KIND_COLD;
722349cc55cSDimitry Andric   case Attribute::DisableSanitizerInstrumentation:
723349cc55cSDimitry Andric     return bitc::ATTR_KIND_DISABLE_SANITIZER_INSTRUMENTATION;
724753f127fSDimitry Andric   case Attribute::FnRetThunkExtern:
725753f127fSDimitry Andric     return bitc::ATTR_KIND_FNRETTHUNK_EXTERN;
726e8d8bef9SDimitry Andric   case Attribute::Hot:
727e8d8bef9SDimitry Andric     return bitc::ATTR_KIND_HOT;
728fe6060f1SDimitry Andric   case Attribute::ElementType:
729fe6060f1SDimitry Andric     return bitc::ATTR_KIND_ELEMENTTYPE;
730*0fca6ea1SDimitry Andric   case Attribute::HybridPatchable:
731*0fca6ea1SDimitry Andric     return bitc::ATTR_KIND_HYBRID_PATCHABLE;
7320b57cec5SDimitry Andric   case Attribute::InlineHint:
7330b57cec5SDimitry Andric     return bitc::ATTR_KIND_INLINE_HINT;
7340b57cec5SDimitry Andric   case Attribute::InReg:
7350b57cec5SDimitry Andric     return bitc::ATTR_KIND_IN_REG;
7360b57cec5SDimitry Andric   case Attribute::JumpTable:
7370b57cec5SDimitry Andric     return bitc::ATTR_KIND_JUMP_TABLE;
7380b57cec5SDimitry Andric   case Attribute::MinSize:
7390b57cec5SDimitry Andric     return bitc::ATTR_KIND_MIN_SIZE;
74081ad6265SDimitry Andric   case Attribute::AllocatedPointer:
74181ad6265SDimitry Andric     return bitc::ATTR_KIND_ALLOCATED_POINTER;
74281ad6265SDimitry Andric   case Attribute::AllocKind:
74381ad6265SDimitry Andric     return bitc::ATTR_KIND_ALLOC_KIND;
744bdd1243dSDimitry Andric   case Attribute::Memory:
745bdd1243dSDimitry Andric     return bitc::ATTR_KIND_MEMORY;
74606c3fb27SDimitry Andric   case Attribute::NoFPClass:
74706c3fb27SDimitry Andric     return bitc::ATTR_KIND_NOFPCLASS;
7480b57cec5SDimitry Andric   case Attribute::Naked:
7490b57cec5SDimitry Andric     return bitc::ATTR_KIND_NAKED;
7500b57cec5SDimitry Andric   case Attribute::Nest:
7510b57cec5SDimitry Andric     return bitc::ATTR_KIND_NEST;
7520b57cec5SDimitry Andric   case Attribute::NoAlias:
7530b57cec5SDimitry Andric     return bitc::ATTR_KIND_NO_ALIAS;
7540b57cec5SDimitry Andric   case Attribute::NoBuiltin:
7550b57cec5SDimitry Andric     return bitc::ATTR_KIND_NO_BUILTIN;
756e8d8bef9SDimitry Andric   case Attribute::NoCallback:
757e8d8bef9SDimitry Andric     return bitc::ATTR_KIND_NO_CALLBACK;
7580b57cec5SDimitry Andric   case Attribute::NoCapture:
7590b57cec5SDimitry Andric     return bitc::ATTR_KIND_NO_CAPTURE;
7600b57cec5SDimitry Andric   case Attribute::NoDuplicate:
7610b57cec5SDimitry Andric     return bitc::ATTR_KIND_NO_DUPLICATE;
7620b57cec5SDimitry Andric   case Attribute::NoFree:
7630b57cec5SDimitry Andric     return bitc::ATTR_KIND_NOFREE;
7640b57cec5SDimitry Andric   case Attribute::NoImplicitFloat:
7650b57cec5SDimitry Andric     return bitc::ATTR_KIND_NO_IMPLICIT_FLOAT;
7660b57cec5SDimitry Andric   case Attribute::NoInline:
7670b57cec5SDimitry Andric     return bitc::ATTR_KIND_NO_INLINE;
7680b57cec5SDimitry Andric   case Attribute::NoRecurse:
7690b57cec5SDimitry Andric     return bitc::ATTR_KIND_NO_RECURSE;
7705ffd83dbSDimitry Andric   case Attribute::NoMerge:
7715ffd83dbSDimitry Andric     return bitc::ATTR_KIND_NO_MERGE;
7720b57cec5SDimitry Andric   case Attribute::NonLazyBind:
7730b57cec5SDimitry Andric     return bitc::ATTR_KIND_NON_LAZY_BIND;
7740b57cec5SDimitry Andric   case Attribute::NonNull:
7750b57cec5SDimitry Andric     return bitc::ATTR_KIND_NON_NULL;
7760b57cec5SDimitry Andric   case Attribute::Dereferenceable:
7770b57cec5SDimitry Andric     return bitc::ATTR_KIND_DEREFERENCEABLE;
7780b57cec5SDimitry Andric   case Attribute::DereferenceableOrNull:
7790b57cec5SDimitry Andric     return bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL;
7800b57cec5SDimitry Andric   case Attribute::NoRedZone:
7810b57cec5SDimitry Andric     return bitc::ATTR_KIND_NO_RED_ZONE;
7820b57cec5SDimitry Andric   case Attribute::NoReturn:
7830b57cec5SDimitry Andric     return bitc::ATTR_KIND_NO_RETURN;
7840b57cec5SDimitry Andric   case Attribute::NoSync:
7850b57cec5SDimitry Andric     return bitc::ATTR_KIND_NOSYNC;
7860b57cec5SDimitry Andric   case Attribute::NoCfCheck:
7870b57cec5SDimitry Andric     return bitc::ATTR_KIND_NOCF_CHECK;
788e8d8bef9SDimitry Andric   case Attribute::NoProfile:
789e8d8bef9SDimitry Andric     return bitc::ATTR_KIND_NO_PROFILE;
790bdd1243dSDimitry Andric   case Attribute::SkipProfile:
791bdd1243dSDimitry Andric     return bitc::ATTR_KIND_SKIP_PROFILE;
7920b57cec5SDimitry Andric   case Attribute::NoUnwind:
7930b57cec5SDimitry Andric     return bitc::ATTR_KIND_NO_UNWIND;
79481ad6265SDimitry Andric   case Attribute::NoSanitizeBounds:
79581ad6265SDimitry Andric     return bitc::ATTR_KIND_NO_SANITIZE_BOUNDS;
796fe6060f1SDimitry Andric   case Attribute::NoSanitizeCoverage:
797fe6060f1SDimitry Andric     return bitc::ATTR_KIND_NO_SANITIZE_COVERAGE;
7985ffd83dbSDimitry Andric   case Attribute::NullPointerIsValid:
7995ffd83dbSDimitry Andric     return bitc::ATTR_KIND_NULL_POINTER_IS_VALID;
8005f757f3fSDimitry Andric   case Attribute::OptimizeForDebugging:
8015f757f3fSDimitry Andric     return bitc::ATTR_KIND_OPTIMIZE_FOR_DEBUGGING;
8020b57cec5SDimitry Andric   case Attribute::OptForFuzzing:
8030b57cec5SDimitry Andric     return bitc::ATTR_KIND_OPT_FOR_FUZZING;
8040b57cec5SDimitry Andric   case Attribute::OptimizeForSize:
8050b57cec5SDimitry Andric     return bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE;
8060b57cec5SDimitry Andric   case Attribute::OptimizeNone:
8070b57cec5SDimitry Andric     return bitc::ATTR_KIND_OPTIMIZE_NONE;
8080b57cec5SDimitry Andric   case Attribute::ReadNone:
8090b57cec5SDimitry Andric     return bitc::ATTR_KIND_READ_NONE;
8100b57cec5SDimitry Andric   case Attribute::ReadOnly:
8110b57cec5SDimitry Andric     return bitc::ATTR_KIND_READ_ONLY;
8120b57cec5SDimitry Andric   case Attribute::Returned:
8130b57cec5SDimitry Andric     return bitc::ATTR_KIND_RETURNED;
8140b57cec5SDimitry Andric   case Attribute::ReturnsTwice:
8150b57cec5SDimitry Andric     return bitc::ATTR_KIND_RETURNS_TWICE;
8160b57cec5SDimitry Andric   case Attribute::SExt:
8170b57cec5SDimitry Andric     return bitc::ATTR_KIND_S_EXT;
8180b57cec5SDimitry Andric   case Attribute::Speculatable:
8190b57cec5SDimitry Andric     return bitc::ATTR_KIND_SPECULATABLE;
8200b57cec5SDimitry Andric   case Attribute::StackAlignment:
8210b57cec5SDimitry Andric     return bitc::ATTR_KIND_STACK_ALIGNMENT;
8220b57cec5SDimitry Andric   case Attribute::StackProtect:
8230b57cec5SDimitry Andric     return bitc::ATTR_KIND_STACK_PROTECT;
8240b57cec5SDimitry Andric   case Attribute::StackProtectReq:
8250b57cec5SDimitry Andric     return bitc::ATTR_KIND_STACK_PROTECT_REQ;
8260b57cec5SDimitry Andric   case Attribute::StackProtectStrong:
8270b57cec5SDimitry Andric     return bitc::ATTR_KIND_STACK_PROTECT_STRONG;
8280b57cec5SDimitry Andric   case Attribute::SafeStack:
8290b57cec5SDimitry Andric     return bitc::ATTR_KIND_SAFESTACK;
8300b57cec5SDimitry Andric   case Attribute::ShadowCallStack:
8310b57cec5SDimitry Andric     return bitc::ATTR_KIND_SHADOWCALLSTACK;
8320b57cec5SDimitry Andric   case Attribute::StrictFP:
8330b57cec5SDimitry Andric     return bitc::ATTR_KIND_STRICT_FP;
8340b57cec5SDimitry Andric   case Attribute::StructRet:
8350b57cec5SDimitry Andric     return bitc::ATTR_KIND_STRUCT_RET;
8360b57cec5SDimitry Andric   case Attribute::SanitizeAddress:
8370b57cec5SDimitry Andric     return bitc::ATTR_KIND_SANITIZE_ADDRESS;
8380b57cec5SDimitry Andric   case Attribute::SanitizeHWAddress:
8390b57cec5SDimitry Andric     return bitc::ATTR_KIND_SANITIZE_HWADDRESS;
8400b57cec5SDimitry Andric   case Attribute::SanitizeThread:
8410b57cec5SDimitry Andric     return bitc::ATTR_KIND_SANITIZE_THREAD;
8420b57cec5SDimitry Andric   case Attribute::SanitizeMemory:
8430b57cec5SDimitry Andric     return bitc::ATTR_KIND_SANITIZE_MEMORY;
844*0fca6ea1SDimitry Andric   case Attribute::SanitizeNumericalStability:
845*0fca6ea1SDimitry Andric     return bitc::ATTR_KIND_SANITIZE_NUMERICAL_STABILITY;
8460b57cec5SDimitry Andric   case Attribute::SpeculativeLoadHardening:
8470b57cec5SDimitry Andric     return bitc::ATTR_KIND_SPECULATIVE_LOAD_HARDENING;
8480b57cec5SDimitry Andric   case Attribute::SwiftError:
8490b57cec5SDimitry Andric     return bitc::ATTR_KIND_SWIFT_ERROR;
8500b57cec5SDimitry Andric   case Attribute::SwiftSelf:
8510b57cec5SDimitry Andric     return bitc::ATTR_KIND_SWIFT_SELF;
852fe6060f1SDimitry Andric   case Attribute::SwiftAsync:
853fe6060f1SDimitry Andric     return bitc::ATTR_KIND_SWIFT_ASYNC;
8540b57cec5SDimitry Andric   case Attribute::UWTable:
8550b57cec5SDimitry Andric     return bitc::ATTR_KIND_UW_TABLE;
856fe6060f1SDimitry Andric   case Attribute::VScaleRange:
857fe6060f1SDimitry Andric     return bitc::ATTR_KIND_VSCALE_RANGE;
8580b57cec5SDimitry Andric   case Attribute::WillReturn:
8590b57cec5SDimitry Andric     return bitc::ATTR_KIND_WILLRETURN;
8600b57cec5SDimitry Andric   case Attribute::WriteOnly:
8610b57cec5SDimitry Andric     return bitc::ATTR_KIND_WRITEONLY;
8620b57cec5SDimitry Andric   case Attribute::ZExt:
8630b57cec5SDimitry Andric     return bitc::ATTR_KIND_Z_EXT;
8640b57cec5SDimitry Andric   case Attribute::ImmArg:
8650b57cec5SDimitry Andric     return bitc::ATTR_KIND_IMMARG;
8660b57cec5SDimitry Andric   case Attribute::SanitizeMemTag:
8670b57cec5SDimitry Andric     return bitc::ATTR_KIND_SANITIZE_MEMTAG;
8685ffd83dbSDimitry Andric   case Attribute::Preallocated:
8695ffd83dbSDimitry Andric     return bitc::ATTR_KIND_PREALLOCATED;
8705ffd83dbSDimitry Andric   case Attribute::NoUndef:
8715ffd83dbSDimitry Andric     return bitc::ATTR_KIND_NOUNDEF;
872e8d8bef9SDimitry Andric   case Attribute::ByRef:
873e8d8bef9SDimitry Andric     return bitc::ATTR_KIND_BYREF;
874e8d8bef9SDimitry Andric   case Attribute::MustProgress:
875e8d8bef9SDimitry Andric     return bitc::ATTR_KIND_MUSTPROGRESS;
87681ad6265SDimitry Andric   case Attribute::PresplitCoroutine:
87781ad6265SDimitry Andric     return bitc::ATTR_KIND_PRESPLIT_COROUTINE;
8785f757f3fSDimitry Andric   case Attribute::Writable:
8795f757f3fSDimitry Andric     return bitc::ATTR_KIND_WRITABLE;
8805f757f3fSDimitry Andric   case Attribute::CoroDestroyOnlyWhenComplete:
8815f757f3fSDimitry Andric     return bitc::ATTR_KIND_CORO_ONLY_DESTROY_WHEN_COMPLETE;
8825f757f3fSDimitry Andric   case Attribute::DeadOnUnwind:
8835f757f3fSDimitry Andric     return bitc::ATTR_KIND_DEAD_ON_UNWIND;
884*0fca6ea1SDimitry Andric   case Attribute::Range:
885*0fca6ea1SDimitry Andric     return bitc::ATTR_KIND_RANGE;
886*0fca6ea1SDimitry Andric   case Attribute::Initializes:
887*0fca6ea1SDimitry Andric     return bitc::ATTR_KIND_INITIALIZES;
8880b57cec5SDimitry Andric   case Attribute::EndAttrKinds:
8890b57cec5SDimitry Andric     llvm_unreachable("Can not encode end-attribute kinds marker.");
8900b57cec5SDimitry Andric   case Attribute::None:
8910b57cec5SDimitry Andric     llvm_unreachable("Can not encode none-attribute.");
8925ffd83dbSDimitry Andric   case Attribute::EmptyKey:
8935ffd83dbSDimitry Andric   case Attribute::TombstoneKey:
8945ffd83dbSDimitry Andric     llvm_unreachable("Trying to encode EmptyKey/TombstoneKey");
8950b57cec5SDimitry Andric   }
8960b57cec5SDimitry Andric 
8970b57cec5SDimitry Andric   llvm_unreachable("Trying to encode unknown attribute");
8980b57cec5SDimitry Andric }
8990b57cec5SDimitry Andric 
900*0fca6ea1SDimitry Andric static void emitSignedInt64(SmallVectorImpl<uint64_t> &Vals, uint64_t V) {
901*0fca6ea1SDimitry Andric   if ((int64_t)V >= 0)
902*0fca6ea1SDimitry Andric     Vals.push_back(V << 1);
903*0fca6ea1SDimitry Andric   else
904*0fca6ea1SDimitry Andric     Vals.push_back((-V << 1) | 1);
905*0fca6ea1SDimitry Andric }
906*0fca6ea1SDimitry Andric 
907*0fca6ea1SDimitry Andric static void emitWideAPInt(SmallVectorImpl<uint64_t> &Vals, const APInt &A) {
908*0fca6ea1SDimitry Andric   // We have an arbitrary precision integer value to write whose
909*0fca6ea1SDimitry Andric   // bit width is > 64. However, in canonical unsigned integer
910*0fca6ea1SDimitry Andric   // format it is likely that the high bits are going to be zero.
911*0fca6ea1SDimitry Andric   // So, we only write the number of active words.
912*0fca6ea1SDimitry Andric   unsigned NumWords = A.getActiveWords();
913*0fca6ea1SDimitry Andric   const uint64_t *RawData = A.getRawData();
914*0fca6ea1SDimitry Andric   for (unsigned i = 0; i < NumWords; i++)
915*0fca6ea1SDimitry Andric     emitSignedInt64(Vals, RawData[i]);
916*0fca6ea1SDimitry Andric }
917*0fca6ea1SDimitry Andric 
918*0fca6ea1SDimitry Andric static void emitConstantRange(SmallVectorImpl<uint64_t> &Record,
919*0fca6ea1SDimitry Andric                               const ConstantRange &CR, bool EmitBitWidth) {
920*0fca6ea1SDimitry Andric   unsigned BitWidth = CR.getBitWidth();
921*0fca6ea1SDimitry Andric   if (EmitBitWidth)
922*0fca6ea1SDimitry Andric     Record.push_back(BitWidth);
923*0fca6ea1SDimitry Andric   if (BitWidth > 64) {
924*0fca6ea1SDimitry Andric     Record.push_back(CR.getLower().getActiveWords() |
925*0fca6ea1SDimitry Andric                      (uint64_t(CR.getUpper().getActiveWords()) << 32));
926*0fca6ea1SDimitry Andric     emitWideAPInt(Record, CR.getLower());
927*0fca6ea1SDimitry Andric     emitWideAPInt(Record, CR.getUpper());
928*0fca6ea1SDimitry Andric   } else {
929*0fca6ea1SDimitry Andric     emitSignedInt64(Record, CR.getLower().getSExtValue());
930*0fca6ea1SDimitry Andric     emitSignedInt64(Record, CR.getUpper().getSExtValue());
931*0fca6ea1SDimitry Andric   }
932*0fca6ea1SDimitry Andric }
933*0fca6ea1SDimitry Andric 
9340b57cec5SDimitry Andric void ModuleBitcodeWriter::writeAttributeGroupTable() {
9350b57cec5SDimitry Andric   const std::vector<ValueEnumerator::IndexAndAttrSet> &AttrGrps =
9360b57cec5SDimitry Andric       VE.getAttributeGroups();
9370b57cec5SDimitry Andric   if (AttrGrps.empty()) return;
9380b57cec5SDimitry Andric 
9390b57cec5SDimitry Andric   Stream.EnterSubblock(bitc::PARAMATTR_GROUP_BLOCK_ID, 3);
9400b57cec5SDimitry Andric 
9410b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
9420b57cec5SDimitry Andric   for (ValueEnumerator::IndexAndAttrSet Pair : AttrGrps) {
9430b57cec5SDimitry Andric     unsigned AttrListIndex = Pair.first;
9440b57cec5SDimitry Andric     AttributeSet AS = Pair.second;
9450b57cec5SDimitry Andric     Record.push_back(VE.getAttributeGroupID(Pair));
9460b57cec5SDimitry Andric     Record.push_back(AttrListIndex);
9470b57cec5SDimitry Andric 
9480b57cec5SDimitry Andric     for (Attribute Attr : AS) {
9490b57cec5SDimitry Andric       if (Attr.isEnumAttribute()) {
9500b57cec5SDimitry Andric         Record.push_back(0);
9510b57cec5SDimitry Andric         Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
9520b57cec5SDimitry Andric       } else if (Attr.isIntAttribute()) {
9530b57cec5SDimitry Andric         Record.push_back(1);
9540b57cec5SDimitry Andric         Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
9550b57cec5SDimitry Andric         Record.push_back(Attr.getValueAsInt());
9560b57cec5SDimitry Andric       } else if (Attr.isStringAttribute()) {
9570b57cec5SDimitry Andric         StringRef Kind = Attr.getKindAsString();
9580b57cec5SDimitry Andric         StringRef Val = Attr.getValueAsString();
9590b57cec5SDimitry Andric 
9600b57cec5SDimitry Andric         Record.push_back(Val.empty() ? 3 : 4);
9610b57cec5SDimitry Andric         Record.append(Kind.begin(), Kind.end());
9620b57cec5SDimitry Andric         Record.push_back(0);
9630b57cec5SDimitry Andric         if (!Val.empty()) {
9640b57cec5SDimitry Andric           Record.append(Val.begin(), Val.end());
9650b57cec5SDimitry Andric           Record.push_back(0);
9660b57cec5SDimitry Andric         }
967*0fca6ea1SDimitry Andric       } else if (Attr.isTypeAttribute()) {
9680b57cec5SDimitry Andric         Type *Ty = Attr.getValueAsType();
9690b57cec5SDimitry Andric         Record.push_back(Ty ? 6 : 5);
9700b57cec5SDimitry Andric         Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
9710b57cec5SDimitry Andric         if (Ty)
9720b57cec5SDimitry Andric           Record.push_back(VE.getTypeID(Attr.getValueAsType()));
973*0fca6ea1SDimitry Andric       } else if (Attr.isConstantRangeAttribute()) {
974*0fca6ea1SDimitry Andric         Record.push_back(7);
975*0fca6ea1SDimitry Andric         Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
976*0fca6ea1SDimitry Andric         emitConstantRange(Record, Attr.getValueAsConstantRange(),
977*0fca6ea1SDimitry Andric                           /*EmitBitWidth=*/true);
978*0fca6ea1SDimitry Andric       } else {
979*0fca6ea1SDimitry Andric         assert(Attr.isConstantRangeListAttribute());
980*0fca6ea1SDimitry Andric         Record.push_back(8);
981*0fca6ea1SDimitry Andric         Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
982*0fca6ea1SDimitry Andric         ArrayRef<ConstantRange> Val = Attr.getValueAsConstantRangeList();
983*0fca6ea1SDimitry Andric         Record.push_back(Val.size());
984*0fca6ea1SDimitry Andric         Record.push_back(Val[0].getBitWidth());
985*0fca6ea1SDimitry Andric         for (auto &CR : Val)
986*0fca6ea1SDimitry Andric           emitConstantRange(Record, CR, /*EmitBitWidth=*/false);
9870b57cec5SDimitry Andric       }
9880b57cec5SDimitry Andric     }
9890b57cec5SDimitry Andric 
9900b57cec5SDimitry Andric     Stream.EmitRecord(bitc::PARAMATTR_GRP_CODE_ENTRY, Record);
9910b57cec5SDimitry Andric     Record.clear();
9920b57cec5SDimitry Andric   }
9930b57cec5SDimitry Andric 
9940b57cec5SDimitry Andric   Stream.ExitBlock();
9950b57cec5SDimitry Andric }
9960b57cec5SDimitry Andric 
9970b57cec5SDimitry Andric void ModuleBitcodeWriter::writeAttributeTable() {
9980b57cec5SDimitry Andric   const std::vector<AttributeList> &Attrs = VE.getAttributeLists();
9990b57cec5SDimitry Andric   if (Attrs.empty()) return;
10000b57cec5SDimitry Andric 
10010b57cec5SDimitry Andric   Stream.EnterSubblock(bitc::PARAMATTR_BLOCK_ID, 3);
10020b57cec5SDimitry Andric 
10030b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
10040eae32dcSDimitry Andric   for (const AttributeList &AL : Attrs) {
1005349cc55cSDimitry Andric     for (unsigned i : AL.indexes()) {
10060b57cec5SDimitry Andric       AttributeSet AS = AL.getAttributes(i);
10070b57cec5SDimitry Andric       if (AS.hasAttributes())
10080b57cec5SDimitry Andric         Record.push_back(VE.getAttributeGroupID({i, AS}));
10090b57cec5SDimitry Andric     }
10100b57cec5SDimitry Andric 
10110b57cec5SDimitry Andric     Stream.EmitRecord(bitc::PARAMATTR_CODE_ENTRY, Record);
10120b57cec5SDimitry Andric     Record.clear();
10130b57cec5SDimitry Andric   }
10140b57cec5SDimitry Andric 
10150b57cec5SDimitry Andric   Stream.ExitBlock();
10160b57cec5SDimitry Andric }
10170b57cec5SDimitry Andric 
10180b57cec5SDimitry Andric /// WriteTypeTable - Write out the type table for a module.
10190b57cec5SDimitry Andric void ModuleBitcodeWriter::writeTypeTable() {
10200b57cec5SDimitry Andric   const ValueEnumerator::TypeList &TypeList = VE.getTypes();
10210b57cec5SDimitry Andric 
10220b57cec5SDimitry Andric   Stream.EnterSubblock(bitc::TYPE_BLOCK_ID_NEW, 4 /*count from # abbrevs */);
10230b57cec5SDimitry Andric   SmallVector<uint64_t, 64> TypeVals;
10240b57cec5SDimitry Andric 
1025*0fca6ea1SDimitry Andric   uint64_t NumBits = VE.computeBitsRequiredForTypeIndices();
10260b57cec5SDimitry Andric 
1027fe6060f1SDimitry Andric   // Abbrev for TYPE_CODE_OPAQUE_POINTER.
102806c3fb27SDimitry Andric   auto Abbv = std::make_shared<BitCodeAbbrev>();
1029fe6060f1SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_OPAQUE_POINTER));
1030fe6060f1SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(0)); // Addrspace = 0
1031fe6060f1SDimitry Andric   unsigned OpaquePtrAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1032fe6060f1SDimitry Andric 
10330b57cec5SDimitry Andric   // Abbrev for TYPE_CODE_FUNCTION.
10340b57cec5SDimitry Andric   Abbv = std::make_shared<BitCodeAbbrev>();
10350b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_FUNCTION));
10360b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));  // isvararg
10370b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
10380b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
10390b57cec5SDimitry Andric   unsigned FunctionAbbrev = Stream.EmitAbbrev(std::move(Abbv));
10400b57cec5SDimitry Andric 
10410b57cec5SDimitry Andric   // Abbrev for TYPE_CODE_STRUCT_ANON.
10420b57cec5SDimitry Andric   Abbv = std::make_shared<BitCodeAbbrev>();
10430b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_ANON));
10440b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));  // ispacked
10450b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
10460b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
10470b57cec5SDimitry Andric   unsigned StructAnonAbbrev = Stream.EmitAbbrev(std::move(Abbv));
10480b57cec5SDimitry Andric 
10490b57cec5SDimitry Andric   // Abbrev for TYPE_CODE_STRUCT_NAME.
10500b57cec5SDimitry Andric   Abbv = std::make_shared<BitCodeAbbrev>();
10510b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAME));
10520b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
10530b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
10540b57cec5SDimitry Andric   unsigned StructNameAbbrev = Stream.EmitAbbrev(std::move(Abbv));
10550b57cec5SDimitry Andric 
10560b57cec5SDimitry Andric   // Abbrev for TYPE_CODE_STRUCT_NAMED.
10570b57cec5SDimitry Andric   Abbv = std::make_shared<BitCodeAbbrev>();
10580b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAMED));
10590b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));  // ispacked
10600b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
10610b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
10620b57cec5SDimitry Andric   unsigned StructNamedAbbrev = Stream.EmitAbbrev(std::move(Abbv));
10630b57cec5SDimitry Andric 
10640b57cec5SDimitry Andric   // Abbrev for TYPE_CODE_ARRAY.
10650b57cec5SDimitry Andric   Abbv = std::make_shared<BitCodeAbbrev>();
10660b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_ARRAY));
10670b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // size
10680b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
10690b57cec5SDimitry Andric   unsigned ArrayAbbrev = Stream.EmitAbbrev(std::move(Abbv));
10700b57cec5SDimitry Andric 
10710b57cec5SDimitry Andric   // Emit an entry count so the reader can reserve space.
10720b57cec5SDimitry Andric   TypeVals.push_back(TypeList.size());
10730b57cec5SDimitry Andric   Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals);
10740b57cec5SDimitry Andric   TypeVals.clear();
10750b57cec5SDimitry Andric 
10760b57cec5SDimitry Andric   // Loop over all of the types, emitting each in turn.
10774824e7fdSDimitry Andric   for (Type *T : TypeList) {
10780b57cec5SDimitry Andric     int AbbrevToUse = 0;
10790b57cec5SDimitry Andric     unsigned Code = 0;
10800b57cec5SDimitry Andric 
10810b57cec5SDimitry Andric     switch (T->getTypeID()) {
10820b57cec5SDimitry Andric     case Type::VoidTyID:      Code = bitc::TYPE_CODE_VOID;      break;
10830b57cec5SDimitry Andric     case Type::HalfTyID:      Code = bitc::TYPE_CODE_HALF;      break;
10845ffd83dbSDimitry Andric     case Type::BFloatTyID:    Code = bitc::TYPE_CODE_BFLOAT;    break;
10850b57cec5SDimitry Andric     case Type::FloatTyID:     Code = bitc::TYPE_CODE_FLOAT;     break;
10860b57cec5SDimitry Andric     case Type::DoubleTyID:    Code = bitc::TYPE_CODE_DOUBLE;    break;
10870b57cec5SDimitry Andric     case Type::X86_FP80TyID:  Code = bitc::TYPE_CODE_X86_FP80;  break;
10880b57cec5SDimitry Andric     case Type::FP128TyID:     Code = bitc::TYPE_CODE_FP128;     break;
10890b57cec5SDimitry Andric     case Type::PPC_FP128TyID: Code = bitc::TYPE_CODE_PPC_FP128; break;
10900b57cec5SDimitry Andric     case Type::LabelTyID:     Code = bitc::TYPE_CODE_LABEL;     break;
10910b57cec5SDimitry Andric     case Type::MetadataTyID:  Code = bitc::TYPE_CODE_METADATA;  break;
10920b57cec5SDimitry Andric     case Type::X86_MMXTyID:   Code = bitc::TYPE_CODE_X86_MMX;   break;
1093e8d8bef9SDimitry Andric     case Type::X86_AMXTyID:   Code = bitc::TYPE_CODE_X86_AMX;   break;
10940b57cec5SDimitry Andric     case Type::TokenTyID:     Code = bitc::TYPE_CODE_TOKEN;     break;
10950b57cec5SDimitry Andric     case Type::IntegerTyID:
10960b57cec5SDimitry Andric       // INTEGER: [width]
10970b57cec5SDimitry Andric       Code = bitc::TYPE_CODE_INTEGER;
10980b57cec5SDimitry Andric       TypeVals.push_back(cast<IntegerType>(T)->getBitWidth());
10990b57cec5SDimitry Andric       break;
11000b57cec5SDimitry Andric     case Type::PointerTyID: {
11010b57cec5SDimitry Andric       PointerType *PTy = cast<PointerType>(T);
1102fe6060f1SDimitry Andric       unsigned AddressSpace = PTy->getAddressSpace();
1103fe6060f1SDimitry Andric       // OPAQUE_POINTER: [address space]
1104fe6060f1SDimitry Andric       Code = bitc::TYPE_CODE_OPAQUE_POINTER;
1105fe6060f1SDimitry Andric       TypeVals.push_back(AddressSpace);
1106fe6060f1SDimitry Andric       if (AddressSpace == 0)
1107fe6060f1SDimitry Andric         AbbrevToUse = OpaquePtrAbbrev;
11080b57cec5SDimitry Andric       break;
11090b57cec5SDimitry Andric     }
11100b57cec5SDimitry Andric     case Type::FunctionTyID: {
11110b57cec5SDimitry Andric       FunctionType *FT = cast<FunctionType>(T);
11120b57cec5SDimitry Andric       // FUNCTION: [isvararg, retty, paramty x N]
11130b57cec5SDimitry Andric       Code = bitc::TYPE_CODE_FUNCTION;
11140b57cec5SDimitry Andric       TypeVals.push_back(FT->isVarArg());
11150b57cec5SDimitry Andric       TypeVals.push_back(VE.getTypeID(FT->getReturnType()));
11160b57cec5SDimitry Andric       for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
11170b57cec5SDimitry Andric         TypeVals.push_back(VE.getTypeID(FT->getParamType(i)));
11180b57cec5SDimitry Andric       AbbrevToUse = FunctionAbbrev;
11190b57cec5SDimitry Andric       break;
11200b57cec5SDimitry Andric     }
11210b57cec5SDimitry Andric     case Type::StructTyID: {
11220b57cec5SDimitry Andric       StructType *ST = cast<StructType>(T);
11230b57cec5SDimitry Andric       // STRUCT: [ispacked, eltty x N]
11240b57cec5SDimitry Andric       TypeVals.push_back(ST->isPacked());
11250b57cec5SDimitry Andric       // Output all of the element types.
1126349cc55cSDimitry Andric       for (Type *ET : ST->elements())
1127349cc55cSDimitry Andric         TypeVals.push_back(VE.getTypeID(ET));
11280b57cec5SDimitry Andric 
11290b57cec5SDimitry Andric       if (ST->isLiteral()) {
11300b57cec5SDimitry Andric         Code = bitc::TYPE_CODE_STRUCT_ANON;
11310b57cec5SDimitry Andric         AbbrevToUse = StructAnonAbbrev;
11320b57cec5SDimitry Andric       } else {
11330b57cec5SDimitry Andric         if (ST->isOpaque()) {
11340b57cec5SDimitry Andric           Code = bitc::TYPE_CODE_OPAQUE;
11350b57cec5SDimitry Andric         } else {
11360b57cec5SDimitry Andric           Code = bitc::TYPE_CODE_STRUCT_NAMED;
11370b57cec5SDimitry Andric           AbbrevToUse = StructNamedAbbrev;
11380b57cec5SDimitry Andric         }
11390b57cec5SDimitry Andric 
11400b57cec5SDimitry Andric         // Emit the name if it is present.
11410b57cec5SDimitry Andric         if (!ST->getName().empty())
11420b57cec5SDimitry Andric           writeStringRecord(Stream, bitc::TYPE_CODE_STRUCT_NAME, ST->getName(),
11430b57cec5SDimitry Andric                             StructNameAbbrev);
11440b57cec5SDimitry Andric       }
11450b57cec5SDimitry Andric       break;
11460b57cec5SDimitry Andric     }
11470b57cec5SDimitry Andric     case Type::ArrayTyID: {
11480b57cec5SDimitry Andric       ArrayType *AT = cast<ArrayType>(T);
11490b57cec5SDimitry Andric       // ARRAY: [numelts, eltty]
11500b57cec5SDimitry Andric       Code = bitc::TYPE_CODE_ARRAY;
11510b57cec5SDimitry Andric       TypeVals.push_back(AT->getNumElements());
11520b57cec5SDimitry Andric       TypeVals.push_back(VE.getTypeID(AT->getElementType()));
11530b57cec5SDimitry Andric       AbbrevToUse = ArrayAbbrev;
11540b57cec5SDimitry Andric       break;
11550b57cec5SDimitry Andric     }
11565ffd83dbSDimitry Andric     case Type::FixedVectorTyID:
11575ffd83dbSDimitry Andric     case Type::ScalableVectorTyID: {
11580b57cec5SDimitry Andric       VectorType *VT = cast<VectorType>(T);
11590b57cec5SDimitry Andric       // VECTOR [numelts, eltty] or
11600b57cec5SDimitry Andric       //        [numelts, eltty, scalable]
11610b57cec5SDimitry Andric       Code = bitc::TYPE_CODE_VECTOR;
1162e8d8bef9SDimitry Andric       TypeVals.push_back(VT->getElementCount().getKnownMinValue());
11630b57cec5SDimitry Andric       TypeVals.push_back(VE.getTypeID(VT->getElementType()));
11645ffd83dbSDimitry Andric       if (isa<ScalableVectorType>(VT))
11655ffd83dbSDimitry Andric         TypeVals.push_back(true);
11660b57cec5SDimitry Andric       break;
11670b57cec5SDimitry Andric     }
1168bdd1243dSDimitry Andric     case Type::TargetExtTyID: {
1169bdd1243dSDimitry Andric       TargetExtType *TET = cast<TargetExtType>(T);
1170bdd1243dSDimitry Andric       Code = bitc::TYPE_CODE_TARGET_TYPE;
1171bdd1243dSDimitry Andric       writeStringRecord(Stream, bitc::TYPE_CODE_STRUCT_NAME, TET->getName(),
1172bdd1243dSDimitry Andric                         StructNameAbbrev);
1173bdd1243dSDimitry Andric       TypeVals.push_back(TET->getNumTypeParameters());
1174bdd1243dSDimitry Andric       for (Type *InnerTy : TET->type_params())
1175bdd1243dSDimitry Andric         TypeVals.push_back(VE.getTypeID(InnerTy));
1176bdd1243dSDimitry Andric       for (unsigned IntParam : TET->int_params())
1177bdd1243dSDimitry Andric         TypeVals.push_back(IntParam);
1178bdd1243dSDimitry Andric       break;
1179bdd1243dSDimitry Andric     }
1180bdd1243dSDimitry Andric     case Type::TypedPointerTyID:
1181bdd1243dSDimitry Andric       llvm_unreachable("Typed pointers cannot be added to IR modules");
11820b57cec5SDimitry Andric     }
11830b57cec5SDimitry Andric 
11840b57cec5SDimitry Andric     // Emit the finished record.
11850b57cec5SDimitry Andric     Stream.EmitRecord(Code, TypeVals, AbbrevToUse);
11860b57cec5SDimitry Andric     TypeVals.clear();
11870b57cec5SDimitry Andric   }
11880b57cec5SDimitry Andric 
11890b57cec5SDimitry Andric   Stream.ExitBlock();
11900b57cec5SDimitry Andric }
11910b57cec5SDimitry Andric 
11920b57cec5SDimitry Andric static unsigned getEncodedLinkage(const GlobalValue::LinkageTypes Linkage) {
11930b57cec5SDimitry Andric   switch (Linkage) {
11940b57cec5SDimitry Andric   case GlobalValue::ExternalLinkage:
11950b57cec5SDimitry Andric     return 0;
11960b57cec5SDimitry Andric   case GlobalValue::WeakAnyLinkage:
11970b57cec5SDimitry Andric     return 16;
11980b57cec5SDimitry Andric   case GlobalValue::AppendingLinkage:
11990b57cec5SDimitry Andric     return 2;
12000b57cec5SDimitry Andric   case GlobalValue::InternalLinkage:
12010b57cec5SDimitry Andric     return 3;
12020b57cec5SDimitry Andric   case GlobalValue::LinkOnceAnyLinkage:
12030b57cec5SDimitry Andric     return 18;
12040b57cec5SDimitry Andric   case GlobalValue::ExternalWeakLinkage:
12050b57cec5SDimitry Andric     return 7;
12060b57cec5SDimitry Andric   case GlobalValue::CommonLinkage:
12070b57cec5SDimitry Andric     return 8;
12080b57cec5SDimitry Andric   case GlobalValue::PrivateLinkage:
12090b57cec5SDimitry Andric     return 9;
12100b57cec5SDimitry Andric   case GlobalValue::WeakODRLinkage:
12110b57cec5SDimitry Andric     return 17;
12120b57cec5SDimitry Andric   case GlobalValue::LinkOnceODRLinkage:
12130b57cec5SDimitry Andric     return 19;
12140b57cec5SDimitry Andric   case GlobalValue::AvailableExternallyLinkage:
12150b57cec5SDimitry Andric     return 12;
12160b57cec5SDimitry Andric   }
12170b57cec5SDimitry Andric   llvm_unreachable("Invalid linkage");
12180b57cec5SDimitry Andric }
12190b57cec5SDimitry Andric 
12200b57cec5SDimitry Andric static unsigned getEncodedLinkage(const GlobalValue &GV) {
12210b57cec5SDimitry Andric   return getEncodedLinkage(GV.getLinkage());
12220b57cec5SDimitry Andric }
12230b57cec5SDimitry Andric 
12240b57cec5SDimitry Andric static uint64_t getEncodedFFlags(FunctionSummary::FFlags Flags) {
12250b57cec5SDimitry Andric   uint64_t RawFlags = 0;
12260b57cec5SDimitry Andric   RawFlags |= Flags.ReadNone;
12270b57cec5SDimitry Andric   RawFlags |= (Flags.ReadOnly << 1);
12280b57cec5SDimitry Andric   RawFlags |= (Flags.NoRecurse << 2);
12290b57cec5SDimitry Andric   RawFlags |= (Flags.ReturnDoesNotAlias << 3);
12300b57cec5SDimitry Andric   RawFlags |= (Flags.NoInline << 4);
1231480093f4SDimitry Andric   RawFlags |= (Flags.AlwaysInline << 5);
1232349cc55cSDimitry Andric   RawFlags |= (Flags.NoUnwind << 6);
1233349cc55cSDimitry Andric   RawFlags |= (Flags.MayThrow << 7);
1234349cc55cSDimitry Andric   RawFlags |= (Flags.HasUnknownCall << 8);
12350eae32dcSDimitry Andric   RawFlags |= (Flags.MustBeUnreachable << 9);
12360b57cec5SDimitry Andric   return RawFlags;
12370b57cec5SDimitry Andric }
12380b57cec5SDimitry Andric 
1239fe6060f1SDimitry Andric // Decode the flags for GlobalValue in the summary. See getDecodedGVSummaryFlags
1240fe6060f1SDimitry Andric // in BitcodeReader.cpp.
1241*0fca6ea1SDimitry Andric static uint64_t getEncodedGVSummaryFlags(GlobalValueSummary::GVFlags Flags,
1242*0fca6ea1SDimitry Andric                                          bool ImportAsDecl = false) {
12430b57cec5SDimitry Andric   uint64_t RawFlags = 0;
12440b57cec5SDimitry Andric 
12450b57cec5SDimitry Andric   RawFlags |= Flags.NotEligibleToImport; // bool
12460b57cec5SDimitry Andric   RawFlags |= (Flags.Live << 1);
12470b57cec5SDimitry Andric   RawFlags |= (Flags.DSOLocal << 2);
12480b57cec5SDimitry Andric   RawFlags |= (Flags.CanAutoHide << 3);
12490b57cec5SDimitry Andric 
12500b57cec5SDimitry Andric   // Linkage don't need to be remapped at that time for the summary. Any future
12510b57cec5SDimitry Andric   // change to the getEncodedLinkage() function will need to be taken into
12520b57cec5SDimitry Andric   // account here as well.
12530b57cec5SDimitry Andric   RawFlags = (RawFlags << 4) | Flags.Linkage; // 4 bits
12540b57cec5SDimitry Andric 
1255fe6060f1SDimitry Andric   RawFlags |= (Flags.Visibility << 8); // 2 bits
1256fe6060f1SDimitry Andric 
1257*0fca6ea1SDimitry Andric   unsigned ImportType = Flags.ImportType | ImportAsDecl;
1258*0fca6ea1SDimitry Andric   RawFlags |= (ImportType << 10); // 1 bit
1259*0fca6ea1SDimitry Andric 
12600b57cec5SDimitry Andric   return RawFlags;
12610b57cec5SDimitry Andric }
12620b57cec5SDimitry Andric 
12630b57cec5SDimitry Andric static uint64_t getEncodedGVarFlags(GlobalVarSummary::GVarFlags Flags) {
12645ffd83dbSDimitry Andric   uint64_t RawFlags = Flags.MaybeReadOnly | (Flags.MaybeWriteOnly << 1) |
12655ffd83dbSDimitry Andric                       (Flags.Constant << 2) | Flags.VCallVisibility << 3;
12660b57cec5SDimitry Andric   return RawFlags;
12670b57cec5SDimitry Andric }
12680b57cec5SDimitry Andric 
12695f757f3fSDimitry Andric static uint64_t getEncodedHotnessCallEdgeInfo(const CalleeInfo &CI) {
12705f757f3fSDimitry Andric   uint64_t RawFlags = 0;
12715f757f3fSDimitry Andric 
12725f757f3fSDimitry Andric   RawFlags |= CI.Hotness;            // 3 bits
12735f757f3fSDimitry Andric   RawFlags |= (CI.HasTailCall << 3); // 1 bit
12745f757f3fSDimitry Andric 
12755f757f3fSDimitry Andric   return RawFlags;
12765f757f3fSDimitry Andric }
12775f757f3fSDimitry Andric 
12785f757f3fSDimitry Andric static uint64_t getEncodedRelBFCallEdgeInfo(const CalleeInfo &CI) {
12795f757f3fSDimitry Andric   uint64_t RawFlags = 0;
12805f757f3fSDimitry Andric 
12815f757f3fSDimitry Andric   RawFlags |= CI.RelBlockFreq; // CalleeInfo::RelBlockFreqBits bits
12825f757f3fSDimitry Andric   RawFlags |= (CI.HasTailCall << CalleeInfo::RelBlockFreqBits); // 1 bit
12835f757f3fSDimitry Andric 
12845f757f3fSDimitry Andric   return RawFlags;
12855f757f3fSDimitry Andric }
12865f757f3fSDimitry Andric 
12870b57cec5SDimitry Andric static unsigned getEncodedVisibility(const GlobalValue &GV) {
12880b57cec5SDimitry Andric   switch (GV.getVisibility()) {
12890b57cec5SDimitry Andric   case GlobalValue::DefaultVisibility:   return 0;
12900b57cec5SDimitry Andric   case GlobalValue::HiddenVisibility:    return 1;
12910b57cec5SDimitry Andric   case GlobalValue::ProtectedVisibility: return 2;
12920b57cec5SDimitry Andric   }
12930b57cec5SDimitry Andric   llvm_unreachable("Invalid visibility");
12940b57cec5SDimitry Andric }
12950b57cec5SDimitry Andric 
12960b57cec5SDimitry Andric static unsigned getEncodedDLLStorageClass(const GlobalValue &GV) {
12970b57cec5SDimitry Andric   switch (GV.getDLLStorageClass()) {
12980b57cec5SDimitry Andric   case GlobalValue::DefaultStorageClass:   return 0;
12990b57cec5SDimitry Andric   case GlobalValue::DLLImportStorageClass: return 1;
13000b57cec5SDimitry Andric   case GlobalValue::DLLExportStorageClass: return 2;
13010b57cec5SDimitry Andric   }
13020b57cec5SDimitry Andric   llvm_unreachable("Invalid DLL storage class");
13030b57cec5SDimitry Andric }
13040b57cec5SDimitry Andric 
13050b57cec5SDimitry Andric static unsigned getEncodedThreadLocalMode(const GlobalValue &GV) {
13060b57cec5SDimitry Andric   switch (GV.getThreadLocalMode()) {
13070b57cec5SDimitry Andric     case GlobalVariable::NotThreadLocal:         return 0;
13080b57cec5SDimitry Andric     case GlobalVariable::GeneralDynamicTLSModel: return 1;
13090b57cec5SDimitry Andric     case GlobalVariable::LocalDynamicTLSModel:   return 2;
13100b57cec5SDimitry Andric     case GlobalVariable::InitialExecTLSModel:    return 3;
13110b57cec5SDimitry Andric     case GlobalVariable::LocalExecTLSModel:      return 4;
13120b57cec5SDimitry Andric   }
13130b57cec5SDimitry Andric   llvm_unreachable("Invalid TLS model");
13140b57cec5SDimitry Andric }
13150b57cec5SDimitry Andric 
13160b57cec5SDimitry Andric static unsigned getEncodedComdatSelectionKind(const Comdat &C) {
13170b57cec5SDimitry Andric   switch (C.getSelectionKind()) {
13180b57cec5SDimitry Andric   case Comdat::Any:
13190b57cec5SDimitry Andric     return bitc::COMDAT_SELECTION_KIND_ANY;
13200b57cec5SDimitry Andric   case Comdat::ExactMatch:
13210b57cec5SDimitry Andric     return bitc::COMDAT_SELECTION_KIND_EXACT_MATCH;
13220b57cec5SDimitry Andric   case Comdat::Largest:
13230b57cec5SDimitry Andric     return bitc::COMDAT_SELECTION_KIND_LARGEST;
1324fe6060f1SDimitry Andric   case Comdat::NoDeduplicate:
13250b57cec5SDimitry Andric     return bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES;
13260b57cec5SDimitry Andric   case Comdat::SameSize:
13270b57cec5SDimitry Andric     return bitc::COMDAT_SELECTION_KIND_SAME_SIZE;
13280b57cec5SDimitry Andric   }
13290b57cec5SDimitry Andric   llvm_unreachable("Invalid selection kind");
13300b57cec5SDimitry Andric }
13310b57cec5SDimitry Andric 
13320b57cec5SDimitry Andric static unsigned getEncodedUnnamedAddr(const GlobalValue &GV) {
13330b57cec5SDimitry Andric   switch (GV.getUnnamedAddr()) {
13340b57cec5SDimitry Andric   case GlobalValue::UnnamedAddr::None:   return 0;
13350b57cec5SDimitry Andric   case GlobalValue::UnnamedAddr::Local:  return 2;
13360b57cec5SDimitry Andric   case GlobalValue::UnnamedAddr::Global: return 1;
13370b57cec5SDimitry Andric   }
13380b57cec5SDimitry Andric   llvm_unreachable("Invalid unnamed_addr");
13390b57cec5SDimitry Andric }
13400b57cec5SDimitry Andric 
13410b57cec5SDimitry Andric size_t ModuleBitcodeWriter::addToStrtab(StringRef Str) {
13420b57cec5SDimitry Andric   if (GenerateHash)
13430b57cec5SDimitry Andric     Hasher.update(Str);
13440b57cec5SDimitry Andric   return StrtabBuilder.add(Str);
13450b57cec5SDimitry Andric }
13460b57cec5SDimitry Andric 
13470b57cec5SDimitry Andric void ModuleBitcodeWriter::writeComdats() {
13480b57cec5SDimitry Andric   SmallVector<unsigned, 64> Vals;
13490b57cec5SDimitry Andric   for (const Comdat *C : VE.getComdats()) {
13500b57cec5SDimitry Andric     // COMDAT: [strtab offset, strtab size, selection_kind]
13510b57cec5SDimitry Andric     Vals.push_back(addToStrtab(C->getName()));
13520b57cec5SDimitry Andric     Vals.push_back(C->getName().size());
13530b57cec5SDimitry Andric     Vals.push_back(getEncodedComdatSelectionKind(*C));
13540b57cec5SDimitry Andric     Stream.EmitRecord(bitc::MODULE_CODE_COMDAT, Vals, /*AbbrevToUse=*/0);
13550b57cec5SDimitry Andric     Vals.clear();
13560b57cec5SDimitry Andric   }
13570b57cec5SDimitry Andric }
13580b57cec5SDimitry Andric 
13590b57cec5SDimitry Andric /// Write a record that will eventually hold the word offset of the
13600b57cec5SDimitry Andric /// module-level VST. For now the offset is 0, which will be backpatched
13610b57cec5SDimitry Andric /// after the real VST is written. Saves the bit offset to backpatch.
13620b57cec5SDimitry Andric void ModuleBitcodeWriter::writeValueSymbolTableForwardDecl() {
13630b57cec5SDimitry Andric   // Write a placeholder value in for the offset of the real VST,
13640b57cec5SDimitry Andric   // which is written after the function blocks so that it can include
13650b57cec5SDimitry Andric   // the offset of each function. The placeholder offset will be
13660b57cec5SDimitry Andric   // updated when the real VST is written.
13670b57cec5SDimitry Andric   auto Abbv = std::make_shared<BitCodeAbbrev>();
13680b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_VSTOFFSET));
13690b57cec5SDimitry Andric   // Blocks are 32-bit aligned, so we can use a 32-bit word offset to
13700b57cec5SDimitry Andric   // hold the real VST offset. Must use fixed instead of VBR as we don't
13710b57cec5SDimitry Andric   // know how many VBR chunks to reserve ahead of time.
13720b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
13730b57cec5SDimitry Andric   unsigned VSTOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbv));
13740b57cec5SDimitry Andric 
13750b57cec5SDimitry Andric   // Emit the placeholder
13760b57cec5SDimitry Andric   uint64_t Vals[] = {bitc::MODULE_CODE_VSTOFFSET, 0};
13770b57cec5SDimitry Andric   Stream.EmitRecordWithAbbrev(VSTOffsetAbbrev, Vals);
13780b57cec5SDimitry Andric 
13790b57cec5SDimitry Andric   // Compute and save the bit offset to the placeholder, which will be
13800b57cec5SDimitry Andric   // patched when the real VST is written. We can simply subtract the 32-bit
13810b57cec5SDimitry Andric   // fixed size from the current bit number to get the location to backpatch.
13820b57cec5SDimitry Andric   VSTOffsetPlaceholder = Stream.GetCurrentBitNo() - 32;
13830b57cec5SDimitry Andric }
13840b57cec5SDimitry Andric 
13850b57cec5SDimitry Andric enum StringEncoding { SE_Char6, SE_Fixed7, SE_Fixed8 };
13860b57cec5SDimitry Andric 
13870b57cec5SDimitry Andric /// Determine the encoding to use for the given string name and length.
13880b57cec5SDimitry Andric static StringEncoding getStringEncoding(StringRef Str) {
13890b57cec5SDimitry Andric   bool isChar6 = true;
13900b57cec5SDimitry Andric   for (char C : Str) {
13910b57cec5SDimitry Andric     if (isChar6)
13920b57cec5SDimitry Andric       isChar6 = BitCodeAbbrevOp::isChar6(C);
13930b57cec5SDimitry Andric     if ((unsigned char)C & 128)
13940b57cec5SDimitry Andric       // don't bother scanning the rest.
13950b57cec5SDimitry Andric       return SE_Fixed8;
13960b57cec5SDimitry Andric   }
13970b57cec5SDimitry Andric   if (isChar6)
13980b57cec5SDimitry Andric     return SE_Char6;
13990b57cec5SDimitry Andric   return SE_Fixed7;
14000b57cec5SDimitry Andric }
14010b57cec5SDimitry Andric 
140281ad6265SDimitry Andric static_assert(sizeof(GlobalValue::SanitizerMetadata) <= sizeof(unsigned),
140381ad6265SDimitry Andric               "Sanitizer Metadata is too large for naive serialization.");
140481ad6265SDimitry Andric static unsigned
140581ad6265SDimitry Andric serializeSanitizerMetadata(const GlobalValue::SanitizerMetadata &Meta) {
140681ad6265SDimitry Andric   return Meta.NoAddress | (Meta.NoHWAddress << 1) |
1407753f127fSDimitry Andric          (Meta.Memtag << 2) | (Meta.IsDynInit << 3);
140881ad6265SDimitry Andric }
140981ad6265SDimitry Andric 
14100b57cec5SDimitry Andric /// Emit top-level description of module, including target triple, inline asm,
14110b57cec5SDimitry Andric /// descriptors for global variables, and function prototype info.
14120b57cec5SDimitry Andric /// Returns the bit offset to backpatch with the location of the real VST.
14130b57cec5SDimitry Andric void ModuleBitcodeWriter::writeModuleInfo() {
14140b57cec5SDimitry Andric   // Emit various pieces of data attached to a module.
14150b57cec5SDimitry Andric   if (!M.getTargetTriple().empty())
14160b57cec5SDimitry Andric     writeStringRecord(Stream, bitc::MODULE_CODE_TRIPLE, M.getTargetTriple(),
14170b57cec5SDimitry Andric                       0 /*TODO*/);
14180b57cec5SDimitry Andric   const std::string &DL = M.getDataLayoutStr();
14190b57cec5SDimitry Andric   if (!DL.empty())
14200b57cec5SDimitry Andric     writeStringRecord(Stream, bitc::MODULE_CODE_DATALAYOUT, DL, 0 /*TODO*/);
14210b57cec5SDimitry Andric   if (!M.getModuleInlineAsm().empty())
14220b57cec5SDimitry Andric     writeStringRecord(Stream, bitc::MODULE_CODE_ASM, M.getModuleInlineAsm(),
14230b57cec5SDimitry Andric                       0 /*TODO*/);
14240b57cec5SDimitry Andric 
14250b57cec5SDimitry Andric   // Emit information about sections and GC, computing how many there are. Also
14260b57cec5SDimitry Andric   // compute the maximum alignment value.
14270b57cec5SDimitry Andric   std::map<std::string, unsigned> SectionMap;
14280b57cec5SDimitry Andric   std::map<std::string, unsigned> GCMap;
1429e8d8bef9SDimitry Andric   MaybeAlign MaxAlignment;
14300b57cec5SDimitry Andric   unsigned MaxGlobalType = 0;
1431e8d8bef9SDimitry Andric   const auto UpdateMaxAlignment = [&MaxAlignment](const MaybeAlign A) {
1432e8d8bef9SDimitry Andric     if (A)
1433e8d8bef9SDimitry Andric       MaxAlignment = !MaxAlignment ? *A : std::max(*MaxAlignment, *A);
1434e8d8bef9SDimitry Andric   };
14355ffd83dbSDimitry Andric   for (const GlobalVariable &GV : M.globals()) {
1436e8d8bef9SDimitry Andric     UpdateMaxAlignment(GV.getAlign());
14370b57cec5SDimitry Andric     MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV.getValueType()));
14380b57cec5SDimitry Andric     if (GV.hasSection()) {
14390b57cec5SDimitry Andric       // Give section names unique ID's.
14405ffd83dbSDimitry Andric       unsigned &Entry = SectionMap[std::string(GV.getSection())];
14410b57cec5SDimitry Andric       if (!Entry) {
14420b57cec5SDimitry Andric         writeStringRecord(Stream, bitc::MODULE_CODE_SECTIONNAME, GV.getSection(),
14430b57cec5SDimitry Andric                           0 /*TODO*/);
14440b57cec5SDimitry Andric         Entry = SectionMap.size();
14450b57cec5SDimitry Andric       }
14460b57cec5SDimitry Andric     }
14470b57cec5SDimitry Andric   }
14480b57cec5SDimitry Andric   for (const Function &F : M) {
1449e8d8bef9SDimitry Andric     UpdateMaxAlignment(F.getAlign());
14500b57cec5SDimitry Andric     if (F.hasSection()) {
14510b57cec5SDimitry Andric       // Give section names unique ID's.
14525ffd83dbSDimitry Andric       unsigned &Entry = SectionMap[std::string(F.getSection())];
14530b57cec5SDimitry Andric       if (!Entry) {
14540b57cec5SDimitry Andric         writeStringRecord(Stream, bitc::MODULE_CODE_SECTIONNAME, F.getSection(),
14550b57cec5SDimitry Andric                           0 /*TODO*/);
14560b57cec5SDimitry Andric         Entry = SectionMap.size();
14570b57cec5SDimitry Andric       }
14580b57cec5SDimitry Andric     }
14590b57cec5SDimitry Andric     if (F.hasGC()) {
14600b57cec5SDimitry Andric       // Same for GC names.
14610b57cec5SDimitry Andric       unsigned &Entry = GCMap[F.getGC()];
14620b57cec5SDimitry Andric       if (!Entry) {
14630b57cec5SDimitry Andric         writeStringRecord(Stream, bitc::MODULE_CODE_GCNAME, F.getGC(),
14640b57cec5SDimitry Andric                           0 /*TODO*/);
14650b57cec5SDimitry Andric         Entry = GCMap.size();
14660b57cec5SDimitry Andric       }
14670b57cec5SDimitry Andric     }
14680b57cec5SDimitry Andric   }
14690b57cec5SDimitry Andric 
14700b57cec5SDimitry Andric   // Emit abbrev for globals, now that we know # sections and max alignment.
14710b57cec5SDimitry Andric   unsigned SimpleGVarAbbrev = 0;
14720b57cec5SDimitry Andric   if (!M.global_empty()) {
14730b57cec5SDimitry Andric     // Add an abbrev for common globals with no visibility or thread localness.
14740b57cec5SDimitry Andric     auto Abbv = std::make_shared<BitCodeAbbrev>();
14750b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GLOBALVAR));
14760b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
14770b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
14780b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
14790b57cec5SDimitry Andric                               Log2_32_Ceil(MaxGlobalType+1)));
14800b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // AddrSpace << 2
14810b57cec5SDimitry Andric                                                            //| explicitType << 1
14820b57cec5SDimitry Andric                                                            //| constant
14830b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // Initializer.
14840b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5)); // Linkage.
1485e8d8bef9SDimitry Andric     if (!MaxAlignment)                                     // Alignment.
14860b57cec5SDimitry Andric       Abbv->Add(BitCodeAbbrevOp(0));
14870b57cec5SDimitry Andric     else {
1488e8d8bef9SDimitry Andric       unsigned MaxEncAlignment = getEncodedAlign(MaxAlignment);
14890b57cec5SDimitry Andric       Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
14900b57cec5SDimitry Andric                                Log2_32_Ceil(MaxEncAlignment+1)));
14910b57cec5SDimitry Andric     }
14920b57cec5SDimitry Andric     if (SectionMap.empty())                                    // Section.
14930b57cec5SDimitry Andric       Abbv->Add(BitCodeAbbrevOp(0));
14940b57cec5SDimitry Andric     else
14950b57cec5SDimitry Andric       Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
14960b57cec5SDimitry Andric                                Log2_32_Ceil(SectionMap.size()+1)));
14970b57cec5SDimitry Andric     // Don't bother emitting vis + thread local.
14980b57cec5SDimitry Andric     SimpleGVarAbbrev = Stream.EmitAbbrev(std::move(Abbv));
14990b57cec5SDimitry Andric   }
15000b57cec5SDimitry Andric 
15010b57cec5SDimitry Andric   SmallVector<unsigned, 64> Vals;
15020b57cec5SDimitry Andric   // Emit the module's source file name.
15030b57cec5SDimitry Andric   {
15040b57cec5SDimitry Andric     StringEncoding Bits = getStringEncoding(M.getSourceFileName());
15050b57cec5SDimitry Andric     BitCodeAbbrevOp AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8);
15060b57cec5SDimitry Andric     if (Bits == SE_Char6)
15070b57cec5SDimitry Andric       AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Char6);
15080b57cec5SDimitry Andric     else if (Bits == SE_Fixed7)
15090b57cec5SDimitry Andric       AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7);
15100b57cec5SDimitry Andric 
15110b57cec5SDimitry Andric     // MODULE_CODE_SOURCE_FILENAME: [namechar x N]
15120b57cec5SDimitry Andric     auto Abbv = std::make_shared<BitCodeAbbrev>();
15130b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_SOURCE_FILENAME));
15140b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
15150b57cec5SDimitry Andric     Abbv->Add(AbbrevOpToUse);
15160b57cec5SDimitry Andric     unsigned FilenameAbbrev = Stream.EmitAbbrev(std::move(Abbv));
15170b57cec5SDimitry Andric 
15180b57cec5SDimitry Andric     for (const auto P : M.getSourceFileName())
15190b57cec5SDimitry Andric       Vals.push_back((unsigned char)P);
15200b57cec5SDimitry Andric 
15210b57cec5SDimitry Andric     // Emit the finished record.
15220b57cec5SDimitry Andric     Stream.EmitRecord(bitc::MODULE_CODE_SOURCE_FILENAME, Vals, FilenameAbbrev);
15230b57cec5SDimitry Andric     Vals.clear();
15240b57cec5SDimitry Andric   }
15250b57cec5SDimitry Andric 
15260b57cec5SDimitry Andric   // Emit the global variable information.
15270b57cec5SDimitry Andric   for (const GlobalVariable &GV : M.globals()) {
15280b57cec5SDimitry Andric     unsigned AbbrevToUse = 0;
15290b57cec5SDimitry Andric 
15300b57cec5SDimitry Andric     // GLOBALVAR: [strtab offset, strtab size, type, isconst, initid,
15310b57cec5SDimitry Andric     //             linkage, alignment, section, visibility, threadlocal,
15320b57cec5SDimitry Andric     //             unnamed_addr, externally_initialized, dllstorageclass,
15335f757f3fSDimitry Andric     //             comdat, attributes, DSO_Local, GlobalSanitizer, code_model]
15340b57cec5SDimitry Andric     Vals.push_back(addToStrtab(GV.getName()));
15350b57cec5SDimitry Andric     Vals.push_back(GV.getName().size());
15360b57cec5SDimitry Andric     Vals.push_back(VE.getTypeID(GV.getValueType()));
15370b57cec5SDimitry Andric     Vals.push_back(GV.getType()->getAddressSpace() << 2 | 2 | GV.isConstant());
15380b57cec5SDimitry Andric     Vals.push_back(GV.isDeclaration() ? 0 :
15390b57cec5SDimitry Andric                    (VE.getValueID(GV.getInitializer()) + 1));
15400b57cec5SDimitry Andric     Vals.push_back(getEncodedLinkage(GV));
1541e8d8bef9SDimitry Andric     Vals.push_back(getEncodedAlign(GV.getAlign()));
15425ffd83dbSDimitry Andric     Vals.push_back(GV.hasSection() ? SectionMap[std::string(GV.getSection())]
15435ffd83dbSDimitry Andric                                    : 0);
15440b57cec5SDimitry Andric     if (GV.isThreadLocal() ||
15450b57cec5SDimitry Andric         GV.getVisibility() != GlobalValue::DefaultVisibility ||
15460b57cec5SDimitry Andric         GV.getUnnamedAddr() != GlobalValue::UnnamedAddr::None ||
15470b57cec5SDimitry Andric         GV.isExternallyInitialized() ||
15480b57cec5SDimitry Andric         GV.getDLLStorageClass() != GlobalValue::DefaultStorageClass ||
154981ad6265SDimitry Andric         GV.hasComdat() || GV.hasAttributes() || GV.isDSOLocal() ||
15505f757f3fSDimitry Andric         GV.hasPartition() || GV.hasSanitizerMetadata() || GV.getCodeModel()) {
15510b57cec5SDimitry Andric       Vals.push_back(getEncodedVisibility(GV));
15520b57cec5SDimitry Andric       Vals.push_back(getEncodedThreadLocalMode(GV));
15530b57cec5SDimitry Andric       Vals.push_back(getEncodedUnnamedAddr(GV));
15540b57cec5SDimitry Andric       Vals.push_back(GV.isExternallyInitialized());
15550b57cec5SDimitry Andric       Vals.push_back(getEncodedDLLStorageClass(GV));
15560b57cec5SDimitry Andric       Vals.push_back(GV.hasComdat() ? VE.getComdatID(GV.getComdat()) : 0);
15570b57cec5SDimitry Andric 
15580b57cec5SDimitry Andric       auto AL = GV.getAttributesAsList(AttributeList::FunctionIndex);
15590b57cec5SDimitry Andric       Vals.push_back(VE.getAttributeListID(AL));
15600b57cec5SDimitry Andric 
15610b57cec5SDimitry Andric       Vals.push_back(GV.isDSOLocal());
15620b57cec5SDimitry Andric       Vals.push_back(addToStrtab(GV.getPartition()));
15630b57cec5SDimitry Andric       Vals.push_back(GV.getPartition().size());
156481ad6265SDimitry Andric 
156581ad6265SDimitry Andric       Vals.push_back((GV.hasSanitizerMetadata() ? serializeSanitizerMetadata(
156681ad6265SDimitry Andric                                                       GV.getSanitizerMetadata())
156781ad6265SDimitry Andric                                                 : 0));
15685f757f3fSDimitry Andric       Vals.push_back(GV.getCodeModelRaw());
15690b57cec5SDimitry Andric     } else {
15700b57cec5SDimitry Andric       AbbrevToUse = SimpleGVarAbbrev;
15710b57cec5SDimitry Andric     }
15720b57cec5SDimitry Andric 
15730b57cec5SDimitry Andric     Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse);
15740b57cec5SDimitry Andric     Vals.clear();
15750b57cec5SDimitry Andric   }
15760b57cec5SDimitry Andric 
15770b57cec5SDimitry Andric   // Emit the function proto information.
15780b57cec5SDimitry Andric   for (const Function &F : M) {
15790b57cec5SDimitry Andric     // FUNCTION:  [strtab offset, strtab size, type, callingconv, isproto,
15800b57cec5SDimitry Andric     //             linkage, paramattrs, alignment, section, visibility, gc,
15810b57cec5SDimitry Andric     //             unnamed_addr, prologuedata, dllstorageclass, comdat,
15820b57cec5SDimitry Andric     //             prefixdata, personalityfn, DSO_Local, addrspace]
15830b57cec5SDimitry Andric     Vals.push_back(addToStrtab(F.getName()));
15840b57cec5SDimitry Andric     Vals.push_back(F.getName().size());
15850b57cec5SDimitry Andric     Vals.push_back(VE.getTypeID(F.getFunctionType()));
15860b57cec5SDimitry Andric     Vals.push_back(F.getCallingConv());
15870b57cec5SDimitry Andric     Vals.push_back(F.isDeclaration());
15880b57cec5SDimitry Andric     Vals.push_back(getEncodedLinkage(F));
15890b57cec5SDimitry Andric     Vals.push_back(VE.getAttributeListID(F.getAttributes()));
1590e8d8bef9SDimitry Andric     Vals.push_back(getEncodedAlign(F.getAlign()));
15915ffd83dbSDimitry Andric     Vals.push_back(F.hasSection() ? SectionMap[std::string(F.getSection())]
15925ffd83dbSDimitry Andric                                   : 0);
15930b57cec5SDimitry Andric     Vals.push_back(getEncodedVisibility(F));
15940b57cec5SDimitry Andric     Vals.push_back(F.hasGC() ? GCMap[F.getGC()] : 0);
15950b57cec5SDimitry Andric     Vals.push_back(getEncodedUnnamedAddr(F));
15960b57cec5SDimitry Andric     Vals.push_back(F.hasPrologueData() ? (VE.getValueID(F.getPrologueData()) + 1)
15970b57cec5SDimitry Andric                                        : 0);
15980b57cec5SDimitry Andric     Vals.push_back(getEncodedDLLStorageClass(F));
15990b57cec5SDimitry Andric     Vals.push_back(F.hasComdat() ? VE.getComdatID(F.getComdat()) : 0);
16000b57cec5SDimitry Andric     Vals.push_back(F.hasPrefixData() ? (VE.getValueID(F.getPrefixData()) + 1)
16010b57cec5SDimitry Andric                                      : 0);
16020b57cec5SDimitry Andric     Vals.push_back(
16030b57cec5SDimitry Andric         F.hasPersonalityFn() ? (VE.getValueID(F.getPersonalityFn()) + 1) : 0);
16040b57cec5SDimitry Andric 
16050b57cec5SDimitry Andric     Vals.push_back(F.isDSOLocal());
16060b57cec5SDimitry Andric     Vals.push_back(F.getAddressSpace());
16070b57cec5SDimitry Andric     Vals.push_back(addToStrtab(F.getPartition()));
16080b57cec5SDimitry Andric     Vals.push_back(F.getPartition().size());
16090b57cec5SDimitry Andric 
16100b57cec5SDimitry Andric     unsigned AbbrevToUse = 0;
16110b57cec5SDimitry Andric     Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse);
16120b57cec5SDimitry Andric     Vals.clear();
16130b57cec5SDimitry Andric   }
16140b57cec5SDimitry Andric 
16150b57cec5SDimitry Andric   // Emit the alias information.
16160b57cec5SDimitry Andric   for (const GlobalAlias &A : M.aliases()) {
16170b57cec5SDimitry Andric     // ALIAS: [strtab offset, strtab size, alias type, aliasee val#, linkage,
16180b57cec5SDimitry Andric     //         visibility, dllstorageclass, threadlocal, unnamed_addr,
16190b57cec5SDimitry Andric     //         DSO_Local]
16200b57cec5SDimitry Andric     Vals.push_back(addToStrtab(A.getName()));
16210b57cec5SDimitry Andric     Vals.push_back(A.getName().size());
16220b57cec5SDimitry Andric     Vals.push_back(VE.getTypeID(A.getValueType()));
16230b57cec5SDimitry Andric     Vals.push_back(A.getType()->getAddressSpace());
16240b57cec5SDimitry Andric     Vals.push_back(VE.getValueID(A.getAliasee()));
16250b57cec5SDimitry Andric     Vals.push_back(getEncodedLinkage(A));
16260b57cec5SDimitry Andric     Vals.push_back(getEncodedVisibility(A));
16270b57cec5SDimitry Andric     Vals.push_back(getEncodedDLLStorageClass(A));
16280b57cec5SDimitry Andric     Vals.push_back(getEncodedThreadLocalMode(A));
16290b57cec5SDimitry Andric     Vals.push_back(getEncodedUnnamedAddr(A));
16300b57cec5SDimitry Andric     Vals.push_back(A.isDSOLocal());
16310b57cec5SDimitry Andric     Vals.push_back(addToStrtab(A.getPartition()));
16320b57cec5SDimitry Andric     Vals.push_back(A.getPartition().size());
16330b57cec5SDimitry Andric 
16340b57cec5SDimitry Andric     unsigned AbbrevToUse = 0;
16350b57cec5SDimitry Andric     Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse);
16360b57cec5SDimitry Andric     Vals.clear();
16370b57cec5SDimitry Andric   }
16380b57cec5SDimitry Andric 
16390b57cec5SDimitry Andric   // Emit the ifunc information.
16400b57cec5SDimitry Andric   for (const GlobalIFunc &I : M.ifuncs()) {
16410b57cec5SDimitry Andric     // IFUNC: [strtab offset, strtab size, ifunc type, address space, resolver
16420b57cec5SDimitry Andric     //         val#, linkage, visibility, DSO_Local]
16430b57cec5SDimitry Andric     Vals.push_back(addToStrtab(I.getName()));
16440b57cec5SDimitry Andric     Vals.push_back(I.getName().size());
16450b57cec5SDimitry Andric     Vals.push_back(VE.getTypeID(I.getValueType()));
16460b57cec5SDimitry Andric     Vals.push_back(I.getType()->getAddressSpace());
16470b57cec5SDimitry Andric     Vals.push_back(VE.getValueID(I.getResolver()));
16480b57cec5SDimitry Andric     Vals.push_back(getEncodedLinkage(I));
16490b57cec5SDimitry Andric     Vals.push_back(getEncodedVisibility(I));
16500b57cec5SDimitry Andric     Vals.push_back(I.isDSOLocal());
16510b57cec5SDimitry Andric     Vals.push_back(addToStrtab(I.getPartition()));
16520b57cec5SDimitry Andric     Vals.push_back(I.getPartition().size());
16530b57cec5SDimitry Andric     Stream.EmitRecord(bitc::MODULE_CODE_IFUNC, Vals);
16540b57cec5SDimitry Andric     Vals.clear();
16550b57cec5SDimitry Andric   }
16560b57cec5SDimitry Andric 
16570b57cec5SDimitry Andric   writeValueSymbolTableForwardDecl();
16580b57cec5SDimitry Andric }
16590b57cec5SDimitry Andric 
16600b57cec5SDimitry Andric static uint64_t getOptimizationFlags(const Value *V) {
16610b57cec5SDimitry Andric   uint64_t Flags = 0;
16620b57cec5SDimitry Andric 
16630b57cec5SDimitry Andric   if (const auto *OBO = dyn_cast<OverflowingBinaryOperator>(V)) {
16640b57cec5SDimitry Andric     if (OBO->hasNoSignedWrap())
16650b57cec5SDimitry Andric       Flags |= 1 << bitc::OBO_NO_SIGNED_WRAP;
16660b57cec5SDimitry Andric     if (OBO->hasNoUnsignedWrap())
16670b57cec5SDimitry Andric       Flags |= 1 << bitc::OBO_NO_UNSIGNED_WRAP;
16680b57cec5SDimitry Andric   } else if (const auto *PEO = dyn_cast<PossiblyExactOperator>(V)) {
16690b57cec5SDimitry Andric     if (PEO->isExact())
16700b57cec5SDimitry Andric       Flags |= 1 << bitc::PEO_EXACT;
16715f757f3fSDimitry Andric   } else if (const auto *PDI = dyn_cast<PossiblyDisjointInst>(V)) {
16725f757f3fSDimitry Andric     if (PDI->isDisjoint())
16735f757f3fSDimitry Andric       Flags |= 1 << bitc::PDI_DISJOINT;
16740b57cec5SDimitry Andric   } else if (const auto *FPMO = dyn_cast<FPMathOperator>(V)) {
16750b57cec5SDimitry Andric     if (FPMO->hasAllowReassoc())
16760b57cec5SDimitry Andric       Flags |= bitc::AllowReassoc;
16770b57cec5SDimitry Andric     if (FPMO->hasNoNaNs())
16780b57cec5SDimitry Andric       Flags |= bitc::NoNaNs;
16790b57cec5SDimitry Andric     if (FPMO->hasNoInfs())
16800b57cec5SDimitry Andric       Flags |= bitc::NoInfs;
16810b57cec5SDimitry Andric     if (FPMO->hasNoSignedZeros())
16820b57cec5SDimitry Andric       Flags |= bitc::NoSignedZeros;
16830b57cec5SDimitry Andric     if (FPMO->hasAllowReciprocal())
16840b57cec5SDimitry Andric       Flags |= bitc::AllowReciprocal;
16850b57cec5SDimitry Andric     if (FPMO->hasAllowContract())
16860b57cec5SDimitry Andric       Flags |= bitc::AllowContract;
16870b57cec5SDimitry Andric     if (FPMO->hasApproxFunc())
16880b57cec5SDimitry Andric       Flags |= bitc::ApproxFunc;
16895f757f3fSDimitry Andric   } else if (const auto *NNI = dyn_cast<PossiblyNonNegInst>(V)) {
16905f757f3fSDimitry Andric     if (NNI->hasNonNeg())
16915f757f3fSDimitry Andric       Flags |= 1 << bitc::PNNI_NON_NEG;
1692*0fca6ea1SDimitry Andric   } else if (const auto *TI = dyn_cast<TruncInst>(V)) {
1693*0fca6ea1SDimitry Andric     if (TI->hasNoSignedWrap())
1694*0fca6ea1SDimitry Andric       Flags |= 1 << bitc::TIO_NO_SIGNED_WRAP;
1695*0fca6ea1SDimitry Andric     if (TI->hasNoUnsignedWrap())
1696*0fca6ea1SDimitry Andric       Flags |= 1 << bitc::TIO_NO_UNSIGNED_WRAP;
1697*0fca6ea1SDimitry Andric   } else if (const auto *GEP = dyn_cast<GEPOperator>(V)) {
1698*0fca6ea1SDimitry Andric     if (GEP->isInBounds())
1699*0fca6ea1SDimitry Andric       Flags |= 1 << bitc::GEP_INBOUNDS;
1700*0fca6ea1SDimitry Andric     if (GEP->hasNoUnsignedSignedWrap())
1701*0fca6ea1SDimitry Andric       Flags |= 1 << bitc::GEP_NUSW;
1702*0fca6ea1SDimitry Andric     if (GEP->hasNoUnsignedWrap())
1703*0fca6ea1SDimitry Andric       Flags |= 1 << bitc::GEP_NUW;
17040b57cec5SDimitry Andric   }
17050b57cec5SDimitry Andric 
17060b57cec5SDimitry Andric   return Flags;
17070b57cec5SDimitry Andric }
17080b57cec5SDimitry Andric 
17090b57cec5SDimitry Andric void ModuleBitcodeWriter::writeValueAsMetadata(
17100b57cec5SDimitry Andric     const ValueAsMetadata *MD, SmallVectorImpl<uint64_t> &Record) {
17110b57cec5SDimitry Andric   // Mimic an MDNode with a value as one operand.
17120b57cec5SDimitry Andric   Value *V = MD->getValue();
17130b57cec5SDimitry Andric   Record.push_back(VE.getTypeID(V->getType()));
17140b57cec5SDimitry Andric   Record.push_back(VE.getValueID(V));
17150b57cec5SDimitry Andric   Stream.EmitRecord(bitc::METADATA_VALUE, Record, 0);
17160b57cec5SDimitry Andric   Record.clear();
17170b57cec5SDimitry Andric }
17180b57cec5SDimitry Andric 
17190b57cec5SDimitry Andric void ModuleBitcodeWriter::writeMDTuple(const MDTuple *N,
17200b57cec5SDimitry Andric                                        SmallVectorImpl<uint64_t> &Record,
17210b57cec5SDimitry Andric                                        unsigned Abbrev) {
1722*0fca6ea1SDimitry Andric   for (const MDOperand &MDO : N->operands()) {
1723*0fca6ea1SDimitry Andric     Metadata *MD = MDO;
17240b57cec5SDimitry Andric     assert(!(MD && isa<LocalAsMetadata>(MD)) &&
17250b57cec5SDimitry Andric            "Unexpected function-local metadata");
17260b57cec5SDimitry Andric     Record.push_back(VE.getMetadataOrNullID(MD));
17270b57cec5SDimitry Andric   }
17280b57cec5SDimitry Andric   Stream.EmitRecord(N->isDistinct() ? bitc::METADATA_DISTINCT_NODE
17290b57cec5SDimitry Andric                                     : bitc::METADATA_NODE,
17300b57cec5SDimitry Andric                     Record, Abbrev);
17310b57cec5SDimitry Andric   Record.clear();
17320b57cec5SDimitry Andric }
17330b57cec5SDimitry Andric 
17340b57cec5SDimitry Andric unsigned ModuleBitcodeWriter::createDILocationAbbrev() {
17350b57cec5SDimitry Andric   // Assume the column is usually under 128, and always output the inlined-at
17360b57cec5SDimitry Andric   // location (it's never more expensive than building an array size 1).
17370b57cec5SDimitry Andric   auto Abbv = std::make_shared<BitCodeAbbrev>();
17380b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_LOCATION));
17390b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
17400b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
17410b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
17420b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
17430b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
17440b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
17450b57cec5SDimitry Andric   return Stream.EmitAbbrev(std::move(Abbv));
17460b57cec5SDimitry Andric }
17470b57cec5SDimitry Andric 
17480b57cec5SDimitry Andric void ModuleBitcodeWriter::writeDILocation(const DILocation *N,
17490b57cec5SDimitry Andric                                           SmallVectorImpl<uint64_t> &Record,
17500b57cec5SDimitry Andric                                           unsigned &Abbrev) {
17510b57cec5SDimitry Andric   if (!Abbrev)
17520b57cec5SDimitry Andric     Abbrev = createDILocationAbbrev();
17530b57cec5SDimitry Andric 
17540b57cec5SDimitry Andric   Record.push_back(N->isDistinct());
17550b57cec5SDimitry Andric   Record.push_back(N->getLine());
17560b57cec5SDimitry Andric   Record.push_back(N->getColumn());
17570b57cec5SDimitry Andric   Record.push_back(VE.getMetadataID(N->getScope()));
17580b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getInlinedAt()));
17590b57cec5SDimitry Andric   Record.push_back(N->isImplicitCode());
17600b57cec5SDimitry Andric 
17610b57cec5SDimitry Andric   Stream.EmitRecord(bitc::METADATA_LOCATION, Record, Abbrev);
17620b57cec5SDimitry Andric   Record.clear();
17630b57cec5SDimitry Andric }
17640b57cec5SDimitry Andric 
17650b57cec5SDimitry Andric unsigned ModuleBitcodeWriter::createGenericDINodeAbbrev() {
17660b57cec5SDimitry Andric   // Assume the column is usually under 128, and always output the inlined-at
17670b57cec5SDimitry Andric   // location (it's never more expensive than building an array size 1).
17680b57cec5SDimitry Andric   auto Abbv = std::make_shared<BitCodeAbbrev>();
17690b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_GENERIC_DEBUG));
17700b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
17710b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
17720b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
17730b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
17740b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
17750b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
17760b57cec5SDimitry Andric   return Stream.EmitAbbrev(std::move(Abbv));
17770b57cec5SDimitry Andric }
17780b57cec5SDimitry Andric 
17790b57cec5SDimitry Andric void ModuleBitcodeWriter::writeGenericDINode(const GenericDINode *N,
17800b57cec5SDimitry Andric                                              SmallVectorImpl<uint64_t> &Record,
17810b57cec5SDimitry Andric                                              unsigned &Abbrev) {
17820b57cec5SDimitry Andric   if (!Abbrev)
17830b57cec5SDimitry Andric     Abbrev = createGenericDINodeAbbrev();
17840b57cec5SDimitry Andric 
17850b57cec5SDimitry Andric   Record.push_back(N->isDistinct());
17860b57cec5SDimitry Andric   Record.push_back(N->getTag());
17870b57cec5SDimitry Andric   Record.push_back(0); // Per-tag version field; unused for now.
17880b57cec5SDimitry Andric 
17890b57cec5SDimitry Andric   for (auto &I : N->operands())
17900b57cec5SDimitry Andric     Record.push_back(VE.getMetadataOrNullID(I));
17910b57cec5SDimitry Andric 
17920b57cec5SDimitry Andric   Stream.EmitRecord(bitc::METADATA_GENERIC_DEBUG, Record, Abbrev);
17930b57cec5SDimitry Andric   Record.clear();
17940b57cec5SDimitry Andric }
17950b57cec5SDimitry Andric 
17960b57cec5SDimitry Andric void ModuleBitcodeWriter::writeDISubrange(const DISubrange *N,
17970b57cec5SDimitry Andric                                           SmallVectorImpl<uint64_t> &Record,
17980b57cec5SDimitry Andric                                           unsigned Abbrev) {
17995ffd83dbSDimitry Andric   const uint64_t Version = 2 << 1;
18000b57cec5SDimitry Andric   Record.push_back((uint64_t)N->isDistinct() | Version);
18010b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawCountNode()));
18025ffd83dbSDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawLowerBound()));
18035ffd83dbSDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawUpperBound()));
18045ffd83dbSDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawStride()));
18050b57cec5SDimitry Andric 
18060b57cec5SDimitry Andric   Stream.EmitRecord(bitc::METADATA_SUBRANGE, Record, Abbrev);
18070b57cec5SDimitry Andric   Record.clear();
18080b57cec5SDimitry Andric }
18090b57cec5SDimitry Andric 
1810e8d8bef9SDimitry Andric void ModuleBitcodeWriter::writeDIGenericSubrange(
1811e8d8bef9SDimitry Andric     const DIGenericSubrange *N, SmallVectorImpl<uint64_t> &Record,
1812e8d8bef9SDimitry Andric     unsigned Abbrev) {
1813e8d8bef9SDimitry Andric   Record.push_back((uint64_t)N->isDistinct());
1814e8d8bef9SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawCountNode()));
1815e8d8bef9SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawLowerBound()));
1816e8d8bef9SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawUpperBound()));
1817e8d8bef9SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawStride()));
1818e8d8bef9SDimitry Andric 
1819e8d8bef9SDimitry Andric   Stream.EmitRecord(bitc::METADATA_GENERIC_SUBRANGE, Record, Abbrev);
1820e8d8bef9SDimitry Andric   Record.clear();
1821e8d8bef9SDimitry Andric }
1822e8d8bef9SDimitry Andric 
18230b57cec5SDimitry Andric void ModuleBitcodeWriter::writeDIEnumerator(const DIEnumerator *N,
18240b57cec5SDimitry Andric                                             SmallVectorImpl<uint64_t> &Record,
18250b57cec5SDimitry Andric                                             unsigned Abbrev) {
18265ffd83dbSDimitry Andric   const uint64_t IsBigInt = 1 << 2;
18275ffd83dbSDimitry Andric   Record.push_back(IsBigInt | (N->isUnsigned() << 1) | N->isDistinct());
18285ffd83dbSDimitry Andric   Record.push_back(N->getValue().getBitWidth());
18290b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
18305ffd83dbSDimitry Andric   emitWideAPInt(Record, N->getValue());
18310b57cec5SDimitry Andric 
18320b57cec5SDimitry Andric   Stream.EmitRecord(bitc::METADATA_ENUMERATOR, Record, Abbrev);
18330b57cec5SDimitry Andric   Record.clear();
18340b57cec5SDimitry Andric }
18350b57cec5SDimitry Andric 
18360b57cec5SDimitry Andric void ModuleBitcodeWriter::writeDIBasicType(const DIBasicType *N,
18370b57cec5SDimitry Andric                                            SmallVectorImpl<uint64_t> &Record,
18380b57cec5SDimitry Andric                                            unsigned Abbrev) {
18390b57cec5SDimitry Andric   Record.push_back(N->isDistinct());
18400b57cec5SDimitry Andric   Record.push_back(N->getTag());
18410b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
18420b57cec5SDimitry Andric   Record.push_back(N->getSizeInBits());
18430b57cec5SDimitry Andric   Record.push_back(N->getAlignInBits());
18440b57cec5SDimitry Andric   Record.push_back(N->getEncoding());
18450b57cec5SDimitry Andric   Record.push_back(N->getFlags());
18460b57cec5SDimitry Andric 
18470b57cec5SDimitry Andric   Stream.EmitRecord(bitc::METADATA_BASIC_TYPE, Record, Abbrev);
18480b57cec5SDimitry Andric   Record.clear();
18490b57cec5SDimitry Andric }
18500b57cec5SDimitry Andric 
1851e8d8bef9SDimitry Andric void ModuleBitcodeWriter::writeDIStringType(const DIStringType *N,
1852e8d8bef9SDimitry Andric                                             SmallVectorImpl<uint64_t> &Record,
1853e8d8bef9SDimitry Andric                                             unsigned Abbrev) {
1854e8d8bef9SDimitry Andric   Record.push_back(N->isDistinct());
1855e8d8bef9SDimitry Andric   Record.push_back(N->getTag());
1856e8d8bef9SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1857e8d8bef9SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getStringLength()));
1858e8d8bef9SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getStringLengthExp()));
185904eeddc0SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getStringLocationExp()));
1860e8d8bef9SDimitry Andric   Record.push_back(N->getSizeInBits());
1861e8d8bef9SDimitry Andric   Record.push_back(N->getAlignInBits());
1862e8d8bef9SDimitry Andric   Record.push_back(N->getEncoding());
1863e8d8bef9SDimitry Andric 
1864e8d8bef9SDimitry Andric   Stream.EmitRecord(bitc::METADATA_STRING_TYPE, Record, Abbrev);
1865e8d8bef9SDimitry Andric   Record.clear();
1866e8d8bef9SDimitry Andric }
1867e8d8bef9SDimitry Andric 
18680b57cec5SDimitry Andric void ModuleBitcodeWriter::writeDIDerivedType(const DIDerivedType *N,
18690b57cec5SDimitry Andric                                              SmallVectorImpl<uint64_t> &Record,
18700b57cec5SDimitry Andric                                              unsigned Abbrev) {
18710b57cec5SDimitry Andric   Record.push_back(N->isDistinct());
18720b57cec5SDimitry Andric   Record.push_back(N->getTag());
18730b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
18740b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
18750b57cec5SDimitry Andric   Record.push_back(N->getLine());
18760b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
18770b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
18780b57cec5SDimitry Andric   Record.push_back(N->getSizeInBits());
18790b57cec5SDimitry Andric   Record.push_back(N->getAlignInBits());
18800b57cec5SDimitry Andric   Record.push_back(N->getOffsetInBits());
18810b57cec5SDimitry Andric   Record.push_back(N->getFlags());
18820b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getExtraData()));
18830b57cec5SDimitry Andric 
18840b57cec5SDimitry Andric   // DWARF address space is encoded as N->getDWARFAddressSpace() + 1. 0 means
18850b57cec5SDimitry Andric   // that there is no DWARF address space associated with DIDerivedType.
18860b57cec5SDimitry Andric   if (const auto &DWARFAddressSpace = N->getDWARFAddressSpace())
18870b57cec5SDimitry Andric     Record.push_back(*DWARFAddressSpace + 1);
18880b57cec5SDimitry Andric   else
18890b57cec5SDimitry Andric     Record.push_back(0);
18900b57cec5SDimitry Andric 
1891349cc55cSDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getAnnotations().get()));
1892349cc55cSDimitry Andric 
1893*0fca6ea1SDimitry Andric   if (auto PtrAuthData = N->getPtrAuthData())
1894*0fca6ea1SDimitry Andric     Record.push_back(PtrAuthData->RawData);
1895*0fca6ea1SDimitry Andric   else
1896*0fca6ea1SDimitry Andric     Record.push_back(0);
1897*0fca6ea1SDimitry Andric 
18980b57cec5SDimitry Andric   Stream.EmitRecord(bitc::METADATA_DERIVED_TYPE, Record, Abbrev);
18990b57cec5SDimitry Andric   Record.clear();
19000b57cec5SDimitry Andric }
19010b57cec5SDimitry Andric 
19020b57cec5SDimitry Andric void ModuleBitcodeWriter::writeDICompositeType(
19030b57cec5SDimitry Andric     const DICompositeType *N, SmallVectorImpl<uint64_t> &Record,
19040b57cec5SDimitry Andric     unsigned Abbrev) {
19050b57cec5SDimitry Andric   const unsigned IsNotUsedInOldTypeRef = 0x2;
19060b57cec5SDimitry Andric   Record.push_back(IsNotUsedInOldTypeRef | (unsigned)N->isDistinct());
19070b57cec5SDimitry Andric   Record.push_back(N->getTag());
19080b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
19090b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
19100b57cec5SDimitry Andric   Record.push_back(N->getLine());
19110b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
19120b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
19130b57cec5SDimitry Andric   Record.push_back(N->getSizeInBits());
19140b57cec5SDimitry Andric   Record.push_back(N->getAlignInBits());
19150b57cec5SDimitry Andric   Record.push_back(N->getOffsetInBits());
19160b57cec5SDimitry Andric   Record.push_back(N->getFlags());
19170b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
19180b57cec5SDimitry Andric   Record.push_back(N->getRuntimeLang());
19190b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getVTableHolder()));
19200b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
19210b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawIdentifier()));
19220b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getDiscriminator()));
19235ffd83dbSDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawDataLocation()));
1924e8d8bef9SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawAssociated()));
1925e8d8bef9SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawAllocated()));
1926e8d8bef9SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawRank()));
1927349cc55cSDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getAnnotations().get()));
19280b57cec5SDimitry Andric 
19290b57cec5SDimitry Andric   Stream.EmitRecord(bitc::METADATA_COMPOSITE_TYPE, Record, Abbrev);
19300b57cec5SDimitry Andric   Record.clear();
19310b57cec5SDimitry Andric }
19320b57cec5SDimitry Andric 
19330b57cec5SDimitry Andric void ModuleBitcodeWriter::writeDISubroutineType(
19340b57cec5SDimitry Andric     const DISubroutineType *N, SmallVectorImpl<uint64_t> &Record,
19350b57cec5SDimitry Andric     unsigned Abbrev) {
19360b57cec5SDimitry Andric   const unsigned HasNoOldTypeRefs = 0x2;
19370b57cec5SDimitry Andric   Record.push_back(HasNoOldTypeRefs | (unsigned)N->isDistinct());
19380b57cec5SDimitry Andric   Record.push_back(N->getFlags());
19390b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getTypeArray().get()));
19400b57cec5SDimitry Andric   Record.push_back(N->getCC());
19410b57cec5SDimitry Andric 
19420b57cec5SDimitry Andric   Stream.EmitRecord(bitc::METADATA_SUBROUTINE_TYPE, Record, Abbrev);
19430b57cec5SDimitry Andric   Record.clear();
19440b57cec5SDimitry Andric }
19450b57cec5SDimitry Andric 
19460b57cec5SDimitry Andric void ModuleBitcodeWriter::writeDIFile(const DIFile *N,
19470b57cec5SDimitry Andric                                       SmallVectorImpl<uint64_t> &Record,
19480b57cec5SDimitry Andric                                       unsigned Abbrev) {
19490b57cec5SDimitry Andric   Record.push_back(N->isDistinct());
19500b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawFilename()));
19510b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawDirectory()));
19520b57cec5SDimitry Andric   if (N->getRawChecksum()) {
19530b57cec5SDimitry Andric     Record.push_back(N->getRawChecksum()->Kind);
19540b57cec5SDimitry Andric     Record.push_back(VE.getMetadataOrNullID(N->getRawChecksum()->Value));
19550b57cec5SDimitry Andric   } else {
19560b57cec5SDimitry Andric     // Maintain backwards compatibility with the old internal representation of
19570b57cec5SDimitry Andric     // CSK_None in ChecksumKind by writing nulls here when Checksum is None.
19580b57cec5SDimitry Andric     Record.push_back(0);
19590b57cec5SDimitry Andric     Record.push_back(VE.getMetadataOrNullID(nullptr));
19600b57cec5SDimitry Andric   }
19610b57cec5SDimitry Andric   auto Source = N->getRawSource();
19620b57cec5SDimitry Andric   if (Source)
1963bdd1243dSDimitry Andric     Record.push_back(VE.getMetadataOrNullID(Source));
19640b57cec5SDimitry Andric 
19650b57cec5SDimitry Andric   Stream.EmitRecord(bitc::METADATA_FILE, Record, Abbrev);
19660b57cec5SDimitry Andric   Record.clear();
19670b57cec5SDimitry Andric }
19680b57cec5SDimitry Andric 
19690b57cec5SDimitry Andric void ModuleBitcodeWriter::writeDICompileUnit(const DICompileUnit *N,
19700b57cec5SDimitry Andric                                              SmallVectorImpl<uint64_t> &Record,
19710b57cec5SDimitry Andric                                              unsigned Abbrev) {
19720b57cec5SDimitry Andric   assert(N->isDistinct() && "Expected distinct compile units");
19730b57cec5SDimitry Andric   Record.push_back(/* IsDistinct */ true);
19740b57cec5SDimitry Andric   Record.push_back(N->getSourceLanguage());
19750b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
19760b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawProducer()));
19770b57cec5SDimitry Andric   Record.push_back(N->isOptimized());
19780b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawFlags()));
19790b57cec5SDimitry Andric   Record.push_back(N->getRuntimeVersion());
19800b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawSplitDebugFilename()));
19810b57cec5SDimitry Andric   Record.push_back(N->getEmissionKind());
19820b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getEnumTypes().get()));
19830b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRetainedTypes().get()));
19840b57cec5SDimitry Andric   Record.push_back(/* subprograms */ 0);
19850b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getGlobalVariables().get()));
19860b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getImportedEntities().get()));
19870b57cec5SDimitry Andric   Record.push_back(N->getDWOId());
19880b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getMacros().get()));
19890b57cec5SDimitry Andric   Record.push_back(N->getSplitDebugInlining());
19900b57cec5SDimitry Andric   Record.push_back(N->getDebugInfoForProfiling());
19910b57cec5SDimitry Andric   Record.push_back((unsigned)N->getNameTableKind());
19925ffd83dbSDimitry Andric   Record.push_back(N->getRangesBaseAddress());
19935ffd83dbSDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawSysRoot()));
19945ffd83dbSDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawSDK()));
19950b57cec5SDimitry Andric 
19960b57cec5SDimitry Andric   Stream.EmitRecord(bitc::METADATA_COMPILE_UNIT, Record, Abbrev);
19970b57cec5SDimitry Andric   Record.clear();
19980b57cec5SDimitry Andric }
19990b57cec5SDimitry Andric 
20000b57cec5SDimitry Andric void ModuleBitcodeWriter::writeDISubprogram(const DISubprogram *N,
20010b57cec5SDimitry Andric                                             SmallVectorImpl<uint64_t> &Record,
20020b57cec5SDimitry Andric                                             unsigned Abbrev) {
20030b57cec5SDimitry Andric   const uint64_t HasUnitFlag = 1 << 1;
20040b57cec5SDimitry Andric   const uint64_t HasSPFlagsFlag = 1 << 2;
20050b57cec5SDimitry Andric   Record.push_back(uint64_t(N->isDistinct()) | HasUnitFlag | HasSPFlagsFlag);
20060b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
20070b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
20080b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
20090b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
20100b57cec5SDimitry Andric   Record.push_back(N->getLine());
20110b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getType()));
20120b57cec5SDimitry Andric   Record.push_back(N->getScopeLine());
20130b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getContainingType()));
20140b57cec5SDimitry Andric   Record.push_back(N->getSPFlags());
20150b57cec5SDimitry Andric   Record.push_back(N->getVirtualIndex());
20160b57cec5SDimitry Andric   Record.push_back(N->getFlags());
20170b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawUnit()));
20180b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
20190b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getDeclaration()));
20200b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRetainedNodes().get()));
20210b57cec5SDimitry Andric   Record.push_back(N->getThisAdjustment());
20220b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getThrownTypes().get()));
2023349cc55cSDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getAnnotations().get()));
202481ad6265SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawTargetFuncName()));
20250b57cec5SDimitry Andric 
20260b57cec5SDimitry Andric   Stream.EmitRecord(bitc::METADATA_SUBPROGRAM, Record, Abbrev);
20270b57cec5SDimitry Andric   Record.clear();
20280b57cec5SDimitry Andric }
20290b57cec5SDimitry Andric 
20300b57cec5SDimitry Andric void ModuleBitcodeWriter::writeDILexicalBlock(const DILexicalBlock *N,
20310b57cec5SDimitry Andric                                               SmallVectorImpl<uint64_t> &Record,
20320b57cec5SDimitry Andric                                               unsigned Abbrev) {
20330b57cec5SDimitry Andric   Record.push_back(N->isDistinct());
20340b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
20350b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
20360b57cec5SDimitry Andric   Record.push_back(N->getLine());
20370b57cec5SDimitry Andric   Record.push_back(N->getColumn());
20380b57cec5SDimitry Andric 
20390b57cec5SDimitry Andric   Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK, Record, Abbrev);
20400b57cec5SDimitry Andric   Record.clear();
20410b57cec5SDimitry Andric }
20420b57cec5SDimitry Andric 
20430b57cec5SDimitry Andric void ModuleBitcodeWriter::writeDILexicalBlockFile(
20440b57cec5SDimitry Andric     const DILexicalBlockFile *N, SmallVectorImpl<uint64_t> &Record,
20450b57cec5SDimitry Andric     unsigned Abbrev) {
20460b57cec5SDimitry Andric   Record.push_back(N->isDistinct());
20470b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
20480b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
20490b57cec5SDimitry Andric   Record.push_back(N->getDiscriminator());
20500b57cec5SDimitry Andric 
20510b57cec5SDimitry Andric   Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK_FILE, Record, Abbrev);
20520b57cec5SDimitry Andric   Record.clear();
20530b57cec5SDimitry Andric }
20540b57cec5SDimitry Andric 
20550b57cec5SDimitry Andric void ModuleBitcodeWriter::writeDICommonBlock(const DICommonBlock *N,
20560b57cec5SDimitry Andric                                              SmallVectorImpl<uint64_t> &Record,
20570b57cec5SDimitry Andric                                              unsigned Abbrev) {
20580b57cec5SDimitry Andric   Record.push_back(N->isDistinct());
20590b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
20600b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getDecl()));
20610b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
20620b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
20630b57cec5SDimitry Andric   Record.push_back(N->getLineNo());
20640b57cec5SDimitry Andric 
20650b57cec5SDimitry Andric   Stream.EmitRecord(bitc::METADATA_COMMON_BLOCK, Record, Abbrev);
20660b57cec5SDimitry Andric   Record.clear();
20670b57cec5SDimitry Andric }
20680b57cec5SDimitry Andric 
20690b57cec5SDimitry Andric void ModuleBitcodeWriter::writeDINamespace(const DINamespace *N,
20700b57cec5SDimitry Andric                                            SmallVectorImpl<uint64_t> &Record,
20710b57cec5SDimitry Andric                                            unsigned Abbrev) {
20720b57cec5SDimitry Andric   Record.push_back(N->isDistinct() | N->getExportSymbols() << 1);
20730b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
20740b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
20750b57cec5SDimitry Andric 
20760b57cec5SDimitry Andric   Stream.EmitRecord(bitc::METADATA_NAMESPACE, Record, Abbrev);
20770b57cec5SDimitry Andric   Record.clear();
20780b57cec5SDimitry Andric }
20790b57cec5SDimitry Andric 
20800b57cec5SDimitry Andric void ModuleBitcodeWriter::writeDIMacro(const DIMacro *N,
20810b57cec5SDimitry Andric                                        SmallVectorImpl<uint64_t> &Record,
20820b57cec5SDimitry Andric                                        unsigned Abbrev) {
20830b57cec5SDimitry Andric   Record.push_back(N->isDistinct());
20840b57cec5SDimitry Andric   Record.push_back(N->getMacinfoType());
20850b57cec5SDimitry Andric   Record.push_back(N->getLine());
20860b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
20870b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawValue()));
20880b57cec5SDimitry Andric 
20890b57cec5SDimitry Andric   Stream.EmitRecord(bitc::METADATA_MACRO, Record, Abbrev);
20900b57cec5SDimitry Andric   Record.clear();
20910b57cec5SDimitry Andric }
20920b57cec5SDimitry Andric 
20930b57cec5SDimitry Andric void ModuleBitcodeWriter::writeDIMacroFile(const DIMacroFile *N,
20940b57cec5SDimitry Andric                                            SmallVectorImpl<uint64_t> &Record,
20950b57cec5SDimitry Andric                                            unsigned Abbrev) {
20960b57cec5SDimitry Andric   Record.push_back(N->isDistinct());
20970b57cec5SDimitry Andric   Record.push_back(N->getMacinfoType());
20980b57cec5SDimitry Andric   Record.push_back(N->getLine());
20990b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
21000b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
21010b57cec5SDimitry Andric 
21020b57cec5SDimitry Andric   Stream.EmitRecord(bitc::METADATA_MACRO_FILE, Record, Abbrev);
21030b57cec5SDimitry Andric   Record.clear();
21040b57cec5SDimitry Andric }
21050b57cec5SDimitry Andric 
2106fe6060f1SDimitry Andric void ModuleBitcodeWriter::writeDIArgList(const DIArgList *N,
21075f757f3fSDimitry Andric                                          SmallVectorImpl<uint64_t> &Record) {
2108fe6060f1SDimitry Andric   Record.reserve(N->getArgs().size());
2109fe6060f1SDimitry Andric   for (ValueAsMetadata *MD : N->getArgs())
2110fe6060f1SDimitry Andric     Record.push_back(VE.getMetadataID(MD));
2111fe6060f1SDimitry Andric 
21125f757f3fSDimitry Andric   Stream.EmitRecord(bitc::METADATA_ARG_LIST, Record);
2113fe6060f1SDimitry Andric   Record.clear();
2114fe6060f1SDimitry Andric }
2115fe6060f1SDimitry Andric 
21160b57cec5SDimitry Andric void ModuleBitcodeWriter::writeDIModule(const DIModule *N,
21170b57cec5SDimitry Andric                                         SmallVectorImpl<uint64_t> &Record,
21180b57cec5SDimitry Andric                                         unsigned Abbrev) {
21190b57cec5SDimitry Andric   Record.push_back(N->isDistinct());
21200b57cec5SDimitry Andric   for (auto &I : N->operands())
21210b57cec5SDimitry Andric     Record.push_back(VE.getMetadataOrNullID(I));
21225ffd83dbSDimitry Andric   Record.push_back(N->getLineNo());
2123e8d8bef9SDimitry Andric   Record.push_back(N->getIsDecl());
21240b57cec5SDimitry Andric 
21250b57cec5SDimitry Andric   Stream.EmitRecord(bitc::METADATA_MODULE, Record, Abbrev);
21260b57cec5SDimitry Andric   Record.clear();
21270b57cec5SDimitry Andric }
21280b57cec5SDimitry Andric 
2129bdd1243dSDimitry Andric void ModuleBitcodeWriter::writeDIAssignID(const DIAssignID *N,
2130bdd1243dSDimitry Andric                                           SmallVectorImpl<uint64_t> &Record,
2131bdd1243dSDimitry Andric                                           unsigned Abbrev) {
2132bdd1243dSDimitry Andric   // There are no arguments for this metadata type.
2133bdd1243dSDimitry Andric   Record.push_back(N->isDistinct());
2134bdd1243dSDimitry Andric   Stream.EmitRecord(bitc::METADATA_ASSIGN_ID, Record, Abbrev);
2135bdd1243dSDimitry Andric   Record.clear();
2136bdd1243dSDimitry Andric }
2137bdd1243dSDimitry Andric 
21380b57cec5SDimitry Andric void ModuleBitcodeWriter::writeDITemplateTypeParameter(
21390b57cec5SDimitry Andric     const DITemplateTypeParameter *N, SmallVectorImpl<uint64_t> &Record,
21400b57cec5SDimitry Andric     unsigned Abbrev) {
21410b57cec5SDimitry Andric   Record.push_back(N->isDistinct());
21420b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
21430b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getType()));
21445ffd83dbSDimitry Andric   Record.push_back(N->isDefault());
21450b57cec5SDimitry Andric 
21460b57cec5SDimitry Andric   Stream.EmitRecord(bitc::METADATA_TEMPLATE_TYPE, Record, Abbrev);
21470b57cec5SDimitry Andric   Record.clear();
21480b57cec5SDimitry Andric }
21490b57cec5SDimitry Andric 
21500b57cec5SDimitry Andric void ModuleBitcodeWriter::writeDITemplateValueParameter(
21510b57cec5SDimitry Andric     const DITemplateValueParameter *N, SmallVectorImpl<uint64_t> &Record,
21520b57cec5SDimitry Andric     unsigned Abbrev) {
21530b57cec5SDimitry Andric   Record.push_back(N->isDistinct());
21540b57cec5SDimitry Andric   Record.push_back(N->getTag());
21550b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
21560b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getType()));
21575ffd83dbSDimitry Andric   Record.push_back(N->isDefault());
21580b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getValue()));
21590b57cec5SDimitry Andric 
21600b57cec5SDimitry Andric   Stream.EmitRecord(bitc::METADATA_TEMPLATE_VALUE, Record, Abbrev);
21610b57cec5SDimitry Andric   Record.clear();
21620b57cec5SDimitry Andric }
21630b57cec5SDimitry Andric 
21640b57cec5SDimitry Andric void ModuleBitcodeWriter::writeDIGlobalVariable(
21650b57cec5SDimitry Andric     const DIGlobalVariable *N, SmallVectorImpl<uint64_t> &Record,
21660b57cec5SDimitry Andric     unsigned Abbrev) {
21670b57cec5SDimitry Andric   const uint64_t Version = 2 << 1;
21680b57cec5SDimitry Andric   Record.push_back((uint64_t)N->isDistinct() | Version);
21690b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
21700b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
21710b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
21720b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
21730b57cec5SDimitry Andric   Record.push_back(N->getLine());
21740b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getType()));
21750b57cec5SDimitry Andric   Record.push_back(N->isLocalToUnit());
21760b57cec5SDimitry Andric   Record.push_back(N->isDefinition());
21770b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getStaticDataMemberDeclaration()));
21780b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams()));
21790b57cec5SDimitry Andric   Record.push_back(N->getAlignInBits());
2180349cc55cSDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getAnnotations().get()));
21810b57cec5SDimitry Andric 
21820b57cec5SDimitry Andric   Stream.EmitRecord(bitc::METADATA_GLOBAL_VAR, Record, Abbrev);
21830b57cec5SDimitry Andric   Record.clear();
21840b57cec5SDimitry Andric }
21850b57cec5SDimitry Andric 
21860b57cec5SDimitry Andric void ModuleBitcodeWriter::writeDILocalVariable(
21870b57cec5SDimitry Andric     const DILocalVariable *N, SmallVectorImpl<uint64_t> &Record,
21880b57cec5SDimitry Andric     unsigned Abbrev) {
21890b57cec5SDimitry Andric   // In order to support all possible bitcode formats in BitcodeReader we need
21900b57cec5SDimitry Andric   // to distinguish the following cases:
21910b57cec5SDimitry Andric   // 1) Record has no artificial tag (Record[1]),
21920b57cec5SDimitry Andric   //   has no obsolete inlinedAt field (Record[9]).
21930b57cec5SDimitry Andric   //   In this case Record size will be 8, HasAlignment flag is false.
21940b57cec5SDimitry Andric   // 2) Record has artificial tag (Record[1]),
21950b57cec5SDimitry Andric   //   has no obsolete inlignedAt field (Record[9]).
21960b57cec5SDimitry Andric   //   In this case Record size will be 9, HasAlignment flag is false.
21970b57cec5SDimitry Andric   // 3) Record has both artificial tag (Record[1]) and
21980b57cec5SDimitry Andric   //   obsolete inlignedAt field (Record[9]).
21990b57cec5SDimitry Andric   //   In this case Record size will be 10, HasAlignment flag is false.
22000b57cec5SDimitry Andric   // 4) Record has neither artificial tag, nor inlignedAt field, but
22010b57cec5SDimitry Andric   //   HasAlignment flag is true and Record[8] contains alignment value.
22020b57cec5SDimitry Andric   const uint64_t HasAlignmentFlag = 1 << 1;
22030b57cec5SDimitry Andric   Record.push_back((uint64_t)N->isDistinct() | HasAlignmentFlag);
22040b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
22050b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
22060b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
22070b57cec5SDimitry Andric   Record.push_back(N->getLine());
22080b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getType()));
22090b57cec5SDimitry Andric   Record.push_back(N->getArg());
22100b57cec5SDimitry Andric   Record.push_back(N->getFlags());
22110b57cec5SDimitry Andric   Record.push_back(N->getAlignInBits());
2212349cc55cSDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getAnnotations().get()));
22130b57cec5SDimitry Andric 
22140b57cec5SDimitry Andric   Stream.EmitRecord(bitc::METADATA_LOCAL_VAR, Record, Abbrev);
22150b57cec5SDimitry Andric   Record.clear();
22160b57cec5SDimitry Andric }
22170b57cec5SDimitry Andric 
22180b57cec5SDimitry Andric void ModuleBitcodeWriter::writeDILabel(
22190b57cec5SDimitry Andric     const DILabel *N, SmallVectorImpl<uint64_t> &Record,
22200b57cec5SDimitry Andric     unsigned Abbrev) {
22210b57cec5SDimitry Andric   Record.push_back((uint64_t)N->isDistinct());
22220b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
22230b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
22240b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
22250b57cec5SDimitry Andric   Record.push_back(N->getLine());
22260b57cec5SDimitry Andric 
22270b57cec5SDimitry Andric   Stream.EmitRecord(bitc::METADATA_LABEL, Record, Abbrev);
22280b57cec5SDimitry Andric   Record.clear();
22290b57cec5SDimitry Andric }
22300b57cec5SDimitry Andric 
22310b57cec5SDimitry Andric void ModuleBitcodeWriter::writeDIExpression(const DIExpression *N,
22320b57cec5SDimitry Andric                                             SmallVectorImpl<uint64_t> &Record,
22330b57cec5SDimitry Andric                                             unsigned Abbrev) {
22340b57cec5SDimitry Andric   Record.reserve(N->getElements().size() + 1);
22350b57cec5SDimitry Andric   const uint64_t Version = 3 << 1;
22360b57cec5SDimitry Andric   Record.push_back((uint64_t)N->isDistinct() | Version);
22370b57cec5SDimitry Andric   Record.append(N->elements_begin(), N->elements_end());
22380b57cec5SDimitry Andric 
22390b57cec5SDimitry Andric   Stream.EmitRecord(bitc::METADATA_EXPRESSION, Record, Abbrev);
22400b57cec5SDimitry Andric   Record.clear();
22410b57cec5SDimitry Andric }
22420b57cec5SDimitry Andric 
22430b57cec5SDimitry Andric void ModuleBitcodeWriter::writeDIGlobalVariableExpression(
22440b57cec5SDimitry Andric     const DIGlobalVariableExpression *N, SmallVectorImpl<uint64_t> &Record,
22450b57cec5SDimitry Andric     unsigned Abbrev) {
22460b57cec5SDimitry Andric   Record.push_back(N->isDistinct());
22470b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getVariable()));
22480b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getExpression()));
22490b57cec5SDimitry Andric 
22500b57cec5SDimitry Andric   Stream.EmitRecord(bitc::METADATA_GLOBAL_VAR_EXPR, Record, Abbrev);
22510b57cec5SDimitry Andric   Record.clear();
22520b57cec5SDimitry Andric }
22530b57cec5SDimitry Andric 
22540b57cec5SDimitry Andric void ModuleBitcodeWriter::writeDIObjCProperty(const DIObjCProperty *N,
22550b57cec5SDimitry Andric                                               SmallVectorImpl<uint64_t> &Record,
22560b57cec5SDimitry Andric                                               unsigned Abbrev) {
22570b57cec5SDimitry Andric   Record.push_back(N->isDistinct());
22580b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
22590b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
22600b57cec5SDimitry Andric   Record.push_back(N->getLine());
22610b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawSetterName()));
22620b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawGetterName()));
22630b57cec5SDimitry Andric   Record.push_back(N->getAttributes());
22640b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getType()));
22650b57cec5SDimitry Andric 
22660b57cec5SDimitry Andric   Stream.EmitRecord(bitc::METADATA_OBJC_PROPERTY, Record, Abbrev);
22670b57cec5SDimitry Andric   Record.clear();
22680b57cec5SDimitry Andric }
22690b57cec5SDimitry Andric 
22700b57cec5SDimitry Andric void ModuleBitcodeWriter::writeDIImportedEntity(
22710b57cec5SDimitry Andric     const DIImportedEntity *N, SmallVectorImpl<uint64_t> &Record,
22720b57cec5SDimitry Andric     unsigned Abbrev) {
22730b57cec5SDimitry Andric   Record.push_back(N->isDistinct());
22740b57cec5SDimitry Andric   Record.push_back(N->getTag());
22750b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
22760b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getEntity()));
22770b57cec5SDimitry Andric   Record.push_back(N->getLine());
22780b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
22790b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawFile()));
2280349cc55cSDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
22810b57cec5SDimitry Andric 
22820b57cec5SDimitry Andric   Stream.EmitRecord(bitc::METADATA_IMPORTED_ENTITY, Record, Abbrev);
22830b57cec5SDimitry Andric   Record.clear();
22840b57cec5SDimitry Andric }
22850b57cec5SDimitry Andric 
22860b57cec5SDimitry Andric unsigned ModuleBitcodeWriter::createNamedMetadataAbbrev() {
22870b57cec5SDimitry Andric   auto Abbv = std::make_shared<BitCodeAbbrev>();
22880b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_NAME));
22890b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
22900b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
22910b57cec5SDimitry Andric   return Stream.EmitAbbrev(std::move(Abbv));
22920b57cec5SDimitry Andric }
22930b57cec5SDimitry Andric 
22940b57cec5SDimitry Andric void ModuleBitcodeWriter::writeNamedMetadata(
22950b57cec5SDimitry Andric     SmallVectorImpl<uint64_t> &Record) {
22960b57cec5SDimitry Andric   if (M.named_metadata_empty())
22970b57cec5SDimitry Andric     return;
22980b57cec5SDimitry Andric 
22990b57cec5SDimitry Andric   unsigned Abbrev = createNamedMetadataAbbrev();
23000b57cec5SDimitry Andric   for (const NamedMDNode &NMD : M.named_metadata()) {
23010b57cec5SDimitry Andric     // Write name.
23020b57cec5SDimitry Andric     StringRef Str = NMD.getName();
23030b57cec5SDimitry Andric     Record.append(Str.bytes_begin(), Str.bytes_end());
23040b57cec5SDimitry Andric     Stream.EmitRecord(bitc::METADATA_NAME, Record, Abbrev);
23050b57cec5SDimitry Andric     Record.clear();
23060b57cec5SDimitry Andric 
23070b57cec5SDimitry Andric     // Write named metadata operands.
23080b57cec5SDimitry Andric     for (const MDNode *N : NMD.operands())
23090b57cec5SDimitry Andric       Record.push_back(VE.getMetadataID(N));
23100b57cec5SDimitry Andric     Stream.EmitRecord(bitc::METADATA_NAMED_NODE, Record, 0);
23110b57cec5SDimitry Andric     Record.clear();
23120b57cec5SDimitry Andric   }
23130b57cec5SDimitry Andric }
23140b57cec5SDimitry Andric 
23150b57cec5SDimitry Andric unsigned ModuleBitcodeWriter::createMetadataStringsAbbrev() {
23160b57cec5SDimitry Andric   auto Abbv = std::make_shared<BitCodeAbbrev>();
23170b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_STRINGS));
23180b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of strings
23190b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // offset to chars
23200b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
23210b57cec5SDimitry Andric   return Stream.EmitAbbrev(std::move(Abbv));
23220b57cec5SDimitry Andric }
23230b57cec5SDimitry Andric 
23240b57cec5SDimitry Andric /// Write out a record for MDString.
23250b57cec5SDimitry Andric ///
23260b57cec5SDimitry Andric /// All the metadata strings in a metadata block are emitted in a single
23270b57cec5SDimitry Andric /// record.  The sizes and strings themselves are shoved into a blob.
23280b57cec5SDimitry Andric void ModuleBitcodeWriter::writeMetadataStrings(
23290b57cec5SDimitry Andric     ArrayRef<const Metadata *> Strings, SmallVectorImpl<uint64_t> &Record) {
23300b57cec5SDimitry Andric   if (Strings.empty())
23310b57cec5SDimitry Andric     return;
23320b57cec5SDimitry Andric 
23330b57cec5SDimitry Andric   // Start the record with the number of strings.
23340b57cec5SDimitry Andric   Record.push_back(bitc::METADATA_STRINGS);
23350b57cec5SDimitry Andric   Record.push_back(Strings.size());
23360b57cec5SDimitry Andric 
23370b57cec5SDimitry Andric   // Emit the sizes of the strings in the blob.
23380b57cec5SDimitry Andric   SmallString<256> Blob;
23390b57cec5SDimitry Andric   {
23400b57cec5SDimitry Andric     BitstreamWriter W(Blob);
23410b57cec5SDimitry Andric     for (const Metadata *MD : Strings)
23420b57cec5SDimitry Andric       W.EmitVBR(cast<MDString>(MD)->getLength(), 6);
23430b57cec5SDimitry Andric     W.FlushToWord();
23440b57cec5SDimitry Andric   }
23450b57cec5SDimitry Andric 
23460b57cec5SDimitry Andric   // Add the offset to the strings to the record.
23470b57cec5SDimitry Andric   Record.push_back(Blob.size());
23480b57cec5SDimitry Andric 
23490b57cec5SDimitry Andric   // Add the strings to the blob.
23500b57cec5SDimitry Andric   for (const Metadata *MD : Strings)
23510b57cec5SDimitry Andric     Blob.append(cast<MDString>(MD)->getString());
23520b57cec5SDimitry Andric 
23530b57cec5SDimitry Andric   // Emit the final record.
23540b57cec5SDimitry Andric   Stream.EmitRecordWithBlob(createMetadataStringsAbbrev(), Record, Blob);
23550b57cec5SDimitry Andric   Record.clear();
23560b57cec5SDimitry Andric }
23570b57cec5SDimitry Andric 
23580b57cec5SDimitry Andric // Generates an enum to use as an index in the Abbrev array of Metadata record.
23590b57cec5SDimitry Andric enum MetadataAbbrev : unsigned {
23600b57cec5SDimitry Andric #define HANDLE_MDNODE_LEAF(CLASS) CLASS##AbbrevID,
23610b57cec5SDimitry Andric #include "llvm/IR/Metadata.def"
23620b57cec5SDimitry Andric   LastPlusOne
23630b57cec5SDimitry Andric };
23640b57cec5SDimitry Andric 
23650b57cec5SDimitry Andric void ModuleBitcodeWriter::writeMetadataRecords(
23660b57cec5SDimitry Andric     ArrayRef<const Metadata *> MDs, SmallVectorImpl<uint64_t> &Record,
23670b57cec5SDimitry Andric     std::vector<unsigned> *MDAbbrevs, std::vector<uint64_t> *IndexPos) {
23680b57cec5SDimitry Andric   if (MDs.empty())
23690b57cec5SDimitry Andric     return;
23700b57cec5SDimitry Andric 
23710b57cec5SDimitry Andric   // Initialize MDNode abbreviations.
23720b57cec5SDimitry Andric #define HANDLE_MDNODE_LEAF(CLASS) unsigned CLASS##Abbrev = 0;
23730b57cec5SDimitry Andric #include "llvm/IR/Metadata.def"
23740b57cec5SDimitry Andric 
23750b57cec5SDimitry Andric   for (const Metadata *MD : MDs) {
23760b57cec5SDimitry Andric     if (IndexPos)
23770b57cec5SDimitry Andric       IndexPos->push_back(Stream.GetCurrentBitNo());
23780b57cec5SDimitry Andric     if (const MDNode *N = dyn_cast<MDNode>(MD)) {
23790b57cec5SDimitry Andric       assert(N->isResolved() && "Expected forward references to be resolved");
23800b57cec5SDimitry Andric 
23810b57cec5SDimitry Andric       switch (N->getMetadataID()) {
23820b57cec5SDimitry Andric       default:
23830b57cec5SDimitry Andric         llvm_unreachable("Invalid MDNode subclass");
23840b57cec5SDimitry Andric #define HANDLE_MDNODE_LEAF(CLASS)                                              \
23850b57cec5SDimitry Andric   case Metadata::CLASS##Kind:                                                  \
23860b57cec5SDimitry Andric     if (MDAbbrevs)                                                             \
23870b57cec5SDimitry Andric       write##CLASS(cast<CLASS>(N), Record,                                     \
23880b57cec5SDimitry Andric                    (*MDAbbrevs)[MetadataAbbrev::CLASS##AbbrevID]);             \
23890b57cec5SDimitry Andric     else                                                                       \
23900b57cec5SDimitry Andric       write##CLASS(cast<CLASS>(N), Record, CLASS##Abbrev);                     \
23910b57cec5SDimitry Andric     continue;
23920b57cec5SDimitry Andric #include "llvm/IR/Metadata.def"
23930b57cec5SDimitry Andric       }
23940b57cec5SDimitry Andric     }
23955f757f3fSDimitry Andric     if (auto *AL = dyn_cast<DIArgList>(MD)) {
23965f757f3fSDimitry Andric       writeDIArgList(AL, Record);
23975f757f3fSDimitry Andric       continue;
23985f757f3fSDimitry Andric     }
23990b57cec5SDimitry Andric     writeValueAsMetadata(cast<ValueAsMetadata>(MD), Record);
24000b57cec5SDimitry Andric   }
24010b57cec5SDimitry Andric }
24020b57cec5SDimitry Andric 
24030b57cec5SDimitry Andric void ModuleBitcodeWriter::writeModuleMetadata() {
24040b57cec5SDimitry Andric   if (!VE.hasMDs() && M.named_metadata_empty())
24050b57cec5SDimitry Andric     return;
24060b57cec5SDimitry Andric 
24070b57cec5SDimitry Andric   Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 4);
24080b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
24090b57cec5SDimitry Andric 
24100b57cec5SDimitry Andric   // Emit all abbrevs upfront, so that the reader can jump in the middle of the
24110b57cec5SDimitry Andric   // block and load any metadata.
24120b57cec5SDimitry Andric   std::vector<unsigned> MDAbbrevs;
24130b57cec5SDimitry Andric 
24140b57cec5SDimitry Andric   MDAbbrevs.resize(MetadataAbbrev::LastPlusOne);
24150b57cec5SDimitry Andric   MDAbbrevs[MetadataAbbrev::DILocationAbbrevID] = createDILocationAbbrev();
24160b57cec5SDimitry Andric   MDAbbrevs[MetadataAbbrev::GenericDINodeAbbrevID] =
24170b57cec5SDimitry Andric       createGenericDINodeAbbrev();
24180b57cec5SDimitry Andric 
24190b57cec5SDimitry Andric   auto Abbv = std::make_shared<BitCodeAbbrev>();
24200b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_INDEX_OFFSET));
24210b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
24220b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
24230b57cec5SDimitry Andric   unsigned OffsetAbbrev = Stream.EmitAbbrev(std::move(Abbv));
24240b57cec5SDimitry Andric 
24250b57cec5SDimitry Andric   Abbv = std::make_shared<BitCodeAbbrev>();
24260b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_INDEX));
24270b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
24280b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
24290b57cec5SDimitry Andric   unsigned IndexAbbrev = Stream.EmitAbbrev(std::move(Abbv));
24300b57cec5SDimitry Andric 
24310b57cec5SDimitry Andric   // Emit MDStrings together upfront.
24320b57cec5SDimitry Andric   writeMetadataStrings(VE.getMDStrings(), Record);
24330b57cec5SDimitry Andric 
24340b57cec5SDimitry Andric   // We only emit an index for the metadata record if we have more than a given
24350b57cec5SDimitry Andric   // (naive) threshold of metadatas, otherwise it is not worth it.
24360b57cec5SDimitry Andric   if (VE.getNonMDStrings().size() > IndexThreshold) {
24370b57cec5SDimitry Andric     // Write a placeholder value in for the offset of the metadata index,
24380b57cec5SDimitry Andric     // which is written after the records, so that it can include
24390b57cec5SDimitry Andric     // the offset of each entry. The placeholder offset will be
24400b57cec5SDimitry Andric     // updated after all records are emitted.
24410b57cec5SDimitry Andric     uint64_t Vals[] = {0, 0};
24420b57cec5SDimitry Andric     Stream.EmitRecord(bitc::METADATA_INDEX_OFFSET, Vals, OffsetAbbrev);
24430b57cec5SDimitry Andric   }
24440b57cec5SDimitry Andric 
24450b57cec5SDimitry Andric   // Compute and save the bit offset to the current position, which will be
24460b57cec5SDimitry Andric   // patched when we emit the index later. We can simply subtract the 64-bit
24470b57cec5SDimitry Andric   // fixed size from the current bit number to get the location to backpatch.
24480b57cec5SDimitry Andric   uint64_t IndexOffsetRecordBitPos = Stream.GetCurrentBitNo();
24490b57cec5SDimitry Andric 
24500b57cec5SDimitry Andric   // This index will contain the bitpos for each individual record.
24510b57cec5SDimitry Andric   std::vector<uint64_t> IndexPos;
24520b57cec5SDimitry Andric   IndexPos.reserve(VE.getNonMDStrings().size());
24530b57cec5SDimitry Andric 
24540b57cec5SDimitry Andric   // Write all the records
24550b57cec5SDimitry Andric   writeMetadataRecords(VE.getNonMDStrings(), Record, &MDAbbrevs, &IndexPos);
24560b57cec5SDimitry Andric 
24570b57cec5SDimitry Andric   if (VE.getNonMDStrings().size() > IndexThreshold) {
24580b57cec5SDimitry Andric     // Now that we have emitted all the records we will emit the index. But
24590b57cec5SDimitry Andric     // first
24600b57cec5SDimitry Andric     // backpatch the forward reference so that the reader can skip the records
24610b57cec5SDimitry Andric     // efficiently.
24620b57cec5SDimitry Andric     Stream.BackpatchWord64(IndexOffsetRecordBitPos - 64,
24630b57cec5SDimitry Andric                            Stream.GetCurrentBitNo() - IndexOffsetRecordBitPos);
24640b57cec5SDimitry Andric 
24650b57cec5SDimitry Andric     // Delta encode the index.
24660b57cec5SDimitry Andric     uint64_t PreviousValue = IndexOffsetRecordBitPos;
24670b57cec5SDimitry Andric     for (auto &Elt : IndexPos) {
24680b57cec5SDimitry Andric       auto EltDelta = Elt - PreviousValue;
24690b57cec5SDimitry Andric       PreviousValue = Elt;
24700b57cec5SDimitry Andric       Elt = EltDelta;
24710b57cec5SDimitry Andric     }
24720b57cec5SDimitry Andric     // Emit the index record.
24730b57cec5SDimitry Andric     Stream.EmitRecord(bitc::METADATA_INDEX, IndexPos, IndexAbbrev);
24740b57cec5SDimitry Andric     IndexPos.clear();
24750b57cec5SDimitry Andric   }
24760b57cec5SDimitry Andric 
24770b57cec5SDimitry Andric   // Write the named metadata now.
24780b57cec5SDimitry Andric   writeNamedMetadata(Record);
24790b57cec5SDimitry Andric 
24800b57cec5SDimitry Andric   auto AddDeclAttachedMetadata = [&](const GlobalObject &GO) {
24810b57cec5SDimitry Andric     SmallVector<uint64_t, 4> Record;
24820b57cec5SDimitry Andric     Record.push_back(VE.getValueID(&GO));
24830b57cec5SDimitry Andric     pushGlobalMetadataAttachment(Record, GO);
24840b57cec5SDimitry Andric     Stream.EmitRecord(bitc::METADATA_GLOBAL_DECL_ATTACHMENT, Record);
24850b57cec5SDimitry Andric   };
24860b57cec5SDimitry Andric   for (const Function &F : M)
24870b57cec5SDimitry Andric     if (F.isDeclaration() && F.hasMetadata())
24880b57cec5SDimitry Andric       AddDeclAttachedMetadata(F);
24890b57cec5SDimitry Andric   // FIXME: Only store metadata for declarations here, and move data for global
24900b57cec5SDimitry Andric   // variable definitions to a separate block (PR28134).
24910b57cec5SDimitry Andric   for (const GlobalVariable &GV : M.globals())
24920b57cec5SDimitry Andric     if (GV.hasMetadata())
24930b57cec5SDimitry Andric       AddDeclAttachedMetadata(GV);
24940b57cec5SDimitry Andric 
24950b57cec5SDimitry Andric   Stream.ExitBlock();
24960b57cec5SDimitry Andric }
24970b57cec5SDimitry Andric 
24980b57cec5SDimitry Andric void ModuleBitcodeWriter::writeFunctionMetadata(const Function &F) {
24990b57cec5SDimitry Andric   if (!VE.hasMDs())
25000b57cec5SDimitry Andric     return;
25010b57cec5SDimitry Andric 
25020b57cec5SDimitry Andric   Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
25030b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
25040b57cec5SDimitry Andric   writeMetadataStrings(VE.getMDStrings(), Record);
25050b57cec5SDimitry Andric   writeMetadataRecords(VE.getNonMDStrings(), Record);
25060b57cec5SDimitry Andric   Stream.ExitBlock();
25070b57cec5SDimitry Andric }
25080b57cec5SDimitry Andric 
25090b57cec5SDimitry Andric void ModuleBitcodeWriter::pushGlobalMetadataAttachment(
25100b57cec5SDimitry Andric     SmallVectorImpl<uint64_t> &Record, const GlobalObject &GO) {
25110b57cec5SDimitry Andric   // [n x [id, mdnode]]
25120b57cec5SDimitry Andric   SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
25130b57cec5SDimitry Andric   GO.getAllMetadata(MDs);
25140b57cec5SDimitry Andric   for (const auto &I : MDs) {
25150b57cec5SDimitry Andric     Record.push_back(I.first);
25160b57cec5SDimitry Andric     Record.push_back(VE.getMetadataID(I.second));
25170b57cec5SDimitry Andric   }
25180b57cec5SDimitry Andric }
25190b57cec5SDimitry Andric 
25200b57cec5SDimitry Andric void ModuleBitcodeWriter::writeFunctionMetadataAttachment(const Function &F) {
25210b57cec5SDimitry Andric   Stream.EnterSubblock(bitc::METADATA_ATTACHMENT_ID, 3);
25220b57cec5SDimitry Andric 
25230b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
25240b57cec5SDimitry Andric 
25250b57cec5SDimitry Andric   if (F.hasMetadata()) {
25260b57cec5SDimitry Andric     pushGlobalMetadataAttachment(Record, F);
25270b57cec5SDimitry Andric     Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
25280b57cec5SDimitry Andric     Record.clear();
25290b57cec5SDimitry Andric   }
25300b57cec5SDimitry Andric 
25310b57cec5SDimitry Andric   // Write metadata attachments
25320b57cec5SDimitry Andric   // METADATA_ATTACHMENT - [m x [value, [n x [id, mdnode]]]
25330b57cec5SDimitry Andric   SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
25340b57cec5SDimitry Andric   for (const BasicBlock &BB : F)
25350b57cec5SDimitry Andric     for (const Instruction &I : BB) {
25360b57cec5SDimitry Andric       MDs.clear();
25370b57cec5SDimitry Andric       I.getAllMetadataOtherThanDebugLoc(MDs);
25380b57cec5SDimitry Andric 
25390b57cec5SDimitry Andric       // If no metadata, ignore instruction.
25400b57cec5SDimitry Andric       if (MDs.empty()) continue;
25410b57cec5SDimitry Andric 
25420b57cec5SDimitry Andric       Record.push_back(VE.getInstructionID(&I));
25430b57cec5SDimitry Andric 
25440b57cec5SDimitry Andric       for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
25450b57cec5SDimitry Andric         Record.push_back(MDs[i].first);
25460b57cec5SDimitry Andric         Record.push_back(VE.getMetadataID(MDs[i].second));
25470b57cec5SDimitry Andric       }
25480b57cec5SDimitry Andric       Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
25490b57cec5SDimitry Andric       Record.clear();
25500b57cec5SDimitry Andric     }
25510b57cec5SDimitry Andric 
25520b57cec5SDimitry Andric   Stream.ExitBlock();
25530b57cec5SDimitry Andric }
25540b57cec5SDimitry Andric 
25550b57cec5SDimitry Andric void ModuleBitcodeWriter::writeModuleMetadataKinds() {
25560b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
25570b57cec5SDimitry Andric 
25580b57cec5SDimitry Andric   // Write metadata kinds
25590b57cec5SDimitry Andric   // METADATA_KIND - [n x [id, name]]
25600b57cec5SDimitry Andric   SmallVector<StringRef, 8> Names;
25610b57cec5SDimitry Andric   M.getMDKindNames(Names);
25620b57cec5SDimitry Andric 
25630b57cec5SDimitry Andric   if (Names.empty()) return;
25640b57cec5SDimitry Andric 
25650b57cec5SDimitry Andric   Stream.EnterSubblock(bitc::METADATA_KIND_BLOCK_ID, 3);
25660b57cec5SDimitry Andric 
25670b57cec5SDimitry Andric   for (unsigned MDKindID = 0, e = Names.size(); MDKindID != e; ++MDKindID) {
25680b57cec5SDimitry Andric     Record.push_back(MDKindID);
25690b57cec5SDimitry Andric     StringRef KName = Names[MDKindID];
25700b57cec5SDimitry Andric     Record.append(KName.begin(), KName.end());
25710b57cec5SDimitry Andric 
25720b57cec5SDimitry Andric     Stream.EmitRecord(bitc::METADATA_KIND, Record, 0);
25730b57cec5SDimitry Andric     Record.clear();
25740b57cec5SDimitry Andric   }
25750b57cec5SDimitry Andric 
25760b57cec5SDimitry Andric   Stream.ExitBlock();
25770b57cec5SDimitry Andric }
25780b57cec5SDimitry Andric 
25790b57cec5SDimitry Andric void ModuleBitcodeWriter::writeOperandBundleTags() {
25800b57cec5SDimitry Andric   // Write metadata kinds
25810b57cec5SDimitry Andric   //
25820b57cec5SDimitry Andric   // OPERAND_BUNDLE_TAGS_BLOCK_ID : N x OPERAND_BUNDLE_TAG
25830b57cec5SDimitry Andric   //
25840b57cec5SDimitry Andric   // OPERAND_BUNDLE_TAG - [strchr x N]
25850b57cec5SDimitry Andric 
25860b57cec5SDimitry Andric   SmallVector<StringRef, 8> Tags;
25870b57cec5SDimitry Andric   M.getOperandBundleTags(Tags);
25880b57cec5SDimitry Andric 
25890b57cec5SDimitry Andric   if (Tags.empty())
25900b57cec5SDimitry Andric     return;
25910b57cec5SDimitry Andric 
25920b57cec5SDimitry Andric   Stream.EnterSubblock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID, 3);
25930b57cec5SDimitry Andric 
25940b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
25950b57cec5SDimitry Andric 
25960b57cec5SDimitry Andric   for (auto Tag : Tags) {
25970b57cec5SDimitry Andric     Record.append(Tag.begin(), Tag.end());
25980b57cec5SDimitry Andric 
25990b57cec5SDimitry Andric     Stream.EmitRecord(bitc::OPERAND_BUNDLE_TAG, Record, 0);
26000b57cec5SDimitry Andric     Record.clear();
26010b57cec5SDimitry Andric   }
26020b57cec5SDimitry Andric 
26030b57cec5SDimitry Andric   Stream.ExitBlock();
26040b57cec5SDimitry Andric }
26050b57cec5SDimitry Andric 
26060b57cec5SDimitry Andric void ModuleBitcodeWriter::writeSyncScopeNames() {
26070b57cec5SDimitry Andric   SmallVector<StringRef, 8> SSNs;
26080b57cec5SDimitry Andric   M.getContext().getSyncScopeNames(SSNs);
26090b57cec5SDimitry Andric   if (SSNs.empty())
26100b57cec5SDimitry Andric     return;
26110b57cec5SDimitry Andric 
26120b57cec5SDimitry Andric   Stream.EnterSubblock(bitc::SYNC_SCOPE_NAMES_BLOCK_ID, 2);
26130b57cec5SDimitry Andric 
26140b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
26150b57cec5SDimitry Andric   for (auto SSN : SSNs) {
26160b57cec5SDimitry Andric     Record.append(SSN.begin(), SSN.end());
26170b57cec5SDimitry Andric     Stream.EmitRecord(bitc::SYNC_SCOPE_NAME, Record, 0);
26180b57cec5SDimitry Andric     Record.clear();
26190b57cec5SDimitry Andric   }
26200b57cec5SDimitry Andric 
26210b57cec5SDimitry Andric   Stream.ExitBlock();
26220b57cec5SDimitry Andric }
26230b57cec5SDimitry Andric 
26240b57cec5SDimitry Andric void ModuleBitcodeWriter::writeConstants(unsigned FirstVal, unsigned LastVal,
26250b57cec5SDimitry Andric                                          bool isGlobal) {
26260b57cec5SDimitry Andric   if (FirstVal == LastVal) return;
26270b57cec5SDimitry Andric 
26280b57cec5SDimitry Andric   Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 4);
26290b57cec5SDimitry Andric 
26300b57cec5SDimitry Andric   unsigned AggregateAbbrev = 0;
26310b57cec5SDimitry Andric   unsigned String8Abbrev = 0;
26320b57cec5SDimitry Andric   unsigned CString7Abbrev = 0;
26330b57cec5SDimitry Andric   unsigned CString6Abbrev = 0;
26340b57cec5SDimitry Andric   // If this is a constant pool for the module, emit module-specific abbrevs.
26350b57cec5SDimitry Andric   if (isGlobal) {
26360b57cec5SDimitry Andric     // Abbrev for CST_CODE_AGGREGATE.
26370b57cec5SDimitry Andric     auto Abbv = std::make_shared<BitCodeAbbrev>();
26380b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_AGGREGATE));
26390b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
26400b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal+1)));
26410b57cec5SDimitry Andric     AggregateAbbrev = Stream.EmitAbbrev(std::move(Abbv));
26420b57cec5SDimitry Andric 
26430b57cec5SDimitry Andric     // Abbrev for CST_CODE_STRING.
26440b57cec5SDimitry Andric     Abbv = std::make_shared<BitCodeAbbrev>();
26450b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_STRING));
26460b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
26470b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
26480b57cec5SDimitry Andric     String8Abbrev = Stream.EmitAbbrev(std::move(Abbv));
26490b57cec5SDimitry Andric     // Abbrev for CST_CODE_CSTRING.
26500b57cec5SDimitry Andric     Abbv = std::make_shared<BitCodeAbbrev>();
26510b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
26520b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
26530b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
26540b57cec5SDimitry Andric     CString7Abbrev = Stream.EmitAbbrev(std::move(Abbv));
26550b57cec5SDimitry Andric     // Abbrev for CST_CODE_CSTRING.
26560b57cec5SDimitry Andric     Abbv = std::make_shared<BitCodeAbbrev>();
26570b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
26580b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
26590b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
26600b57cec5SDimitry Andric     CString6Abbrev = Stream.EmitAbbrev(std::move(Abbv));
26610b57cec5SDimitry Andric   }
26620b57cec5SDimitry Andric 
26630b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
26640b57cec5SDimitry Andric 
26650b57cec5SDimitry Andric   const ValueEnumerator::ValueList &Vals = VE.getValues();
26660b57cec5SDimitry Andric   Type *LastTy = nullptr;
26670b57cec5SDimitry Andric   for (unsigned i = FirstVal; i != LastVal; ++i) {
26680b57cec5SDimitry Andric     const Value *V = Vals[i].first;
26690b57cec5SDimitry Andric     // If we need to switch types, do so now.
26700b57cec5SDimitry Andric     if (V->getType() != LastTy) {
26710b57cec5SDimitry Andric       LastTy = V->getType();
26720b57cec5SDimitry Andric       Record.push_back(VE.getTypeID(LastTy));
26730b57cec5SDimitry Andric       Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record,
26740b57cec5SDimitry Andric                         CONSTANTS_SETTYPE_ABBREV);
26750b57cec5SDimitry Andric       Record.clear();
26760b57cec5SDimitry Andric     }
26770b57cec5SDimitry Andric 
26780b57cec5SDimitry Andric     if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
267904eeddc0SDimitry Andric       Record.push_back(VE.getTypeID(IA->getFunctionType()));
2680fe6060f1SDimitry Andric       Record.push_back(
2681fe6060f1SDimitry Andric           unsigned(IA->hasSideEffects()) | unsigned(IA->isAlignStack()) << 1 |
2682fe6060f1SDimitry Andric           unsigned(IA->getDialect() & 1) << 2 | unsigned(IA->canThrow()) << 3);
26830b57cec5SDimitry Andric 
26840b57cec5SDimitry Andric       // Add the asm string.
26850b57cec5SDimitry Andric       const std::string &AsmStr = IA->getAsmString();
26860b57cec5SDimitry Andric       Record.push_back(AsmStr.size());
26870b57cec5SDimitry Andric       Record.append(AsmStr.begin(), AsmStr.end());
26880b57cec5SDimitry Andric 
26890b57cec5SDimitry Andric       // Add the constraint string.
26900b57cec5SDimitry Andric       const std::string &ConstraintStr = IA->getConstraintString();
26910b57cec5SDimitry Andric       Record.push_back(ConstraintStr.size());
26920b57cec5SDimitry Andric       Record.append(ConstraintStr.begin(), ConstraintStr.end());
26930b57cec5SDimitry Andric       Stream.EmitRecord(bitc::CST_CODE_INLINEASM, Record);
26940b57cec5SDimitry Andric       Record.clear();
26950b57cec5SDimitry Andric       continue;
26960b57cec5SDimitry Andric     }
26970b57cec5SDimitry Andric     const Constant *C = cast<Constant>(V);
26980b57cec5SDimitry Andric     unsigned Code = -1U;
26990b57cec5SDimitry Andric     unsigned AbbrevToUse = 0;
27000b57cec5SDimitry Andric     if (C->isNullValue()) {
27010b57cec5SDimitry Andric       Code = bitc::CST_CODE_NULL;
2702e8d8bef9SDimitry Andric     } else if (isa<PoisonValue>(C)) {
2703e8d8bef9SDimitry Andric       Code = bitc::CST_CODE_POISON;
27040b57cec5SDimitry Andric     } else if (isa<UndefValue>(C)) {
27050b57cec5SDimitry Andric       Code = bitc::CST_CODE_UNDEF;
27060b57cec5SDimitry Andric     } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {
27070b57cec5SDimitry Andric       if (IV->getBitWidth() <= 64) {
27080b57cec5SDimitry Andric         uint64_t V = IV->getSExtValue();
27090b57cec5SDimitry Andric         emitSignedInt64(Record, V);
27100b57cec5SDimitry Andric         Code = bitc::CST_CODE_INTEGER;
27110b57cec5SDimitry Andric         AbbrevToUse = CONSTANTS_INTEGER_ABBREV;
27120b57cec5SDimitry Andric       } else {                             // Wide integers, > 64 bits in size.
27135ffd83dbSDimitry Andric         emitWideAPInt(Record, IV->getValue());
27140b57cec5SDimitry Andric         Code = bitc::CST_CODE_WIDE_INTEGER;
27150b57cec5SDimitry Andric       }
27160b57cec5SDimitry Andric     } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
27170b57cec5SDimitry Andric       Code = bitc::CST_CODE_FLOAT;
2718*0fca6ea1SDimitry Andric       Type *Ty = CFP->getType()->getScalarType();
27195ffd83dbSDimitry Andric       if (Ty->isHalfTy() || Ty->isBFloatTy() || Ty->isFloatTy() ||
27205ffd83dbSDimitry Andric           Ty->isDoubleTy()) {
27210b57cec5SDimitry Andric         Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
27220b57cec5SDimitry Andric       } else if (Ty->isX86_FP80Ty()) {
27230b57cec5SDimitry Andric         // api needed to prevent premature destruction
27240b57cec5SDimitry Andric         // bits are not in the same order as a normal i80 APInt, compensate.
27250b57cec5SDimitry Andric         APInt api = CFP->getValueAPF().bitcastToAPInt();
27260b57cec5SDimitry Andric         const uint64_t *p = api.getRawData();
27270b57cec5SDimitry Andric         Record.push_back((p[1] << 48) | (p[0] >> 16));
27280b57cec5SDimitry Andric         Record.push_back(p[0] & 0xffffLL);
27290b57cec5SDimitry Andric       } else if (Ty->isFP128Ty() || Ty->isPPC_FP128Ty()) {
27300b57cec5SDimitry Andric         APInt api = CFP->getValueAPF().bitcastToAPInt();
27310b57cec5SDimitry Andric         const uint64_t *p = api.getRawData();
27320b57cec5SDimitry Andric         Record.push_back(p[0]);
27330b57cec5SDimitry Andric         Record.push_back(p[1]);
27340b57cec5SDimitry Andric       } else {
27350b57cec5SDimitry Andric         assert(0 && "Unknown FP type!");
27360b57cec5SDimitry Andric       }
27370b57cec5SDimitry Andric     } else if (isa<ConstantDataSequential>(C) &&
27380b57cec5SDimitry Andric                cast<ConstantDataSequential>(C)->isString()) {
27390b57cec5SDimitry Andric       const ConstantDataSequential *Str = cast<ConstantDataSequential>(C);
27400b57cec5SDimitry Andric       // Emit constant strings specially.
27410b57cec5SDimitry Andric       unsigned NumElts = Str->getNumElements();
27420b57cec5SDimitry Andric       // If this is a null-terminated string, use the denser CSTRING encoding.
27430b57cec5SDimitry Andric       if (Str->isCString()) {
27440b57cec5SDimitry Andric         Code = bitc::CST_CODE_CSTRING;
27450b57cec5SDimitry Andric         --NumElts;  // Don't encode the null, which isn't allowed by char6.
27460b57cec5SDimitry Andric       } else {
27470b57cec5SDimitry Andric         Code = bitc::CST_CODE_STRING;
27480b57cec5SDimitry Andric         AbbrevToUse = String8Abbrev;
27490b57cec5SDimitry Andric       }
27500b57cec5SDimitry Andric       bool isCStr7 = Code == bitc::CST_CODE_CSTRING;
27510b57cec5SDimitry Andric       bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING;
27520b57cec5SDimitry Andric       for (unsigned i = 0; i != NumElts; ++i) {
27530b57cec5SDimitry Andric         unsigned char V = Str->getElementAsInteger(i);
27540b57cec5SDimitry Andric         Record.push_back(V);
27550b57cec5SDimitry Andric         isCStr7 &= (V & 128) == 0;
27560b57cec5SDimitry Andric         if (isCStrChar6)
27570b57cec5SDimitry Andric           isCStrChar6 = BitCodeAbbrevOp::isChar6(V);
27580b57cec5SDimitry Andric       }
27590b57cec5SDimitry Andric 
27600b57cec5SDimitry Andric       if (isCStrChar6)
27610b57cec5SDimitry Andric         AbbrevToUse = CString6Abbrev;
27620b57cec5SDimitry Andric       else if (isCStr7)
27630b57cec5SDimitry Andric         AbbrevToUse = CString7Abbrev;
27640b57cec5SDimitry Andric     } else if (const ConstantDataSequential *CDS =
27650b57cec5SDimitry Andric                   dyn_cast<ConstantDataSequential>(C)) {
27660b57cec5SDimitry Andric       Code = bitc::CST_CODE_DATA;
27675ffd83dbSDimitry Andric       Type *EltTy = CDS->getElementType();
27680b57cec5SDimitry Andric       if (isa<IntegerType>(EltTy)) {
27690b57cec5SDimitry Andric         for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
27700b57cec5SDimitry Andric           Record.push_back(CDS->getElementAsInteger(i));
27710b57cec5SDimitry Andric       } else {
27720b57cec5SDimitry Andric         for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
27730b57cec5SDimitry Andric           Record.push_back(
27740b57cec5SDimitry Andric               CDS->getElementAsAPFloat(i).bitcastToAPInt().getLimitedValue());
27750b57cec5SDimitry Andric       }
27760b57cec5SDimitry Andric     } else if (isa<ConstantAggregate>(C)) {
27770b57cec5SDimitry Andric       Code = bitc::CST_CODE_AGGREGATE;
27780b57cec5SDimitry Andric       for (const Value *Op : C->operands())
27790b57cec5SDimitry Andric         Record.push_back(VE.getValueID(Op));
27800b57cec5SDimitry Andric       AbbrevToUse = AggregateAbbrev;
27810b57cec5SDimitry Andric     } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
27820b57cec5SDimitry Andric       switch (CE->getOpcode()) {
27830b57cec5SDimitry Andric       default:
27840b57cec5SDimitry Andric         if (Instruction::isCast(CE->getOpcode())) {
27850b57cec5SDimitry Andric           Code = bitc::CST_CODE_CE_CAST;
27860b57cec5SDimitry Andric           Record.push_back(getEncodedCastOpcode(CE->getOpcode()));
27870b57cec5SDimitry Andric           Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
27880b57cec5SDimitry Andric           Record.push_back(VE.getValueID(C->getOperand(0)));
27890b57cec5SDimitry Andric           AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;
27900b57cec5SDimitry Andric         } else {
27910b57cec5SDimitry Andric           assert(CE->getNumOperands() == 2 && "Unknown constant expr!");
27920b57cec5SDimitry Andric           Code = bitc::CST_CODE_CE_BINOP;
27930b57cec5SDimitry Andric           Record.push_back(getEncodedBinaryOpcode(CE->getOpcode()));
27940b57cec5SDimitry Andric           Record.push_back(VE.getValueID(C->getOperand(0)));
27950b57cec5SDimitry Andric           Record.push_back(VE.getValueID(C->getOperand(1)));
27960b57cec5SDimitry Andric           uint64_t Flags = getOptimizationFlags(CE);
27970b57cec5SDimitry Andric           if (Flags != 0)
27980b57cec5SDimitry Andric             Record.push_back(Flags);
27990b57cec5SDimitry Andric         }
28000b57cec5SDimitry Andric         break;
28010b57cec5SDimitry Andric       case Instruction::FNeg: {
28020b57cec5SDimitry Andric         assert(CE->getNumOperands() == 1 && "Unknown constant expr!");
28030b57cec5SDimitry Andric         Code = bitc::CST_CODE_CE_UNOP;
28040b57cec5SDimitry Andric         Record.push_back(getEncodedUnaryOpcode(CE->getOpcode()));
28050b57cec5SDimitry Andric         Record.push_back(VE.getValueID(C->getOperand(0)));
28060b57cec5SDimitry Andric         uint64_t Flags = getOptimizationFlags(CE);
28070b57cec5SDimitry Andric         if (Flags != 0)
28080b57cec5SDimitry Andric           Record.push_back(Flags);
28090b57cec5SDimitry Andric         break;
28100b57cec5SDimitry Andric       }
28110b57cec5SDimitry Andric       case Instruction::GetElementPtr: {
28120b57cec5SDimitry Andric         Code = bitc::CST_CODE_CE_GEP;
28130b57cec5SDimitry Andric         const auto *GO = cast<GEPOperator>(C);
28140b57cec5SDimitry Andric         Record.push_back(VE.getTypeID(GO->getSourceElementType()));
2815*0fca6ea1SDimitry Andric         Record.push_back(getOptimizationFlags(GO));
2816*0fca6ea1SDimitry Andric         if (std::optional<ConstantRange> Range = GO->getInRange()) {
2817*0fca6ea1SDimitry Andric           Code = bitc::CST_CODE_CE_GEP_WITH_INRANGE;
2818*0fca6ea1SDimitry Andric           emitConstantRange(Record, *Range, /*EmitBitWidth=*/true);
2819*0fca6ea1SDimitry Andric         }
28200b57cec5SDimitry Andric         for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
28210b57cec5SDimitry Andric           Record.push_back(VE.getTypeID(C->getOperand(i)->getType()));
28220b57cec5SDimitry Andric           Record.push_back(VE.getValueID(C->getOperand(i)));
28230b57cec5SDimitry Andric         }
28240b57cec5SDimitry Andric         break;
28250b57cec5SDimitry Andric       }
28260b57cec5SDimitry Andric       case Instruction::ExtractElement:
28270b57cec5SDimitry Andric         Code = bitc::CST_CODE_CE_EXTRACTELT;
28280b57cec5SDimitry Andric         Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
28290b57cec5SDimitry Andric         Record.push_back(VE.getValueID(C->getOperand(0)));
28300b57cec5SDimitry Andric         Record.push_back(VE.getTypeID(C->getOperand(1)->getType()));
28310b57cec5SDimitry Andric         Record.push_back(VE.getValueID(C->getOperand(1)));
28320b57cec5SDimitry Andric         break;
28330b57cec5SDimitry Andric       case Instruction::InsertElement:
28340b57cec5SDimitry Andric         Code = bitc::CST_CODE_CE_INSERTELT;
28350b57cec5SDimitry Andric         Record.push_back(VE.getValueID(C->getOperand(0)));
28360b57cec5SDimitry Andric         Record.push_back(VE.getValueID(C->getOperand(1)));
28370b57cec5SDimitry Andric         Record.push_back(VE.getTypeID(C->getOperand(2)->getType()));
28380b57cec5SDimitry Andric         Record.push_back(VE.getValueID(C->getOperand(2)));
28390b57cec5SDimitry Andric         break;
28400b57cec5SDimitry Andric       case Instruction::ShuffleVector:
28410b57cec5SDimitry Andric         // If the return type and argument types are the same, this is a
28420b57cec5SDimitry Andric         // standard shufflevector instruction.  If the types are different,
28430b57cec5SDimitry Andric         // then the shuffle is widening or truncating the input vectors, and
28440b57cec5SDimitry Andric         // the argument type must also be encoded.
28450b57cec5SDimitry Andric         if (C->getType() == C->getOperand(0)->getType()) {
28460b57cec5SDimitry Andric           Code = bitc::CST_CODE_CE_SHUFFLEVEC;
28470b57cec5SDimitry Andric         } else {
28480b57cec5SDimitry Andric           Code = bitc::CST_CODE_CE_SHUFVEC_EX;
28490b57cec5SDimitry Andric           Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
28500b57cec5SDimitry Andric         }
28510b57cec5SDimitry Andric         Record.push_back(VE.getValueID(C->getOperand(0)));
28520b57cec5SDimitry Andric         Record.push_back(VE.getValueID(C->getOperand(1)));
28535ffd83dbSDimitry Andric         Record.push_back(VE.getValueID(CE->getShuffleMaskForBitcode()));
28540b57cec5SDimitry Andric         break;
28550b57cec5SDimitry Andric       }
28560b57cec5SDimitry Andric     } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) {
28570b57cec5SDimitry Andric       Code = bitc::CST_CODE_BLOCKADDRESS;
28580b57cec5SDimitry Andric       Record.push_back(VE.getTypeID(BA->getFunction()->getType()));
28590b57cec5SDimitry Andric       Record.push_back(VE.getValueID(BA->getFunction()));
28600b57cec5SDimitry Andric       Record.push_back(VE.getGlobalBasicBlockID(BA->getBasicBlock()));
2861fe6060f1SDimitry Andric     } else if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C)) {
2862fe6060f1SDimitry Andric       Code = bitc::CST_CODE_DSO_LOCAL_EQUIVALENT;
2863fe6060f1SDimitry Andric       Record.push_back(VE.getTypeID(Equiv->getGlobalValue()->getType()));
2864fe6060f1SDimitry Andric       Record.push_back(VE.getValueID(Equiv->getGlobalValue()));
28650eae32dcSDimitry Andric     } else if (const auto *NC = dyn_cast<NoCFIValue>(C)) {
28660eae32dcSDimitry Andric       Code = bitc::CST_CODE_NO_CFI_VALUE;
28670eae32dcSDimitry Andric       Record.push_back(VE.getTypeID(NC->getGlobalValue()->getType()));
28680eae32dcSDimitry Andric       Record.push_back(VE.getValueID(NC->getGlobalValue()));
2869*0fca6ea1SDimitry Andric     } else if (const auto *CPA = dyn_cast<ConstantPtrAuth>(C)) {
2870*0fca6ea1SDimitry Andric       Code = bitc::CST_CODE_PTRAUTH;
2871*0fca6ea1SDimitry Andric       Record.push_back(VE.getValueID(CPA->getPointer()));
2872*0fca6ea1SDimitry Andric       Record.push_back(VE.getValueID(CPA->getKey()));
2873*0fca6ea1SDimitry Andric       Record.push_back(VE.getValueID(CPA->getDiscriminator()));
2874*0fca6ea1SDimitry Andric       Record.push_back(VE.getValueID(CPA->getAddrDiscriminator()));
28750b57cec5SDimitry Andric     } else {
28760b57cec5SDimitry Andric #ifndef NDEBUG
28770b57cec5SDimitry Andric       C->dump();
28780b57cec5SDimitry Andric #endif
28790b57cec5SDimitry Andric       llvm_unreachable("Unknown constant!");
28800b57cec5SDimitry Andric     }
28810b57cec5SDimitry Andric     Stream.EmitRecord(Code, Record, AbbrevToUse);
28820b57cec5SDimitry Andric     Record.clear();
28830b57cec5SDimitry Andric   }
28840b57cec5SDimitry Andric 
28850b57cec5SDimitry Andric   Stream.ExitBlock();
28860b57cec5SDimitry Andric }
28870b57cec5SDimitry Andric 
28880b57cec5SDimitry Andric void ModuleBitcodeWriter::writeModuleConstants() {
28890b57cec5SDimitry Andric   const ValueEnumerator::ValueList &Vals = VE.getValues();
28900b57cec5SDimitry Andric 
28910b57cec5SDimitry Andric   // Find the first constant to emit, which is the first non-globalvalue value.
28920b57cec5SDimitry Andric   // We know globalvalues have been emitted by WriteModuleInfo.
28930b57cec5SDimitry Andric   for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
28940b57cec5SDimitry Andric     if (!isa<GlobalValue>(Vals[i].first)) {
28950b57cec5SDimitry Andric       writeConstants(i, Vals.size(), true);
28960b57cec5SDimitry Andric       return;
28970b57cec5SDimitry Andric     }
28980b57cec5SDimitry Andric   }
28990b57cec5SDimitry Andric }
29000b57cec5SDimitry Andric 
29010b57cec5SDimitry Andric /// pushValueAndType - The file has to encode both the value and type id for
29020b57cec5SDimitry Andric /// many values, because we need to know what type to create for forward
29030b57cec5SDimitry Andric /// references.  However, most operands are not forward references, so this type
29040b57cec5SDimitry Andric /// field is not needed.
29050b57cec5SDimitry Andric ///
29060b57cec5SDimitry Andric /// This function adds V's value ID to Vals.  If the value ID is higher than the
29070b57cec5SDimitry Andric /// instruction ID, then it is a forward reference, and it also includes the
29080b57cec5SDimitry Andric /// type ID.  The value ID that is written is encoded relative to the InstID.
29090b57cec5SDimitry Andric bool ModuleBitcodeWriter::pushValueAndType(const Value *V, unsigned InstID,
29100b57cec5SDimitry Andric                                            SmallVectorImpl<unsigned> &Vals) {
29110b57cec5SDimitry Andric   unsigned ValID = VE.getValueID(V);
29120b57cec5SDimitry Andric   // Make encoding relative to the InstID.
29130b57cec5SDimitry Andric   Vals.push_back(InstID - ValID);
29140b57cec5SDimitry Andric   if (ValID >= InstID) {
29150b57cec5SDimitry Andric     Vals.push_back(VE.getTypeID(V->getType()));
29160b57cec5SDimitry Andric     return true;
29170b57cec5SDimitry Andric   }
29180b57cec5SDimitry Andric   return false;
29190b57cec5SDimitry Andric }
29200b57cec5SDimitry Andric 
29215ffd83dbSDimitry Andric void ModuleBitcodeWriter::writeOperandBundles(const CallBase &CS,
29220b57cec5SDimitry Andric                                               unsigned InstID) {
29230b57cec5SDimitry Andric   SmallVector<unsigned, 64> Record;
29245ffd83dbSDimitry Andric   LLVMContext &C = CS.getContext();
29250b57cec5SDimitry Andric 
29260b57cec5SDimitry Andric   for (unsigned i = 0, e = CS.getNumOperandBundles(); i != e; ++i) {
29270b57cec5SDimitry Andric     const auto &Bundle = CS.getOperandBundleAt(i);
29280b57cec5SDimitry Andric     Record.push_back(C.getOperandBundleTagID(Bundle.getTagName()));
29290b57cec5SDimitry Andric 
29300b57cec5SDimitry Andric     for (auto &Input : Bundle.Inputs)
29310b57cec5SDimitry Andric       pushValueAndType(Input, InstID, Record);
29320b57cec5SDimitry Andric 
29330b57cec5SDimitry Andric     Stream.EmitRecord(bitc::FUNC_CODE_OPERAND_BUNDLE, Record);
29340b57cec5SDimitry Andric     Record.clear();
29350b57cec5SDimitry Andric   }
29360b57cec5SDimitry Andric }
29370b57cec5SDimitry Andric 
29380b57cec5SDimitry Andric /// pushValue - Like pushValueAndType, but where the type of the value is
29390b57cec5SDimitry Andric /// omitted (perhaps it was already encoded in an earlier operand).
29400b57cec5SDimitry Andric void ModuleBitcodeWriter::pushValue(const Value *V, unsigned InstID,
29410b57cec5SDimitry Andric                                     SmallVectorImpl<unsigned> &Vals) {
29420b57cec5SDimitry Andric   unsigned ValID = VE.getValueID(V);
29430b57cec5SDimitry Andric   Vals.push_back(InstID - ValID);
29440b57cec5SDimitry Andric }
29450b57cec5SDimitry Andric 
29460b57cec5SDimitry Andric void ModuleBitcodeWriter::pushValueSigned(const Value *V, unsigned InstID,
29470b57cec5SDimitry Andric                                           SmallVectorImpl<uint64_t> &Vals) {
29480b57cec5SDimitry Andric   unsigned ValID = VE.getValueID(V);
29490b57cec5SDimitry Andric   int64_t diff = ((int32_t)InstID - (int32_t)ValID);
29500b57cec5SDimitry Andric   emitSignedInt64(Vals, diff);
29510b57cec5SDimitry Andric }
29520b57cec5SDimitry Andric 
29530b57cec5SDimitry Andric /// WriteInstruction - Emit an instruction to the specified stream.
29540b57cec5SDimitry Andric void ModuleBitcodeWriter::writeInstruction(const Instruction &I,
29550b57cec5SDimitry Andric                                            unsigned InstID,
29560b57cec5SDimitry Andric                                            SmallVectorImpl<unsigned> &Vals) {
29570b57cec5SDimitry Andric   unsigned Code = 0;
29580b57cec5SDimitry Andric   unsigned AbbrevToUse = 0;
29590b57cec5SDimitry Andric   VE.setInstructionID(&I);
29600b57cec5SDimitry Andric   switch (I.getOpcode()) {
29610b57cec5SDimitry Andric   default:
29620b57cec5SDimitry Andric     if (Instruction::isCast(I.getOpcode())) {
29630b57cec5SDimitry Andric       Code = bitc::FUNC_CODE_INST_CAST;
29640b57cec5SDimitry Andric       if (!pushValueAndType(I.getOperand(0), InstID, Vals))
29650b57cec5SDimitry Andric         AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
29660b57cec5SDimitry Andric       Vals.push_back(VE.getTypeID(I.getType()));
29670b57cec5SDimitry Andric       Vals.push_back(getEncodedCastOpcode(I.getOpcode()));
29685f757f3fSDimitry Andric       uint64_t Flags = getOptimizationFlags(&I);
29695f757f3fSDimitry Andric       if (Flags != 0) {
29705f757f3fSDimitry Andric         if (AbbrevToUse == FUNCTION_INST_CAST_ABBREV)
29715f757f3fSDimitry Andric           AbbrevToUse = FUNCTION_INST_CAST_FLAGS_ABBREV;
29725f757f3fSDimitry Andric         Vals.push_back(Flags);
29735f757f3fSDimitry Andric       }
29740b57cec5SDimitry Andric     } else {
29750b57cec5SDimitry Andric       assert(isa<BinaryOperator>(I) && "Unknown instruction!");
29760b57cec5SDimitry Andric       Code = bitc::FUNC_CODE_INST_BINOP;
29770b57cec5SDimitry Andric       if (!pushValueAndType(I.getOperand(0), InstID, Vals))
29780b57cec5SDimitry Andric         AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
29790b57cec5SDimitry Andric       pushValue(I.getOperand(1), InstID, Vals);
29800b57cec5SDimitry Andric       Vals.push_back(getEncodedBinaryOpcode(I.getOpcode()));
29810b57cec5SDimitry Andric       uint64_t Flags = getOptimizationFlags(&I);
29820b57cec5SDimitry Andric       if (Flags != 0) {
29830b57cec5SDimitry Andric         if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV)
29840b57cec5SDimitry Andric           AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV;
29850b57cec5SDimitry Andric         Vals.push_back(Flags);
29860b57cec5SDimitry Andric       }
29870b57cec5SDimitry Andric     }
29880b57cec5SDimitry Andric     break;
29890b57cec5SDimitry Andric   case Instruction::FNeg: {
29900b57cec5SDimitry Andric     Code = bitc::FUNC_CODE_INST_UNOP;
29910b57cec5SDimitry Andric     if (!pushValueAndType(I.getOperand(0), InstID, Vals))
29920b57cec5SDimitry Andric       AbbrevToUse = FUNCTION_INST_UNOP_ABBREV;
29930b57cec5SDimitry Andric     Vals.push_back(getEncodedUnaryOpcode(I.getOpcode()));
29940b57cec5SDimitry Andric     uint64_t Flags = getOptimizationFlags(&I);
29950b57cec5SDimitry Andric     if (Flags != 0) {
29960b57cec5SDimitry Andric       if (AbbrevToUse == FUNCTION_INST_UNOP_ABBREV)
29970b57cec5SDimitry Andric         AbbrevToUse = FUNCTION_INST_UNOP_FLAGS_ABBREV;
29980b57cec5SDimitry Andric       Vals.push_back(Flags);
29990b57cec5SDimitry Andric     }
30000b57cec5SDimitry Andric     break;
30010b57cec5SDimitry Andric   }
30020b57cec5SDimitry Andric   case Instruction::GetElementPtr: {
30030b57cec5SDimitry Andric     Code = bitc::FUNC_CODE_INST_GEP;
30040b57cec5SDimitry Andric     AbbrevToUse = FUNCTION_INST_GEP_ABBREV;
30050b57cec5SDimitry Andric     auto &GEPInst = cast<GetElementPtrInst>(I);
3006*0fca6ea1SDimitry Andric     Vals.push_back(getOptimizationFlags(&I));
30070b57cec5SDimitry Andric     Vals.push_back(VE.getTypeID(GEPInst.getSourceElementType()));
30080b57cec5SDimitry Andric     for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
30090b57cec5SDimitry Andric       pushValueAndType(I.getOperand(i), InstID, Vals);
30100b57cec5SDimitry Andric     break;
30110b57cec5SDimitry Andric   }
30120b57cec5SDimitry Andric   case Instruction::ExtractValue: {
30130b57cec5SDimitry Andric     Code = bitc::FUNC_CODE_INST_EXTRACTVAL;
30140b57cec5SDimitry Andric     pushValueAndType(I.getOperand(0), InstID, Vals);
30150b57cec5SDimitry Andric     const ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
30160b57cec5SDimitry Andric     Vals.append(EVI->idx_begin(), EVI->idx_end());
30170b57cec5SDimitry Andric     break;
30180b57cec5SDimitry Andric   }
30190b57cec5SDimitry Andric   case Instruction::InsertValue: {
30200b57cec5SDimitry Andric     Code = bitc::FUNC_CODE_INST_INSERTVAL;
30210b57cec5SDimitry Andric     pushValueAndType(I.getOperand(0), InstID, Vals);
30220b57cec5SDimitry Andric     pushValueAndType(I.getOperand(1), InstID, Vals);
30230b57cec5SDimitry Andric     const InsertValueInst *IVI = cast<InsertValueInst>(&I);
30240b57cec5SDimitry Andric     Vals.append(IVI->idx_begin(), IVI->idx_end());
30250b57cec5SDimitry Andric     break;
30260b57cec5SDimitry Andric   }
30270b57cec5SDimitry Andric   case Instruction::Select: {
30280b57cec5SDimitry Andric     Code = bitc::FUNC_CODE_INST_VSELECT;
30290b57cec5SDimitry Andric     pushValueAndType(I.getOperand(1), InstID, Vals);
30300b57cec5SDimitry Andric     pushValue(I.getOperand(2), InstID, Vals);
30310b57cec5SDimitry Andric     pushValueAndType(I.getOperand(0), InstID, Vals);
30320b57cec5SDimitry Andric     uint64_t Flags = getOptimizationFlags(&I);
30330b57cec5SDimitry Andric     if (Flags != 0)
30340b57cec5SDimitry Andric       Vals.push_back(Flags);
30350b57cec5SDimitry Andric     break;
30360b57cec5SDimitry Andric   }
30370b57cec5SDimitry Andric   case Instruction::ExtractElement:
30380b57cec5SDimitry Andric     Code = bitc::FUNC_CODE_INST_EXTRACTELT;
30390b57cec5SDimitry Andric     pushValueAndType(I.getOperand(0), InstID, Vals);
30400b57cec5SDimitry Andric     pushValueAndType(I.getOperand(1), InstID, Vals);
30410b57cec5SDimitry Andric     break;
30420b57cec5SDimitry Andric   case Instruction::InsertElement:
30430b57cec5SDimitry Andric     Code = bitc::FUNC_CODE_INST_INSERTELT;
30440b57cec5SDimitry Andric     pushValueAndType(I.getOperand(0), InstID, Vals);
30450b57cec5SDimitry Andric     pushValue(I.getOperand(1), InstID, Vals);
30460b57cec5SDimitry Andric     pushValueAndType(I.getOperand(2), InstID, Vals);
30470b57cec5SDimitry Andric     break;
30480b57cec5SDimitry Andric   case Instruction::ShuffleVector:
30490b57cec5SDimitry Andric     Code = bitc::FUNC_CODE_INST_SHUFFLEVEC;
30500b57cec5SDimitry Andric     pushValueAndType(I.getOperand(0), InstID, Vals);
30510b57cec5SDimitry Andric     pushValue(I.getOperand(1), InstID, Vals);
30525ffd83dbSDimitry Andric     pushValue(cast<ShuffleVectorInst>(I).getShuffleMaskForBitcode(), InstID,
30535ffd83dbSDimitry Andric               Vals);
30540b57cec5SDimitry Andric     break;
30550b57cec5SDimitry Andric   case Instruction::ICmp:
30560b57cec5SDimitry Andric   case Instruction::FCmp: {
30570b57cec5SDimitry Andric     // compare returning Int1Ty or vector of Int1Ty
30580b57cec5SDimitry Andric     Code = bitc::FUNC_CODE_INST_CMP2;
30590b57cec5SDimitry Andric     pushValueAndType(I.getOperand(0), InstID, Vals);
30600b57cec5SDimitry Andric     pushValue(I.getOperand(1), InstID, Vals);
30610b57cec5SDimitry Andric     Vals.push_back(cast<CmpInst>(I).getPredicate());
30620b57cec5SDimitry Andric     uint64_t Flags = getOptimizationFlags(&I);
30630b57cec5SDimitry Andric     if (Flags != 0)
30640b57cec5SDimitry Andric       Vals.push_back(Flags);
30650b57cec5SDimitry Andric     break;
30660b57cec5SDimitry Andric   }
30670b57cec5SDimitry Andric 
30680b57cec5SDimitry Andric   case Instruction::Ret:
30690b57cec5SDimitry Andric     {
30700b57cec5SDimitry Andric       Code = bitc::FUNC_CODE_INST_RET;
30710b57cec5SDimitry Andric       unsigned NumOperands = I.getNumOperands();
30720b57cec5SDimitry Andric       if (NumOperands == 0)
30730b57cec5SDimitry Andric         AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
30740b57cec5SDimitry Andric       else if (NumOperands == 1) {
30750b57cec5SDimitry Andric         if (!pushValueAndType(I.getOperand(0), InstID, Vals))
30760b57cec5SDimitry Andric           AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
30770b57cec5SDimitry Andric       } else {
30780b57cec5SDimitry Andric         for (unsigned i = 0, e = NumOperands; i != e; ++i)
30790b57cec5SDimitry Andric           pushValueAndType(I.getOperand(i), InstID, Vals);
30800b57cec5SDimitry Andric       }
30810b57cec5SDimitry Andric     }
30820b57cec5SDimitry Andric     break;
30830b57cec5SDimitry Andric   case Instruction::Br:
30840b57cec5SDimitry Andric     {
30850b57cec5SDimitry Andric       Code = bitc::FUNC_CODE_INST_BR;
30860b57cec5SDimitry Andric       const BranchInst &II = cast<BranchInst>(I);
30870b57cec5SDimitry Andric       Vals.push_back(VE.getValueID(II.getSuccessor(0)));
30880b57cec5SDimitry Andric       if (II.isConditional()) {
30890b57cec5SDimitry Andric         Vals.push_back(VE.getValueID(II.getSuccessor(1)));
30900b57cec5SDimitry Andric         pushValue(II.getCondition(), InstID, Vals);
30910b57cec5SDimitry Andric       }
30920b57cec5SDimitry Andric     }
30930b57cec5SDimitry Andric     break;
30940b57cec5SDimitry Andric   case Instruction::Switch:
30950b57cec5SDimitry Andric     {
30960b57cec5SDimitry Andric       Code = bitc::FUNC_CODE_INST_SWITCH;
30970b57cec5SDimitry Andric       const SwitchInst &SI = cast<SwitchInst>(I);
30980b57cec5SDimitry Andric       Vals.push_back(VE.getTypeID(SI.getCondition()->getType()));
30990b57cec5SDimitry Andric       pushValue(SI.getCondition(), InstID, Vals);
31000b57cec5SDimitry Andric       Vals.push_back(VE.getValueID(SI.getDefaultDest()));
31010b57cec5SDimitry Andric       for (auto Case : SI.cases()) {
31020b57cec5SDimitry Andric         Vals.push_back(VE.getValueID(Case.getCaseValue()));
31030b57cec5SDimitry Andric         Vals.push_back(VE.getValueID(Case.getCaseSuccessor()));
31040b57cec5SDimitry Andric       }
31050b57cec5SDimitry Andric     }
31060b57cec5SDimitry Andric     break;
31070b57cec5SDimitry Andric   case Instruction::IndirectBr:
31080b57cec5SDimitry Andric     Code = bitc::FUNC_CODE_INST_INDIRECTBR;
31090b57cec5SDimitry Andric     Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
31100b57cec5SDimitry Andric     // Encode the address operand as relative, but not the basic blocks.
31110b57cec5SDimitry Andric     pushValue(I.getOperand(0), InstID, Vals);
31120b57cec5SDimitry Andric     for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i)
31130b57cec5SDimitry Andric       Vals.push_back(VE.getValueID(I.getOperand(i)));
31140b57cec5SDimitry Andric     break;
31150b57cec5SDimitry Andric 
31160b57cec5SDimitry Andric   case Instruction::Invoke: {
31170b57cec5SDimitry Andric     const InvokeInst *II = cast<InvokeInst>(&I);
31185ffd83dbSDimitry Andric     const Value *Callee = II->getCalledOperand();
31190b57cec5SDimitry Andric     FunctionType *FTy = II->getFunctionType();
31200b57cec5SDimitry Andric 
31210b57cec5SDimitry Andric     if (II->hasOperandBundles())
31225ffd83dbSDimitry Andric       writeOperandBundles(*II, InstID);
31230b57cec5SDimitry Andric 
31240b57cec5SDimitry Andric     Code = bitc::FUNC_CODE_INST_INVOKE;
31250b57cec5SDimitry Andric 
31260b57cec5SDimitry Andric     Vals.push_back(VE.getAttributeListID(II->getAttributes()));
31270b57cec5SDimitry Andric     Vals.push_back(II->getCallingConv() | 1 << 13);
31280b57cec5SDimitry Andric     Vals.push_back(VE.getValueID(II->getNormalDest()));
31290b57cec5SDimitry Andric     Vals.push_back(VE.getValueID(II->getUnwindDest()));
31300b57cec5SDimitry Andric     Vals.push_back(VE.getTypeID(FTy));
31310b57cec5SDimitry Andric     pushValueAndType(Callee, InstID, Vals);
31320b57cec5SDimitry Andric 
31330b57cec5SDimitry Andric     // Emit value #'s for the fixed parameters.
31340b57cec5SDimitry Andric     for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
31350b57cec5SDimitry Andric       pushValue(I.getOperand(i), InstID, Vals); // fixed param.
31360b57cec5SDimitry Andric 
31370b57cec5SDimitry Andric     // Emit type/value pairs for varargs params.
31380b57cec5SDimitry Andric     if (FTy->isVarArg()) {
3139349cc55cSDimitry Andric       for (unsigned i = FTy->getNumParams(), e = II->arg_size(); i != e; ++i)
31400b57cec5SDimitry Andric         pushValueAndType(I.getOperand(i), InstID, Vals); // vararg
31410b57cec5SDimitry Andric     }
31420b57cec5SDimitry Andric     break;
31430b57cec5SDimitry Andric   }
31440b57cec5SDimitry Andric   case Instruction::Resume:
31450b57cec5SDimitry Andric     Code = bitc::FUNC_CODE_INST_RESUME;
31460b57cec5SDimitry Andric     pushValueAndType(I.getOperand(0), InstID, Vals);
31470b57cec5SDimitry Andric     break;
31480b57cec5SDimitry Andric   case Instruction::CleanupRet: {
31490b57cec5SDimitry Andric     Code = bitc::FUNC_CODE_INST_CLEANUPRET;
31500b57cec5SDimitry Andric     const auto &CRI = cast<CleanupReturnInst>(I);
31510b57cec5SDimitry Andric     pushValue(CRI.getCleanupPad(), InstID, Vals);
31520b57cec5SDimitry Andric     if (CRI.hasUnwindDest())
31530b57cec5SDimitry Andric       Vals.push_back(VE.getValueID(CRI.getUnwindDest()));
31540b57cec5SDimitry Andric     break;
31550b57cec5SDimitry Andric   }
31560b57cec5SDimitry Andric   case Instruction::CatchRet: {
31570b57cec5SDimitry Andric     Code = bitc::FUNC_CODE_INST_CATCHRET;
31580b57cec5SDimitry Andric     const auto &CRI = cast<CatchReturnInst>(I);
31590b57cec5SDimitry Andric     pushValue(CRI.getCatchPad(), InstID, Vals);
31600b57cec5SDimitry Andric     Vals.push_back(VE.getValueID(CRI.getSuccessor()));
31610b57cec5SDimitry Andric     break;
31620b57cec5SDimitry Andric   }
31630b57cec5SDimitry Andric   case Instruction::CleanupPad:
31640b57cec5SDimitry Andric   case Instruction::CatchPad: {
31650b57cec5SDimitry Andric     const auto &FuncletPad = cast<FuncletPadInst>(I);
31660b57cec5SDimitry Andric     Code = isa<CatchPadInst>(FuncletPad) ? bitc::FUNC_CODE_INST_CATCHPAD
31670b57cec5SDimitry Andric                                          : bitc::FUNC_CODE_INST_CLEANUPPAD;
31680b57cec5SDimitry Andric     pushValue(FuncletPad.getParentPad(), InstID, Vals);
31690b57cec5SDimitry Andric 
3170bdd1243dSDimitry Andric     unsigned NumArgOperands = FuncletPad.arg_size();
31710b57cec5SDimitry Andric     Vals.push_back(NumArgOperands);
31720b57cec5SDimitry Andric     for (unsigned Op = 0; Op != NumArgOperands; ++Op)
31730b57cec5SDimitry Andric       pushValueAndType(FuncletPad.getArgOperand(Op), InstID, Vals);
31740b57cec5SDimitry Andric     break;
31750b57cec5SDimitry Andric   }
31760b57cec5SDimitry Andric   case Instruction::CatchSwitch: {
31770b57cec5SDimitry Andric     Code = bitc::FUNC_CODE_INST_CATCHSWITCH;
31780b57cec5SDimitry Andric     const auto &CatchSwitch = cast<CatchSwitchInst>(I);
31790b57cec5SDimitry Andric 
31800b57cec5SDimitry Andric     pushValue(CatchSwitch.getParentPad(), InstID, Vals);
31810b57cec5SDimitry Andric 
31820b57cec5SDimitry Andric     unsigned NumHandlers = CatchSwitch.getNumHandlers();
31830b57cec5SDimitry Andric     Vals.push_back(NumHandlers);
31840b57cec5SDimitry Andric     for (const BasicBlock *CatchPadBB : CatchSwitch.handlers())
31850b57cec5SDimitry Andric       Vals.push_back(VE.getValueID(CatchPadBB));
31860b57cec5SDimitry Andric 
31870b57cec5SDimitry Andric     if (CatchSwitch.hasUnwindDest())
31880b57cec5SDimitry Andric       Vals.push_back(VE.getValueID(CatchSwitch.getUnwindDest()));
31890b57cec5SDimitry Andric     break;
31900b57cec5SDimitry Andric   }
31910b57cec5SDimitry Andric   case Instruction::CallBr: {
31920b57cec5SDimitry Andric     const CallBrInst *CBI = cast<CallBrInst>(&I);
31935ffd83dbSDimitry Andric     const Value *Callee = CBI->getCalledOperand();
31940b57cec5SDimitry Andric     FunctionType *FTy = CBI->getFunctionType();
31950b57cec5SDimitry Andric 
31960b57cec5SDimitry Andric     if (CBI->hasOperandBundles())
31975ffd83dbSDimitry Andric       writeOperandBundles(*CBI, InstID);
31980b57cec5SDimitry Andric 
31990b57cec5SDimitry Andric     Code = bitc::FUNC_CODE_INST_CALLBR;
32000b57cec5SDimitry Andric 
32010b57cec5SDimitry Andric     Vals.push_back(VE.getAttributeListID(CBI->getAttributes()));
32020b57cec5SDimitry Andric 
32030b57cec5SDimitry Andric     Vals.push_back(CBI->getCallingConv() << bitc::CALL_CCONV |
32040b57cec5SDimitry Andric                    1 << bitc::CALL_EXPLICIT_TYPE);
32050b57cec5SDimitry Andric 
32060b57cec5SDimitry Andric     Vals.push_back(VE.getValueID(CBI->getDefaultDest()));
32070b57cec5SDimitry Andric     Vals.push_back(CBI->getNumIndirectDests());
32080b57cec5SDimitry Andric     for (unsigned i = 0, e = CBI->getNumIndirectDests(); i != e; ++i)
32090b57cec5SDimitry Andric       Vals.push_back(VE.getValueID(CBI->getIndirectDest(i)));
32100b57cec5SDimitry Andric 
32110b57cec5SDimitry Andric     Vals.push_back(VE.getTypeID(FTy));
32120b57cec5SDimitry Andric     pushValueAndType(Callee, InstID, Vals);
32130b57cec5SDimitry Andric 
32140b57cec5SDimitry Andric     // Emit value #'s for the fixed parameters.
32150b57cec5SDimitry Andric     for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
32160b57cec5SDimitry Andric       pushValue(I.getOperand(i), InstID, Vals); // fixed param.
32170b57cec5SDimitry Andric 
32180b57cec5SDimitry Andric     // Emit type/value pairs for varargs params.
32190b57cec5SDimitry Andric     if (FTy->isVarArg()) {
3220349cc55cSDimitry Andric       for (unsigned i = FTy->getNumParams(), e = CBI->arg_size(); i != e; ++i)
32210b57cec5SDimitry Andric         pushValueAndType(I.getOperand(i), InstID, Vals); // vararg
32220b57cec5SDimitry Andric     }
32230b57cec5SDimitry Andric     break;
32240b57cec5SDimitry Andric   }
32250b57cec5SDimitry Andric   case Instruction::Unreachable:
32260b57cec5SDimitry Andric     Code = bitc::FUNC_CODE_INST_UNREACHABLE;
32270b57cec5SDimitry Andric     AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
32280b57cec5SDimitry Andric     break;
32290b57cec5SDimitry Andric 
32300b57cec5SDimitry Andric   case Instruction::PHI: {
32310b57cec5SDimitry Andric     const PHINode &PN = cast<PHINode>(I);
32320b57cec5SDimitry Andric     Code = bitc::FUNC_CODE_INST_PHI;
32330b57cec5SDimitry Andric     // With the newer instruction encoding, forward references could give
32340b57cec5SDimitry Andric     // negative valued IDs.  This is most common for PHIs, so we use
32350b57cec5SDimitry Andric     // signed VBRs.
32360b57cec5SDimitry Andric     SmallVector<uint64_t, 128> Vals64;
32370b57cec5SDimitry Andric     Vals64.push_back(VE.getTypeID(PN.getType()));
32380b57cec5SDimitry Andric     for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
32390b57cec5SDimitry Andric       pushValueSigned(PN.getIncomingValue(i), InstID, Vals64);
32400b57cec5SDimitry Andric       Vals64.push_back(VE.getValueID(PN.getIncomingBlock(i)));
32410b57cec5SDimitry Andric     }
32428bcb0991SDimitry Andric 
32438bcb0991SDimitry Andric     uint64_t Flags = getOptimizationFlags(&I);
32448bcb0991SDimitry Andric     if (Flags != 0)
32458bcb0991SDimitry Andric       Vals64.push_back(Flags);
32468bcb0991SDimitry Andric 
32470b57cec5SDimitry Andric     // Emit a Vals64 vector and exit.
32480b57cec5SDimitry Andric     Stream.EmitRecord(Code, Vals64, AbbrevToUse);
32490b57cec5SDimitry Andric     Vals64.clear();
32500b57cec5SDimitry Andric     return;
32510b57cec5SDimitry Andric   }
32520b57cec5SDimitry Andric 
32530b57cec5SDimitry Andric   case Instruction::LandingPad: {
32540b57cec5SDimitry Andric     const LandingPadInst &LP = cast<LandingPadInst>(I);
32550b57cec5SDimitry Andric     Code = bitc::FUNC_CODE_INST_LANDINGPAD;
32560b57cec5SDimitry Andric     Vals.push_back(VE.getTypeID(LP.getType()));
32570b57cec5SDimitry Andric     Vals.push_back(LP.isCleanup());
32580b57cec5SDimitry Andric     Vals.push_back(LP.getNumClauses());
32590b57cec5SDimitry Andric     for (unsigned I = 0, E = LP.getNumClauses(); I != E; ++I) {
32600b57cec5SDimitry Andric       if (LP.isCatch(I))
32610b57cec5SDimitry Andric         Vals.push_back(LandingPadInst::Catch);
32620b57cec5SDimitry Andric       else
32630b57cec5SDimitry Andric         Vals.push_back(LandingPadInst::Filter);
32640b57cec5SDimitry Andric       pushValueAndType(LP.getClause(I), InstID, Vals);
32650b57cec5SDimitry Andric     }
32660b57cec5SDimitry Andric     break;
32670b57cec5SDimitry Andric   }
32680b57cec5SDimitry Andric 
32690b57cec5SDimitry Andric   case Instruction::Alloca: {
32700b57cec5SDimitry Andric     Code = bitc::FUNC_CODE_INST_ALLOCA;
32710b57cec5SDimitry Andric     const AllocaInst &AI = cast<AllocaInst>(I);
32720b57cec5SDimitry Andric     Vals.push_back(VE.getTypeID(AI.getAllocatedType()));
32730b57cec5SDimitry Andric     Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
32740b57cec5SDimitry Andric     Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
3275e8d8bef9SDimitry Andric     using APV = AllocaPackedValues;
3276e8d8bef9SDimitry Andric     unsigned Record = 0;
3277349cc55cSDimitry Andric     unsigned EncodedAlign = getEncodedAlign(AI.getAlign());
3278349cc55cSDimitry Andric     Bitfield::set<APV::AlignLower>(
3279349cc55cSDimitry Andric         Record, EncodedAlign & ((1 << APV::AlignLower::Bits) - 1));
3280349cc55cSDimitry Andric     Bitfield::set<APV::AlignUpper>(Record,
3281349cc55cSDimitry Andric                                    EncodedAlign >> APV::AlignLower::Bits);
3282e8d8bef9SDimitry Andric     Bitfield::set<APV::UsedWithInAlloca>(Record, AI.isUsedWithInAlloca());
3283e8d8bef9SDimitry Andric     Bitfield::set<APV::ExplicitType>(Record, true);
3284e8d8bef9SDimitry Andric     Bitfield::set<APV::SwiftError>(Record, AI.isSwiftError());
3285e8d8bef9SDimitry Andric     Vals.push_back(Record);
328681ad6265SDimitry Andric 
328781ad6265SDimitry Andric     unsigned AS = AI.getAddressSpace();
328881ad6265SDimitry Andric     if (AS != M.getDataLayout().getAllocaAddrSpace())
328981ad6265SDimitry Andric       Vals.push_back(AS);
32900b57cec5SDimitry Andric     break;
32910b57cec5SDimitry Andric   }
32920b57cec5SDimitry Andric 
32930b57cec5SDimitry Andric   case Instruction::Load:
32940b57cec5SDimitry Andric     if (cast<LoadInst>(I).isAtomic()) {
32950b57cec5SDimitry Andric       Code = bitc::FUNC_CODE_INST_LOADATOMIC;
32960b57cec5SDimitry Andric       pushValueAndType(I.getOperand(0), InstID, Vals);
32970b57cec5SDimitry Andric     } else {
32980b57cec5SDimitry Andric       Code = bitc::FUNC_CODE_INST_LOAD;
32990b57cec5SDimitry Andric       if (!pushValueAndType(I.getOperand(0), InstID, Vals)) // ptr
33000b57cec5SDimitry Andric         AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
33010b57cec5SDimitry Andric     }
33020b57cec5SDimitry Andric     Vals.push_back(VE.getTypeID(I.getType()));
3303e8d8bef9SDimitry Andric     Vals.push_back(getEncodedAlign(cast<LoadInst>(I).getAlign()));
33040b57cec5SDimitry Andric     Vals.push_back(cast<LoadInst>(I).isVolatile());
33050b57cec5SDimitry Andric     if (cast<LoadInst>(I).isAtomic()) {
33060b57cec5SDimitry Andric       Vals.push_back(getEncodedOrdering(cast<LoadInst>(I).getOrdering()));
33070b57cec5SDimitry Andric       Vals.push_back(getEncodedSyncScopeID(cast<LoadInst>(I).getSyncScopeID()));
33080b57cec5SDimitry Andric     }
33090b57cec5SDimitry Andric     break;
33100b57cec5SDimitry Andric   case Instruction::Store:
33110b57cec5SDimitry Andric     if (cast<StoreInst>(I).isAtomic())
33120b57cec5SDimitry Andric       Code = bitc::FUNC_CODE_INST_STOREATOMIC;
33130b57cec5SDimitry Andric     else
33140b57cec5SDimitry Andric       Code = bitc::FUNC_CODE_INST_STORE;
33150b57cec5SDimitry Andric     pushValueAndType(I.getOperand(1), InstID, Vals); // ptrty + ptr
33160b57cec5SDimitry Andric     pushValueAndType(I.getOperand(0), InstID, Vals); // valty + val
3317e8d8bef9SDimitry Andric     Vals.push_back(getEncodedAlign(cast<StoreInst>(I).getAlign()));
33180b57cec5SDimitry Andric     Vals.push_back(cast<StoreInst>(I).isVolatile());
33190b57cec5SDimitry Andric     if (cast<StoreInst>(I).isAtomic()) {
33200b57cec5SDimitry Andric       Vals.push_back(getEncodedOrdering(cast<StoreInst>(I).getOrdering()));
33210b57cec5SDimitry Andric       Vals.push_back(
33220b57cec5SDimitry Andric           getEncodedSyncScopeID(cast<StoreInst>(I).getSyncScopeID()));
33230b57cec5SDimitry Andric     }
33240b57cec5SDimitry Andric     break;
33250b57cec5SDimitry Andric   case Instruction::AtomicCmpXchg:
33260b57cec5SDimitry Andric     Code = bitc::FUNC_CODE_INST_CMPXCHG;
33270b57cec5SDimitry Andric     pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr
33280b57cec5SDimitry Andric     pushValueAndType(I.getOperand(1), InstID, Vals); // cmp.
33290b57cec5SDimitry Andric     pushValue(I.getOperand(2), InstID, Vals);        // newval.
33300b57cec5SDimitry Andric     Vals.push_back(cast<AtomicCmpXchgInst>(I).isVolatile());
33310b57cec5SDimitry Andric     Vals.push_back(
33320b57cec5SDimitry Andric         getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getSuccessOrdering()));
33330b57cec5SDimitry Andric     Vals.push_back(
33340b57cec5SDimitry Andric         getEncodedSyncScopeID(cast<AtomicCmpXchgInst>(I).getSyncScopeID()));
33350b57cec5SDimitry Andric     Vals.push_back(
33360b57cec5SDimitry Andric         getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getFailureOrdering()));
33370b57cec5SDimitry Andric     Vals.push_back(cast<AtomicCmpXchgInst>(I).isWeak());
3338fe6060f1SDimitry Andric     Vals.push_back(getEncodedAlign(cast<AtomicCmpXchgInst>(I).getAlign()));
33390b57cec5SDimitry Andric     break;
33400b57cec5SDimitry Andric   case Instruction::AtomicRMW:
33410b57cec5SDimitry Andric     Code = bitc::FUNC_CODE_INST_ATOMICRMW;
33420b57cec5SDimitry Andric     pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr
3343fe6060f1SDimitry Andric     pushValueAndType(I.getOperand(1), InstID, Vals); // valty + val
33440b57cec5SDimitry Andric     Vals.push_back(
33450b57cec5SDimitry Andric         getEncodedRMWOperation(cast<AtomicRMWInst>(I).getOperation()));
33460b57cec5SDimitry Andric     Vals.push_back(cast<AtomicRMWInst>(I).isVolatile());
33470b57cec5SDimitry Andric     Vals.push_back(getEncodedOrdering(cast<AtomicRMWInst>(I).getOrdering()));
33480b57cec5SDimitry Andric     Vals.push_back(
33490b57cec5SDimitry Andric         getEncodedSyncScopeID(cast<AtomicRMWInst>(I).getSyncScopeID()));
3350fe6060f1SDimitry Andric     Vals.push_back(getEncodedAlign(cast<AtomicRMWInst>(I).getAlign()));
33510b57cec5SDimitry Andric     break;
33520b57cec5SDimitry Andric   case Instruction::Fence:
33530b57cec5SDimitry Andric     Code = bitc::FUNC_CODE_INST_FENCE;
33540b57cec5SDimitry Andric     Vals.push_back(getEncodedOrdering(cast<FenceInst>(I).getOrdering()));
33550b57cec5SDimitry Andric     Vals.push_back(getEncodedSyncScopeID(cast<FenceInst>(I).getSyncScopeID()));
33560b57cec5SDimitry Andric     break;
33570b57cec5SDimitry Andric   case Instruction::Call: {
33580b57cec5SDimitry Andric     const CallInst &CI = cast<CallInst>(I);
33590b57cec5SDimitry Andric     FunctionType *FTy = CI.getFunctionType();
33600b57cec5SDimitry Andric 
33610b57cec5SDimitry Andric     if (CI.hasOperandBundles())
33625ffd83dbSDimitry Andric       writeOperandBundles(CI, InstID);
33630b57cec5SDimitry Andric 
33640b57cec5SDimitry Andric     Code = bitc::FUNC_CODE_INST_CALL;
33650b57cec5SDimitry Andric 
33660b57cec5SDimitry Andric     Vals.push_back(VE.getAttributeListID(CI.getAttributes()));
33670b57cec5SDimitry Andric 
33680b57cec5SDimitry Andric     unsigned Flags = getOptimizationFlags(&I);
33690b57cec5SDimitry Andric     Vals.push_back(CI.getCallingConv() << bitc::CALL_CCONV |
33700b57cec5SDimitry Andric                    unsigned(CI.isTailCall()) << bitc::CALL_TAIL |
33710b57cec5SDimitry Andric                    unsigned(CI.isMustTailCall()) << bitc::CALL_MUSTTAIL |
33720b57cec5SDimitry Andric                    1 << bitc::CALL_EXPLICIT_TYPE |
33730b57cec5SDimitry Andric                    unsigned(CI.isNoTailCall()) << bitc::CALL_NOTAIL |
33740b57cec5SDimitry Andric                    unsigned(Flags != 0) << bitc::CALL_FMF);
33750b57cec5SDimitry Andric     if (Flags != 0)
33760b57cec5SDimitry Andric       Vals.push_back(Flags);
33770b57cec5SDimitry Andric 
33780b57cec5SDimitry Andric     Vals.push_back(VE.getTypeID(FTy));
33795ffd83dbSDimitry Andric     pushValueAndType(CI.getCalledOperand(), InstID, Vals); // Callee
33800b57cec5SDimitry Andric 
33810b57cec5SDimitry Andric     // Emit value #'s for the fixed parameters.
33820b57cec5SDimitry Andric     for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
33830b57cec5SDimitry Andric       // Check for labels (can happen with asm labels).
33840b57cec5SDimitry Andric       if (FTy->getParamType(i)->isLabelTy())
33850b57cec5SDimitry Andric         Vals.push_back(VE.getValueID(CI.getArgOperand(i)));
33860b57cec5SDimitry Andric       else
33870b57cec5SDimitry Andric         pushValue(CI.getArgOperand(i), InstID, Vals); // fixed param.
33880b57cec5SDimitry Andric     }
33890b57cec5SDimitry Andric 
33900b57cec5SDimitry Andric     // Emit type/value pairs for varargs params.
33910b57cec5SDimitry Andric     if (FTy->isVarArg()) {
3392349cc55cSDimitry Andric       for (unsigned i = FTy->getNumParams(), e = CI.arg_size(); i != e; ++i)
33930b57cec5SDimitry Andric         pushValueAndType(CI.getArgOperand(i), InstID, Vals); // varargs
33940b57cec5SDimitry Andric     }
33950b57cec5SDimitry Andric     break;
33960b57cec5SDimitry Andric   }
33970b57cec5SDimitry Andric   case Instruction::VAArg:
33980b57cec5SDimitry Andric     Code = bitc::FUNC_CODE_INST_VAARG;
33990b57cec5SDimitry Andric     Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));   // valistty
34000b57cec5SDimitry Andric     pushValue(I.getOperand(0), InstID, Vals);                   // valist.
34010b57cec5SDimitry Andric     Vals.push_back(VE.getTypeID(I.getType())); // restype.
34020b57cec5SDimitry Andric     break;
3403480093f4SDimitry Andric   case Instruction::Freeze:
3404480093f4SDimitry Andric     Code = bitc::FUNC_CODE_INST_FREEZE;
3405480093f4SDimitry Andric     pushValueAndType(I.getOperand(0), InstID, Vals);
3406480093f4SDimitry Andric     break;
34070b57cec5SDimitry Andric   }
34080b57cec5SDimitry Andric 
34090b57cec5SDimitry Andric   Stream.EmitRecord(Code, Vals, AbbrevToUse);
34100b57cec5SDimitry Andric   Vals.clear();
34110b57cec5SDimitry Andric }
34120b57cec5SDimitry Andric 
34130b57cec5SDimitry Andric /// Write a GlobalValue VST to the module. The purpose of this data structure is
34140b57cec5SDimitry Andric /// to allow clients to efficiently find the function body.
34150b57cec5SDimitry Andric void ModuleBitcodeWriter::writeGlobalValueSymbolTable(
34160b57cec5SDimitry Andric   DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) {
34170b57cec5SDimitry Andric   // Get the offset of the VST we are writing, and backpatch it into
34180b57cec5SDimitry Andric   // the VST forward declaration record.
34190b57cec5SDimitry Andric   uint64_t VSTOffset = Stream.GetCurrentBitNo();
34200b57cec5SDimitry Andric   // The BitcodeStartBit was the stream offset of the identification block.
34210b57cec5SDimitry Andric   VSTOffset -= bitcodeStartBit();
34220b57cec5SDimitry Andric   assert((VSTOffset & 31) == 0 && "VST block not 32-bit aligned");
34230b57cec5SDimitry Andric   // Note that we add 1 here because the offset is relative to one word
34240b57cec5SDimitry Andric   // before the start of the identification block, which was historically
34250b57cec5SDimitry Andric   // always the start of the regular bitcode header.
34260b57cec5SDimitry Andric   Stream.BackpatchWord(VSTOffsetPlaceholder, VSTOffset / 32 + 1);
34270b57cec5SDimitry Andric 
34280b57cec5SDimitry Andric   Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
34290b57cec5SDimitry Andric 
34300b57cec5SDimitry Andric   auto Abbv = std::make_shared<BitCodeAbbrev>();
34310b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_FNENTRY));
34320b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
34330b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // funcoffset
34340b57cec5SDimitry Andric   unsigned FnEntryAbbrev = Stream.EmitAbbrev(std::move(Abbv));
34350b57cec5SDimitry Andric 
34360b57cec5SDimitry Andric   for (const Function &F : M) {
34370b57cec5SDimitry Andric     uint64_t Record[2];
34380b57cec5SDimitry Andric 
34390b57cec5SDimitry Andric     if (F.isDeclaration())
34400b57cec5SDimitry Andric       continue;
34410b57cec5SDimitry Andric 
34420b57cec5SDimitry Andric     Record[0] = VE.getValueID(&F);
34430b57cec5SDimitry Andric 
34440b57cec5SDimitry Andric     // Save the word offset of the function (from the start of the
34450b57cec5SDimitry Andric     // actual bitcode written to the stream).
34460b57cec5SDimitry Andric     uint64_t BitcodeIndex = FunctionToBitcodeIndex[&F] - bitcodeStartBit();
34470b57cec5SDimitry Andric     assert((BitcodeIndex & 31) == 0 && "function block not 32-bit aligned");
34480b57cec5SDimitry Andric     // Note that we add 1 here because the offset is relative to one word
34490b57cec5SDimitry Andric     // before the start of the identification block, which was historically
34500b57cec5SDimitry Andric     // always the start of the regular bitcode header.
34510b57cec5SDimitry Andric     Record[1] = BitcodeIndex / 32 + 1;
34520b57cec5SDimitry Andric 
34530b57cec5SDimitry Andric     Stream.EmitRecord(bitc::VST_CODE_FNENTRY, Record, FnEntryAbbrev);
34540b57cec5SDimitry Andric   }
34550b57cec5SDimitry Andric 
34560b57cec5SDimitry Andric   Stream.ExitBlock();
34570b57cec5SDimitry Andric }
34580b57cec5SDimitry Andric 
34590b57cec5SDimitry Andric /// Emit names for arguments, instructions and basic blocks in a function.
34600b57cec5SDimitry Andric void ModuleBitcodeWriter::writeFunctionLevelValueSymbolTable(
34610b57cec5SDimitry Andric     const ValueSymbolTable &VST) {
34620b57cec5SDimitry Andric   if (VST.empty())
34630b57cec5SDimitry Andric     return;
34640b57cec5SDimitry Andric 
34650b57cec5SDimitry Andric   Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
34660b57cec5SDimitry Andric 
34670b57cec5SDimitry Andric   // FIXME: Set up the abbrev, we know how many values there are!
34680b57cec5SDimitry Andric   // FIXME: We know if the type names can use 7-bit ascii.
34690b57cec5SDimitry Andric   SmallVector<uint64_t, 64> NameVals;
34700b57cec5SDimitry Andric 
34710b57cec5SDimitry Andric   for (const ValueName &Name : VST) {
34720b57cec5SDimitry Andric     // Figure out the encoding to use for the name.
34730b57cec5SDimitry Andric     StringEncoding Bits = getStringEncoding(Name.getKey());
34740b57cec5SDimitry Andric 
34750b57cec5SDimitry Andric     unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
34760b57cec5SDimitry Andric     NameVals.push_back(VE.getValueID(Name.getValue()));
34770b57cec5SDimitry Andric 
34780b57cec5SDimitry Andric     // VST_CODE_ENTRY:   [valueid, namechar x N]
34790b57cec5SDimitry Andric     // VST_CODE_BBENTRY: [bbid, namechar x N]
34800b57cec5SDimitry Andric     unsigned Code;
34810b57cec5SDimitry Andric     if (isa<BasicBlock>(Name.getValue())) {
34820b57cec5SDimitry Andric       Code = bitc::VST_CODE_BBENTRY;
34830b57cec5SDimitry Andric       if (Bits == SE_Char6)
34840b57cec5SDimitry Andric         AbbrevToUse = VST_BBENTRY_6_ABBREV;
34850b57cec5SDimitry Andric     } else {
34860b57cec5SDimitry Andric       Code = bitc::VST_CODE_ENTRY;
34870b57cec5SDimitry Andric       if (Bits == SE_Char6)
34880b57cec5SDimitry Andric         AbbrevToUse = VST_ENTRY_6_ABBREV;
34890b57cec5SDimitry Andric       else if (Bits == SE_Fixed7)
34900b57cec5SDimitry Andric         AbbrevToUse = VST_ENTRY_7_ABBREV;
34910b57cec5SDimitry Andric     }
34920b57cec5SDimitry Andric 
34930b57cec5SDimitry Andric     for (const auto P : Name.getKey())
34940b57cec5SDimitry Andric       NameVals.push_back((unsigned char)P);
34950b57cec5SDimitry Andric 
34960b57cec5SDimitry Andric     // Emit the finished record.
34970b57cec5SDimitry Andric     Stream.EmitRecord(Code, NameVals, AbbrevToUse);
34980b57cec5SDimitry Andric     NameVals.clear();
34990b57cec5SDimitry Andric   }
35000b57cec5SDimitry Andric 
35010b57cec5SDimitry Andric   Stream.ExitBlock();
35020b57cec5SDimitry Andric }
35030b57cec5SDimitry Andric 
35040b57cec5SDimitry Andric void ModuleBitcodeWriter::writeUseList(UseListOrder &&Order) {
35050b57cec5SDimitry Andric   assert(Order.Shuffle.size() >= 2 && "Shuffle too small");
35060b57cec5SDimitry Andric   unsigned Code;
35070b57cec5SDimitry Andric   if (isa<BasicBlock>(Order.V))
35080b57cec5SDimitry Andric     Code = bitc::USELIST_CODE_BB;
35090b57cec5SDimitry Andric   else
35100b57cec5SDimitry Andric     Code = bitc::USELIST_CODE_DEFAULT;
35110b57cec5SDimitry Andric 
35120b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record(Order.Shuffle.begin(), Order.Shuffle.end());
35130b57cec5SDimitry Andric   Record.push_back(VE.getValueID(Order.V));
35140b57cec5SDimitry Andric   Stream.EmitRecord(Code, Record);
35150b57cec5SDimitry Andric }
35160b57cec5SDimitry Andric 
35170b57cec5SDimitry Andric void ModuleBitcodeWriter::writeUseListBlock(const Function *F) {
35180b57cec5SDimitry Andric   assert(VE.shouldPreserveUseListOrder() &&
35190b57cec5SDimitry Andric          "Expected to be preserving use-list order");
35200b57cec5SDimitry Andric 
35210b57cec5SDimitry Andric   auto hasMore = [&]() {
35220b57cec5SDimitry Andric     return !VE.UseListOrders.empty() && VE.UseListOrders.back().F == F;
35230b57cec5SDimitry Andric   };
35240b57cec5SDimitry Andric   if (!hasMore())
35250b57cec5SDimitry Andric     // Nothing to do.
35260b57cec5SDimitry Andric     return;
35270b57cec5SDimitry Andric 
35280b57cec5SDimitry Andric   Stream.EnterSubblock(bitc::USELIST_BLOCK_ID, 3);
35290b57cec5SDimitry Andric   while (hasMore()) {
35300b57cec5SDimitry Andric     writeUseList(std::move(VE.UseListOrders.back()));
35310b57cec5SDimitry Andric     VE.UseListOrders.pop_back();
35320b57cec5SDimitry Andric   }
35330b57cec5SDimitry Andric   Stream.ExitBlock();
35340b57cec5SDimitry Andric }
35350b57cec5SDimitry Andric 
35360b57cec5SDimitry Andric /// Emit a function body to the module stream.
35370b57cec5SDimitry Andric void ModuleBitcodeWriter::writeFunction(
35380b57cec5SDimitry Andric     const Function &F,
35390b57cec5SDimitry Andric     DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) {
35400b57cec5SDimitry Andric   // Save the bitcode index of the start of this function block for recording
35410b57cec5SDimitry Andric   // in the VST.
35420b57cec5SDimitry Andric   FunctionToBitcodeIndex[&F] = Stream.GetCurrentBitNo();
35430b57cec5SDimitry Andric 
35440b57cec5SDimitry Andric   Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 4);
35450b57cec5SDimitry Andric   VE.incorporateFunction(F);
35460b57cec5SDimitry Andric 
35470b57cec5SDimitry Andric   SmallVector<unsigned, 64> Vals;
35480b57cec5SDimitry Andric 
35490b57cec5SDimitry Andric   // Emit the number of basic blocks, so the reader can create them ahead of
35500b57cec5SDimitry Andric   // time.
35510b57cec5SDimitry Andric   Vals.push_back(VE.getBasicBlocks().size());
35520b57cec5SDimitry Andric   Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals);
35530b57cec5SDimitry Andric   Vals.clear();
35540b57cec5SDimitry Andric 
35550b57cec5SDimitry Andric   // If there are function-local constants, emit them now.
35560b57cec5SDimitry Andric   unsigned CstStart, CstEnd;
35570b57cec5SDimitry Andric   VE.getFunctionConstantRange(CstStart, CstEnd);
35580b57cec5SDimitry Andric   writeConstants(CstStart, CstEnd, false);
35590b57cec5SDimitry Andric 
35600b57cec5SDimitry Andric   // If there is function-local metadata, emit it now.
35610b57cec5SDimitry Andric   writeFunctionMetadata(F);
35620b57cec5SDimitry Andric 
35630b57cec5SDimitry Andric   // Keep a running idea of what the instruction ID is.
35640b57cec5SDimitry Andric   unsigned InstID = CstEnd;
35650b57cec5SDimitry Andric 
35660b57cec5SDimitry Andric   bool NeedsMetadataAttachment = F.hasMetadata();
35670b57cec5SDimitry Andric 
35680b57cec5SDimitry Andric   DILocation *LastDL = nullptr;
356981ad6265SDimitry Andric   SmallSetVector<Function *, 4> BlockAddressUsers;
357081ad6265SDimitry Andric 
35710b57cec5SDimitry Andric   // Finally, emit all the instructions, in order.
357281ad6265SDimitry Andric   for (const BasicBlock &BB : F) {
35734824e7fdSDimitry Andric     for (const Instruction &I : BB) {
35744824e7fdSDimitry Andric       writeInstruction(I, InstID, Vals);
35750b57cec5SDimitry Andric 
35764824e7fdSDimitry Andric       if (!I.getType()->isVoidTy())
35770b57cec5SDimitry Andric         ++InstID;
35780b57cec5SDimitry Andric 
35790b57cec5SDimitry Andric       // If the instruction has metadata, write a metadata attachment later.
35804824e7fdSDimitry Andric       NeedsMetadataAttachment |= I.hasMetadataOtherThanDebugLoc();
35810b57cec5SDimitry Andric 
35820b57cec5SDimitry Andric       // If the instruction has a debug location, emit it.
3583*0fca6ea1SDimitry Andric       if (DILocation *DL = I.getDebugLoc()) {
35840b57cec5SDimitry Andric         if (DL == LastDL) {
35850b57cec5SDimitry Andric           // Just repeat the same debug loc as last time.
35860b57cec5SDimitry Andric           Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC_AGAIN, Vals);
3587*0fca6ea1SDimitry Andric         } else {
35880b57cec5SDimitry Andric           Vals.push_back(DL->getLine());
35890b57cec5SDimitry Andric           Vals.push_back(DL->getColumn());
35900b57cec5SDimitry Andric           Vals.push_back(VE.getMetadataOrNullID(DL->getScope()));
35910b57cec5SDimitry Andric           Vals.push_back(VE.getMetadataOrNullID(DL->getInlinedAt()));
35920b57cec5SDimitry Andric           Vals.push_back(DL->isImplicitCode());
35930b57cec5SDimitry Andric           Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC, Vals);
35940b57cec5SDimitry Andric           Vals.clear();
35950b57cec5SDimitry Andric           LastDL = DL;
35960b57cec5SDimitry Andric         }
3597*0fca6ea1SDimitry Andric       }
3598*0fca6ea1SDimitry Andric 
3599*0fca6ea1SDimitry Andric       // If the instruction has DbgRecords attached to it, emit them. Note that
3600*0fca6ea1SDimitry Andric       // they come after the instruction so that it's easy to attach them again
3601*0fca6ea1SDimitry Andric       // when reading the bitcode, even though conceptually the debug locations
3602*0fca6ea1SDimitry Andric       // start "before" the instruction.
3603*0fca6ea1SDimitry Andric       if (I.hasDbgRecords() && WriteNewDbgInfoFormatToBitcode) {
3604*0fca6ea1SDimitry Andric         /// Try to push the value only (unwrapped), otherwise push the
3605*0fca6ea1SDimitry Andric         /// metadata wrapped value. Returns true if the value was pushed
3606*0fca6ea1SDimitry Andric         /// without the ValueAsMetadata wrapper.
3607*0fca6ea1SDimitry Andric         auto PushValueOrMetadata = [&Vals, InstID,
3608*0fca6ea1SDimitry Andric                                     this](Metadata *RawLocation) {
3609*0fca6ea1SDimitry Andric           assert(RawLocation &&
3610*0fca6ea1SDimitry Andric                  "RawLocation unexpectedly null in DbgVariableRecord");
3611*0fca6ea1SDimitry Andric           if (ValueAsMetadata *VAM = dyn_cast<ValueAsMetadata>(RawLocation)) {
3612*0fca6ea1SDimitry Andric             SmallVector<unsigned, 2> ValAndType;
3613*0fca6ea1SDimitry Andric             // If the value is a fwd-ref the type is also pushed. We don't
3614*0fca6ea1SDimitry Andric             // want the type, so fwd-refs are kept wrapped (pushValueAndType
3615*0fca6ea1SDimitry Andric             // returns false if the value is pushed without type).
3616*0fca6ea1SDimitry Andric             if (!pushValueAndType(VAM->getValue(), InstID, ValAndType)) {
3617*0fca6ea1SDimitry Andric               Vals.push_back(ValAndType[0]);
3618*0fca6ea1SDimitry Andric               return true;
3619*0fca6ea1SDimitry Andric             }
3620*0fca6ea1SDimitry Andric           }
3621*0fca6ea1SDimitry Andric           // The metadata is a DIArgList, or ValueAsMetadata wrapping a
3622*0fca6ea1SDimitry Andric           // fwd-ref. Push the metadata ID.
3623*0fca6ea1SDimitry Andric           Vals.push_back(VE.getMetadataID(RawLocation));
3624*0fca6ea1SDimitry Andric           return false;
3625*0fca6ea1SDimitry Andric         };
3626*0fca6ea1SDimitry Andric 
3627*0fca6ea1SDimitry Andric         // Write out non-instruction debug information attached to this
3628*0fca6ea1SDimitry Andric         // instruction. Write it after the instruction so that it's easy to
3629*0fca6ea1SDimitry Andric         // re-attach to the instruction reading the records in.
3630*0fca6ea1SDimitry Andric         for (DbgRecord &DR : I.DebugMarker->getDbgRecordRange()) {
3631*0fca6ea1SDimitry Andric           if (DbgLabelRecord *DLR = dyn_cast<DbgLabelRecord>(&DR)) {
3632*0fca6ea1SDimitry Andric             Vals.push_back(VE.getMetadataID(&*DLR->getDebugLoc()));
3633*0fca6ea1SDimitry Andric             Vals.push_back(VE.getMetadataID(DLR->getLabel()));
3634*0fca6ea1SDimitry Andric             Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_RECORD_LABEL, Vals);
3635*0fca6ea1SDimitry Andric             Vals.clear();
3636*0fca6ea1SDimitry Andric             continue;
3637*0fca6ea1SDimitry Andric           }
3638*0fca6ea1SDimitry Andric 
3639*0fca6ea1SDimitry Andric           // First 3 fields are common to all kinds:
3640*0fca6ea1SDimitry Andric           //   DILocation, DILocalVariable, DIExpression
3641*0fca6ea1SDimitry Andric           // dbg_value (FUNC_CODE_DEBUG_RECORD_VALUE)
3642*0fca6ea1SDimitry Andric           //   ..., LocationMetadata
3643*0fca6ea1SDimitry Andric           // dbg_value (FUNC_CODE_DEBUG_RECORD_VALUE_SIMPLE - abbrev'd)
3644*0fca6ea1SDimitry Andric           //   ..., Value
3645*0fca6ea1SDimitry Andric           // dbg_declare (FUNC_CODE_DEBUG_RECORD_DECLARE)
3646*0fca6ea1SDimitry Andric           //   ..., LocationMetadata
3647*0fca6ea1SDimitry Andric           // dbg_assign (FUNC_CODE_DEBUG_RECORD_ASSIGN)
3648*0fca6ea1SDimitry Andric           //   ..., LocationMetadata, DIAssignID, DIExpression, LocationMetadata
3649*0fca6ea1SDimitry Andric           DbgVariableRecord &DVR = cast<DbgVariableRecord>(DR);
3650*0fca6ea1SDimitry Andric           Vals.push_back(VE.getMetadataID(&*DVR.getDebugLoc()));
3651*0fca6ea1SDimitry Andric           Vals.push_back(VE.getMetadataID(DVR.getVariable()));
3652*0fca6ea1SDimitry Andric           Vals.push_back(VE.getMetadataID(DVR.getExpression()));
3653*0fca6ea1SDimitry Andric           if (DVR.isDbgValue()) {
3654*0fca6ea1SDimitry Andric             if (PushValueOrMetadata(DVR.getRawLocation()))
3655*0fca6ea1SDimitry Andric               Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_RECORD_VALUE_SIMPLE, Vals,
3656*0fca6ea1SDimitry Andric                                 FUNCTION_DEBUG_RECORD_VALUE_ABBREV);
3657*0fca6ea1SDimitry Andric             else
3658*0fca6ea1SDimitry Andric               Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_RECORD_VALUE, Vals);
3659*0fca6ea1SDimitry Andric           } else if (DVR.isDbgDeclare()) {
3660*0fca6ea1SDimitry Andric             Vals.push_back(VE.getMetadataID(DVR.getRawLocation()));
3661*0fca6ea1SDimitry Andric             Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_RECORD_DECLARE, Vals);
3662*0fca6ea1SDimitry Andric           } else {
3663*0fca6ea1SDimitry Andric             assert(DVR.isDbgAssign() && "Unexpected DbgRecord kind");
3664*0fca6ea1SDimitry Andric             Vals.push_back(VE.getMetadataID(DVR.getRawLocation()));
3665*0fca6ea1SDimitry Andric             Vals.push_back(VE.getMetadataID(DVR.getAssignID()));
3666*0fca6ea1SDimitry Andric             Vals.push_back(VE.getMetadataID(DVR.getAddressExpression()));
3667*0fca6ea1SDimitry Andric             Vals.push_back(VE.getMetadataID(DVR.getRawAddress()));
3668*0fca6ea1SDimitry Andric             Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_RECORD_ASSIGN, Vals);
3669*0fca6ea1SDimitry Andric           }
3670*0fca6ea1SDimitry Andric           Vals.clear();
3671*0fca6ea1SDimitry Andric         }
3672*0fca6ea1SDimitry Andric       }
3673*0fca6ea1SDimitry Andric     }
36740b57cec5SDimitry Andric 
367581ad6265SDimitry Andric     if (BlockAddress *BA = BlockAddress::lookup(&BB)) {
367681ad6265SDimitry Andric       SmallVector<Value *> Worklist{BA};
367781ad6265SDimitry Andric       SmallPtrSet<Value *, 8> Visited{BA};
367881ad6265SDimitry Andric       while (!Worklist.empty()) {
367981ad6265SDimitry Andric         Value *V = Worklist.pop_back_val();
368081ad6265SDimitry Andric         for (User *U : V->users()) {
368181ad6265SDimitry Andric           if (auto *I = dyn_cast<Instruction>(U)) {
368281ad6265SDimitry Andric             Function *P = I->getFunction();
368381ad6265SDimitry Andric             if (P != &F)
368481ad6265SDimitry Andric               BlockAddressUsers.insert(P);
368581ad6265SDimitry Andric           } else if (isa<Constant>(U) && !isa<GlobalValue>(U) &&
368681ad6265SDimitry Andric                      Visited.insert(U).second)
368781ad6265SDimitry Andric             Worklist.push_back(U);
368881ad6265SDimitry Andric         }
368981ad6265SDimitry Andric       }
369081ad6265SDimitry Andric     }
369181ad6265SDimitry Andric   }
369281ad6265SDimitry Andric 
369381ad6265SDimitry Andric   if (!BlockAddressUsers.empty()) {
369481ad6265SDimitry Andric     Vals.resize(BlockAddressUsers.size());
369581ad6265SDimitry Andric     for (auto I : llvm::enumerate(BlockAddressUsers))
369681ad6265SDimitry Andric       Vals[I.index()] = VE.getValueID(I.value());
369781ad6265SDimitry Andric     Stream.EmitRecord(bitc::FUNC_CODE_BLOCKADDR_USERS, Vals);
369881ad6265SDimitry Andric     Vals.clear();
369981ad6265SDimitry Andric   }
370081ad6265SDimitry Andric 
37010b57cec5SDimitry Andric   // Emit names for all the instructions etc.
37020b57cec5SDimitry Andric   if (auto *Symtab = F.getValueSymbolTable())
37030b57cec5SDimitry Andric     writeFunctionLevelValueSymbolTable(*Symtab);
37040b57cec5SDimitry Andric 
37050b57cec5SDimitry Andric   if (NeedsMetadataAttachment)
37060b57cec5SDimitry Andric     writeFunctionMetadataAttachment(F);
37070b57cec5SDimitry Andric   if (VE.shouldPreserveUseListOrder())
37080b57cec5SDimitry Andric     writeUseListBlock(&F);
37090b57cec5SDimitry Andric   VE.purgeFunction();
37100b57cec5SDimitry Andric   Stream.ExitBlock();
37110b57cec5SDimitry Andric }
37120b57cec5SDimitry Andric 
37130b57cec5SDimitry Andric // Emit blockinfo, which defines the standard abbreviations etc.
37140b57cec5SDimitry Andric void ModuleBitcodeWriter::writeBlockInfo() {
37150b57cec5SDimitry Andric   // We only want to emit block info records for blocks that have multiple
37160b57cec5SDimitry Andric   // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK.
37170b57cec5SDimitry Andric   // Other blocks can define their abbrevs inline.
37180b57cec5SDimitry Andric   Stream.EnterBlockInfoBlock();
37190b57cec5SDimitry Andric 
37200b57cec5SDimitry Andric   { // 8-bit fixed-width VST_CODE_ENTRY/VST_CODE_BBENTRY strings.
37210b57cec5SDimitry Andric     auto Abbv = std::make_shared<BitCodeAbbrev>();
37220b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3));
37230b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
37240b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
37250b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
37260b57cec5SDimitry Andric     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
37270b57cec5SDimitry Andric         VST_ENTRY_8_ABBREV)
37280b57cec5SDimitry Andric       llvm_unreachable("Unexpected abbrev ordering!");
37290b57cec5SDimitry Andric   }
37300b57cec5SDimitry Andric 
37310b57cec5SDimitry Andric   { // 7-bit fixed width VST_CODE_ENTRY strings.
37320b57cec5SDimitry Andric     auto Abbv = std::make_shared<BitCodeAbbrev>();
37330b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
37340b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
37350b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
37360b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
37370b57cec5SDimitry Andric     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
37380b57cec5SDimitry Andric         VST_ENTRY_7_ABBREV)
37390b57cec5SDimitry Andric       llvm_unreachable("Unexpected abbrev ordering!");
37400b57cec5SDimitry Andric   }
37410b57cec5SDimitry Andric   { // 6-bit char6 VST_CODE_ENTRY strings.
37420b57cec5SDimitry Andric     auto Abbv = std::make_shared<BitCodeAbbrev>();
37430b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
37440b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
37450b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
37460b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
37470b57cec5SDimitry Andric     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
37480b57cec5SDimitry Andric         VST_ENTRY_6_ABBREV)
37490b57cec5SDimitry Andric       llvm_unreachable("Unexpected abbrev ordering!");
37500b57cec5SDimitry Andric   }
37510b57cec5SDimitry Andric   { // 6-bit char6 VST_CODE_BBENTRY strings.
37520b57cec5SDimitry Andric     auto Abbv = std::make_shared<BitCodeAbbrev>();
37530b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY));
37540b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
37550b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
37560b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
37570b57cec5SDimitry Andric     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
37580b57cec5SDimitry Andric         VST_BBENTRY_6_ABBREV)
37590b57cec5SDimitry Andric       llvm_unreachable("Unexpected abbrev ordering!");
37600b57cec5SDimitry Andric   }
37610b57cec5SDimitry Andric 
37620b57cec5SDimitry Andric   { // SETTYPE abbrev for CONSTANTS_BLOCK.
37630b57cec5SDimitry Andric     auto Abbv = std::make_shared<BitCodeAbbrev>();
37640b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_SETTYPE));
37650b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
3766*0fca6ea1SDimitry Andric                               VE.computeBitsRequiredForTypeIndices()));
37670b57cec5SDimitry Andric     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
37680b57cec5SDimitry Andric         CONSTANTS_SETTYPE_ABBREV)
37690b57cec5SDimitry Andric       llvm_unreachable("Unexpected abbrev ordering!");
37700b57cec5SDimitry Andric   }
37710b57cec5SDimitry Andric 
37720b57cec5SDimitry Andric   { // INTEGER abbrev for CONSTANTS_BLOCK.
37730b57cec5SDimitry Andric     auto Abbv = std::make_shared<BitCodeAbbrev>();
37740b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_INTEGER));
37750b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
37760b57cec5SDimitry Andric     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
37770b57cec5SDimitry Andric         CONSTANTS_INTEGER_ABBREV)
37780b57cec5SDimitry Andric       llvm_unreachable("Unexpected abbrev ordering!");
37790b57cec5SDimitry Andric   }
37800b57cec5SDimitry Andric 
37810b57cec5SDimitry Andric   { // CE_CAST abbrev for CONSTANTS_BLOCK.
37820b57cec5SDimitry Andric     auto Abbv = std::make_shared<BitCodeAbbrev>();
37830b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CE_CAST));
37840b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4));  // cast opc
37850b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,       // typeid
3786*0fca6ea1SDimitry Andric                               VE.computeBitsRequiredForTypeIndices()));
37870b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));    // value id
37880b57cec5SDimitry Andric 
37890b57cec5SDimitry Andric     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
37900b57cec5SDimitry Andric         CONSTANTS_CE_CAST_Abbrev)
37910b57cec5SDimitry Andric       llvm_unreachable("Unexpected abbrev ordering!");
37920b57cec5SDimitry Andric   }
37930b57cec5SDimitry Andric   { // NULL abbrev for CONSTANTS_BLOCK.
37940b57cec5SDimitry Andric     auto Abbv = std::make_shared<BitCodeAbbrev>();
37950b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_NULL));
37960b57cec5SDimitry Andric     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
37970b57cec5SDimitry Andric         CONSTANTS_NULL_Abbrev)
37980b57cec5SDimitry Andric       llvm_unreachable("Unexpected abbrev ordering!");
37990b57cec5SDimitry Andric   }
38000b57cec5SDimitry Andric 
38010b57cec5SDimitry Andric   // FIXME: This should only use space for first class types!
38020b57cec5SDimitry Andric 
38030b57cec5SDimitry Andric   { // INST_LOAD abbrev for FUNCTION_BLOCK.
38040b57cec5SDimitry Andric     auto Abbv = std::make_shared<BitCodeAbbrev>();
38050b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_LOAD));
38060b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Ptr
38070b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,    // dest ty
3808*0fca6ea1SDimitry Andric                               VE.computeBitsRequiredForTypeIndices()));
38090b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align
38100b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile
38110b57cec5SDimitry Andric     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
38120b57cec5SDimitry Andric         FUNCTION_INST_LOAD_ABBREV)
38130b57cec5SDimitry Andric       llvm_unreachable("Unexpected abbrev ordering!");
38140b57cec5SDimitry Andric   }
38150b57cec5SDimitry Andric   { // INST_UNOP abbrev for FUNCTION_BLOCK.
38160b57cec5SDimitry Andric     auto Abbv = std::make_shared<BitCodeAbbrev>();
38170b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNOP));
38180b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
38190b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
38200b57cec5SDimitry Andric     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
38210b57cec5SDimitry Andric         FUNCTION_INST_UNOP_ABBREV)
38220b57cec5SDimitry Andric       llvm_unreachable("Unexpected abbrev ordering!");
38230b57cec5SDimitry Andric   }
38240b57cec5SDimitry Andric   { // INST_UNOP_FLAGS abbrev for FUNCTION_BLOCK.
38250b57cec5SDimitry Andric     auto Abbv = std::make_shared<BitCodeAbbrev>();
38260b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNOP));
38270b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
38280b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
38290b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); // flags
38300b57cec5SDimitry Andric     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
38310b57cec5SDimitry Andric         FUNCTION_INST_UNOP_FLAGS_ABBREV)
38320b57cec5SDimitry Andric       llvm_unreachable("Unexpected abbrev ordering!");
38330b57cec5SDimitry Andric   }
38340b57cec5SDimitry Andric   { // INST_BINOP abbrev for FUNCTION_BLOCK.
38350b57cec5SDimitry Andric     auto Abbv = std::make_shared<BitCodeAbbrev>();
38360b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
38370b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
38380b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
38390b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
38400b57cec5SDimitry Andric     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
38410b57cec5SDimitry Andric         FUNCTION_INST_BINOP_ABBREV)
38420b57cec5SDimitry Andric       llvm_unreachable("Unexpected abbrev ordering!");
38430b57cec5SDimitry Andric   }
38440b57cec5SDimitry Andric   { // INST_BINOP_FLAGS abbrev for FUNCTION_BLOCK.
38450b57cec5SDimitry Andric     auto Abbv = std::make_shared<BitCodeAbbrev>();
38460b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
38470b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
38480b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
38490b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
38500b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); // flags
38510b57cec5SDimitry Andric     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
38520b57cec5SDimitry Andric         FUNCTION_INST_BINOP_FLAGS_ABBREV)
38530b57cec5SDimitry Andric       llvm_unreachable("Unexpected abbrev ordering!");
38540b57cec5SDimitry Andric   }
38550b57cec5SDimitry Andric   { // INST_CAST abbrev for FUNCTION_BLOCK.
38560b57cec5SDimitry Andric     auto Abbv = std::make_shared<BitCodeAbbrev>();
38570b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST));
38580b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));    // OpVal
38590b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,       // dest ty
3860*0fca6ea1SDimitry Andric                               VE.computeBitsRequiredForTypeIndices()));
38610b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4));  // opc
38620b57cec5SDimitry Andric     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
38630b57cec5SDimitry Andric         FUNCTION_INST_CAST_ABBREV)
38640b57cec5SDimitry Andric       llvm_unreachable("Unexpected abbrev ordering!");
38650b57cec5SDimitry Andric   }
38665f757f3fSDimitry Andric   { // INST_CAST_FLAGS abbrev for FUNCTION_BLOCK.
38675f757f3fSDimitry Andric     auto Abbv = std::make_shared<BitCodeAbbrev>();
38685f757f3fSDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST));
38695f757f3fSDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // OpVal
38705f757f3fSDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,    // dest ty
3871*0fca6ea1SDimitry Andric                               VE.computeBitsRequiredForTypeIndices()));
38725f757f3fSDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
38735f757f3fSDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); // flags
38745f757f3fSDimitry Andric     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
38755f757f3fSDimitry Andric         FUNCTION_INST_CAST_FLAGS_ABBREV)
38765f757f3fSDimitry Andric       llvm_unreachable("Unexpected abbrev ordering!");
38775f757f3fSDimitry Andric   }
38780b57cec5SDimitry Andric 
38790b57cec5SDimitry Andric   { // INST_RET abbrev for FUNCTION_BLOCK.
38800b57cec5SDimitry Andric     auto Abbv = std::make_shared<BitCodeAbbrev>();
38810b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
38820b57cec5SDimitry Andric     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
38830b57cec5SDimitry Andric         FUNCTION_INST_RET_VOID_ABBREV)
38840b57cec5SDimitry Andric       llvm_unreachable("Unexpected abbrev ordering!");
38850b57cec5SDimitry Andric   }
38860b57cec5SDimitry Andric   { // INST_RET abbrev for FUNCTION_BLOCK.
38870b57cec5SDimitry Andric     auto Abbv = std::make_shared<BitCodeAbbrev>();
38880b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
38890b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ValID
38900b57cec5SDimitry Andric     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
38910b57cec5SDimitry Andric         FUNCTION_INST_RET_VAL_ABBREV)
38920b57cec5SDimitry Andric       llvm_unreachable("Unexpected abbrev ordering!");
38930b57cec5SDimitry Andric   }
38940b57cec5SDimitry Andric   { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK.
38950b57cec5SDimitry Andric     auto Abbv = std::make_shared<BitCodeAbbrev>();
38960b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNREACHABLE));
38970b57cec5SDimitry Andric     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
38980b57cec5SDimitry Andric         FUNCTION_INST_UNREACHABLE_ABBREV)
38990b57cec5SDimitry Andric       llvm_unreachable("Unexpected abbrev ordering!");
39000b57cec5SDimitry Andric   }
39010b57cec5SDimitry Andric   {
39020b57cec5SDimitry Andric     auto Abbv = std::make_shared<BitCodeAbbrev>();
39030b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_GEP));
3904*0fca6ea1SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3));
39050b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
39060b57cec5SDimitry Andric                               Log2_32_Ceil(VE.getTypes().size() + 1)));
39070b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
39080b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
39090b57cec5SDimitry Andric     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
39100b57cec5SDimitry Andric         FUNCTION_INST_GEP_ABBREV)
39110b57cec5SDimitry Andric       llvm_unreachable("Unexpected abbrev ordering!");
39120b57cec5SDimitry Andric   }
3913*0fca6ea1SDimitry Andric   {
3914*0fca6ea1SDimitry Andric     auto Abbv = std::make_shared<BitCodeAbbrev>();
3915*0fca6ea1SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_DEBUG_RECORD_VALUE_SIMPLE));
3916*0fca6ea1SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 7)); // dbgloc
3917*0fca6ea1SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 7)); // var
3918*0fca6ea1SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 7)); // expr
3919*0fca6ea1SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // val
3920*0fca6ea1SDimitry Andric     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3921*0fca6ea1SDimitry Andric         FUNCTION_DEBUG_RECORD_VALUE_ABBREV)
3922*0fca6ea1SDimitry Andric       llvm_unreachable("Unexpected abbrev ordering! 1");
3923*0fca6ea1SDimitry Andric   }
39240b57cec5SDimitry Andric   Stream.ExitBlock();
39250b57cec5SDimitry Andric }
39260b57cec5SDimitry Andric 
39270b57cec5SDimitry Andric /// Write the module path strings, currently only used when generating
39280b57cec5SDimitry Andric /// a combined index file.
39290b57cec5SDimitry Andric void IndexBitcodeWriter::writeModStrings() {
39300b57cec5SDimitry Andric   Stream.EnterSubblock(bitc::MODULE_STRTAB_BLOCK_ID, 3);
39310b57cec5SDimitry Andric 
39320b57cec5SDimitry Andric   // TODO: See which abbrev sizes we actually need to emit
39330b57cec5SDimitry Andric 
39340b57cec5SDimitry Andric   // 8-bit fixed-width MST_ENTRY strings.
39350b57cec5SDimitry Andric   auto Abbv = std::make_shared<BitCodeAbbrev>();
39360b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
39370b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
39380b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
39390b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
39400b57cec5SDimitry Andric   unsigned Abbrev8Bit = Stream.EmitAbbrev(std::move(Abbv));
39410b57cec5SDimitry Andric 
39420b57cec5SDimitry Andric   // 7-bit fixed width MST_ENTRY strings.
39430b57cec5SDimitry Andric   Abbv = std::make_shared<BitCodeAbbrev>();
39440b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
39450b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
39460b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
39470b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
39480b57cec5SDimitry Andric   unsigned Abbrev7Bit = Stream.EmitAbbrev(std::move(Abbv));
39490b57cec5SDimitry Andric 
39500b57cec5SDimitry Andric   // 6-bit char6 MST_ENTRY strings.
39510b57cec5SDimitry Andric   Abbv = std::make_shared<BitCodeAbbrev>();
39520b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
39530b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
39540b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
39550b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
39560b57cec5SDimitry Andric   unsigned Abbrev6Bit = Stream.EmitAbbrev(std::move(Abbv));
39570b57cec5SDimitry Andric 
39580b57cec5SDimitry Andric   // Module Hash, 160 bits SHA1. Optionally, emitted after each MST_CODE_ENTRY.
39590b57cec5SDimitry Andric   Abbv = std::make_shared<BitCodeAbbrev>();
39600b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_HASH));
39610b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
39620b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
39630b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
39640b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
39650b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
39660b57cec5SDimitry Andric   unsigned AbbrevHash = Stream.EmitAbbrev(std::move(Abbv));
39670b57cec5SDimitry Andric 
39680b57cec5SDimitry Andric   SmallVector<unsigned, 64> Vals;
39695f757f3fSDimitry Andric   forEachModule([&](const StringMapEntry<ModuleHash> &MPSE) {
39700b57cec5SDimitry Andric     StringRef Key = MPSE.getKey();
39715f757f3fSDimitry Andric     const auto &Hash = MPSE.getValue();
39720b57cec5SDimitry Andric     StringEncoding Bits = getStringEncoding(Key);
39730b57cec5SDimitry Andric     unsigned AbbrevToUse = Abbrev8Bit;
39740b57cec5SDimitry Andric     if (Bits == SE_Char6)
39750b57cec5SDimitry Andric       AbbrevToUse = Abbrev6Bit;
39760b57cec5SDimitry Andric     else if (Bits == SE_Fixed7)
39770b57cec5SDimitry Andric       AbbrevToUse = Abbrev7Bit;
39780b57cec5SDimitry Andric 
39795f757f3fSDimitry Andric     auto ModuleId = ModuleIdMap.size();
39805f757f3fSDimitry Andric     ModuleIdMap[Key] = ModuleId;
39815f757f3fSDimitry Andric     Vals.push_back(ModuleId);
39820b57cec5SDimitry Andric     Vals.append(Key.begin(), Key.end());
39830b57cec5SDimitry Andric 
39840b57cec5SDimitry Andric     // Emit the finished record.
39850b57cec5SDimitry Andric     Stream.EmitRecord(bitc::MST_CODE_ENTRY, Vals, AbbrevToUse);
39860b57cec5SDimitry Andric 
39870b57cec5SDimitry Andric     // Emit an optional hash for the module now
39880b57cec5SDimitry Andric     if (llvm::any_of(Hash, [](uint32_t H) { return H; })) {
39890b57cec5SDimitry Andric       Vals.assign(Hash.begin(), Hash.end());
39900b57cec5SDimitry Andric       // Emit the hash record.
39910b57cec5SDimitry Andric       Stream.EmitRecord(bitc::MST_CODE_HASH, Vals, AbbrevHash);
39920b57cec5SDimitry Andric     }
39930b57cec5SDimitry Andric 
39940b57cec5SDimitry Andric     Vals.clear();
39950b57cec5SDimitry Andric   });
39960b57cec5SDimitry Andric   Stream.ExitBlock();
39970b57cec5SDimitry Andric }
39980b57cec5SDimitry Andric 
39990b57cec5SDimitry Andric /// Write the function type metadata related records that need to appear before
40000b57cec5SDimitry Andric /// a function summary entry (whether per-module or combined).
4001e8d8bef9SDimitry Andric template <typename Fn>
40020b57cec5SDimitry Andric static void writeFunctionTypeMetadataRecords(BitstreamWriter &Stream,
4003e8d8bef9SDimitry Andric                                              FunctionSummary *FS,
4004e8d8bef9SDimitry Andric                                              Fn GetValueID) {
40050b57cec5SDimitry Andric   if (!FS->type_tests().empty())
40060b57cec5SDimitry Andric     Stream.EmitRecord(bitc::FS_TYPE_TESTS, FS->type_tests());
40070b57cec5SDimitry Andric 
40080b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
40090b57cec5SDimitry Andric 
40100b57cec5SDimitry Andric   auto WriteVFuncIdVec = [&](uint64_t Ty,
40110b57cec5SDimitry Andric                              ArrayRef<FunctionSummary::VFuncId> VFs) {
40120b57cec5SDimitry Andric     if (VFs.empty())
40130b57cec5SDimitry Andric       return;
40140b57cec5SDimitry Andric     Record.clear();
40150b57cec5SDimitry Andric     for (auto &VF : VFs) {
40160b57cec5SDimitry Andric       Record.push_back(VF.GUID);
40170b57cec5SDimitry Andric       Record.push_back(VF.Offset);
40180b57cec5SDimitry Andric     }
40190b57cec5SDimitry Andric     Stream.EmitRecord(Ty, Record);
40200b57cec5SDimitry Andric   };
40210b57cec5SDimitry Andric 
40220b57cec5SDimitry Andric   WriteVFuncIdVec(bitc::FS_TYPE_TEST_ASSUME_VCALLS,
40230b57cec5SDimitry Andric                   FS->type_test_assume_vcalls());
40240b57cec5SDimitry Andric   WriteVFuncIdVec(bitc::FS_TYPE_CHECKED_LOAD_VCALLS,
40250b57cec5SDimitry Andric                   FS->type_checked_load_vcalls());
40260b57cec5SDimitry Andric 
40270b57cec5SDimitry Andric   auto WriteConstVCallVec = [&](uint64_t Ty,
40280b57cec5SDimitry Andric                                 ArrayRef<FunctionSummary::ConstVCall> VCs) {
40290b57cec5SDimitry Andric     for (auto &VC : VCs) {
40300b57cec5SDimitry Andric       Record.clear();
40310b57cec5SDimitry Andric       Record.push_back(VC.VFunc.GUID);
40320b57cec5SDimitry Andric       Record.push_back(VC.VFunc.Offset);
4033e8d8bef9SDimitry Andric       llvm::append_range(Record, VC.Args);
40340b57cec5SDimitry Andric       Stream.EmitRecord(Ty, Record);
40350b57cec5SDimitry Andric     }
40360b57cec5SDimitry Andric   };
40370b57cec5SDimitry Andric 
40380b57cec5SDimitry Andric   WriteConstVCallVec(bitc::FS_TYPE_TEST_ASSUME_CONST_VCALL,
40390b57cec5SDimitry Andric                      FS->type_test_assume_const_vcalls());
40400b57cec5SDimitry Andric   WriteConstVCallVec(bitc::FS_TYPE_CHECKED_LOAD_CONST_VCALL,
40410b57cec5SDimitry Andric                      FS->type_checked_load_const_vcalls());
40425ffd83dbSDimitry Andric 
40435ffd83dbSDimitry Andric   auto WriteRange = [&](ConstantRange Range) {
40445ffd83dbSDimitry Andric     Range = Range.sextOrTrunc(FunctionSummary::ParamAccess::RangeWidth);
40455ffd83dbSDimitry Andric     assert(Range.getLower().getNumWords() == 1);
40465ffd83dbSDimitry Andric     assert(Range.getUpper().getNumWords() == 1);
40475ffd83dbSDimitry Andric     emitSignedInt64(Record, *Range.getLower().getRawData());
40485ffd83dbSDimitry Andric     emitSignedInt64(Record, *Range.getUpper().getRawData());
40495ffd83dbSDimitry Andric   };
40505ffd83dbSDimitry Andric 
40515ffd83dbSDimitry Andric   if (!FS->paramAccesses().empty()) {
40525ffd83dbSDimitry Andric     Record.clear();
40535ffd83dbSDimitry Andric     for (auto &Arg : FS->paramAccesses()) {
4054e8d8bef9SDimitry Andric       size_t UndoSize = Record.size();
40555ffd83dbSDimitry Andric       Record.push_back(Arg.ParamNo);
40565ffd83dbSDimitry Andric       WriteRange(Arg.Use);
40575ffd83dbSDimitry Andric       Record.push_back(Arg.Calls.size());
40585ffd83dbSDimitry Andric       for (auto &Call : Arg.Calls) {
40595ffd83dbSDimitry Andric         Record.push_back(Call.ParamNo);
4060bdd1243dSDimitry Andric         std::optional<unsigned> ValueID = GetValueID(Call.Callee);
4061e8d8bef9SDimitry Andric         if (!ValueID) {
4062e8d8bef9SDimitry Andric           // If ValueID is unknown we can't drop just this call, we must drop
4063e8d8bef9SDimitry Andric           // entire parameter.
4064e8d8bef9SDimitry Andric           Record.resize(UndoSize);
4065e8d8bef9SDimitry Andric           break;
4066e8d8bef9SDimitry Andric         }
4067e8d8bef9SDimitry Andric         Record.push_back(*ValueID);
40685ffd83dbSDimitry Andric         WriteRange(Call.Offsets);
40695ffd83dbSDimitry Andric       }
40705ffd83dbSDimitry Andric     }
4071e8d8bef9SDimitry Andric     if (!Record.empty())
40725ffd83dbSDimitry Andric       Stream.EmitRecord(bitc::FS_PARAM_ACCESS, Record);
40735ffd83dbSDimitry Andric   }
40740b57cec5SDimitry Andric }
40750b57cec5SDimitry Andric 
40760b57cec5SDimitry Andric /// Collect type IDs from type tests used by function.
40770b57cec5SDimitry Andric static void
40780b57cec5SDimitry Andric getReferencedTypeIds(FunctionSummary *FS,
40790b57cec5SDimitry Andric                      std::set<GlobalValue::GUID> &ReferencedTypeIds) {
40800b57cec5SDimitry Andric   if (!FS->type_tests().empty())
40810b57cec5SDimitry Andric     for (auto &TT : FS->type_tests())
40820b57cec5SDimitry Andric       ReferencedTypeIds.insert(TT);
40830b57cec5SDimitry Andric 
40840b57cec5SDimitry Andric   auto GetReferencedTypesFromVFuncIdVec =
40850b57cec5SDimitry Andric       [&](ArrayRef<FunctionSummary::VFuncId> VFs) {
40860b57cec5SDimitry Andric         for (auto &VF : VFs)
40870b57cec5SDimitry Andric           ReferencedTypeIds.insert(VF.GUID);
40880b57cec5SDimitry Andric       };
40890b57cec5SDimitry Andric 
40900b57cec5SDimitry Andric   GetReferencedTypesFromVFuncIdVec(FS->type_test_assume_vcalls());
40910b57cec5SDimitry Andric   GetReferencedTypesFromVFuncIdVec(FS->type_checked_load_vcalls());
40920b57cec5SDimitry Andric 
40930b57cec5SDimitry Andric   auto GetReferencedTypesFromConstVCallVec =
40940b57cec5SDimitry Andric       [&](ArrayRef<FunctionSummary::ConstVCall> VCs) {
40950b57cec5SDimitry Andric         for (auto &VC : VCs)
40960b57cec5SDimitry Andric           ReferencedTypeIds.insert(VC.VFunc.GUID);
40970b57cec5SDimitry Andric       };
40980b57cec5SDimitry Andric 
40990b57cec5SDimitry Andric   GetReferencedTypesFromConstVCallVec(FS->type_test_assume_const_vcalls());
41000b57cec5SDimitry Andric   GetReferencedTypesFromConstVCallVec(FS->type_checked_load_const_vcalls());
41010b57cec5SDimitry Andric }
41020b57cec5SDimitry Andric 
41030b57cec5SDimitry Andric static void writeWholeProgramDevirtResolutionByArg(
41040b57cec5SDimitry Andric     SmallVector<uint64_t, 64> &NameVals, const std::vector<uint64_t> &args,
41050b57cec5SDimitry Andric     const WholeProgramDevirtResolution::ByArg &ByArg) {
41060b57cec5SDimitry Andric   NameVals.push_back(args.size());
4107e8d8bef9SDimitry Andric   llvm::append_range(NameVals, args);
41080b57cec5SDimitry Andric 
41090b57cec5SDimitry Andric   NameVals.push_back(ByArg.TheKind);
41100b57cec5SDimitry Andric   NameVals.push_back(ByArg.Info);
41110b57cec5SDimitry Andric   NameVals.push_back(ByArg.Byte);
41120b57cec5SDimitry Andric   NameVals.push_back(ByArg.Bit);
41130b57cec5SDimitry Andric }
41140b57cec5SDimitry Andric 
41150b57cec5SDimitry Andric static void writeWholeProgramDevirtResolution(
41160b57cec5SDimitry Andric     SmallVector<uint64_t, 64> &NameVals, StringTableBuilder &StrtabBuilder,
41170b57cec5SDimitry Andric     uint64_t Id, const WholeProgramDevirtResolution &Wpd) {
41180b57cec5SDimitry Andric   NameVals.push_back(Id);
41190b57cec5SDimitry Andric 
41200b57cec5SDimitry Andric   NameVals.push_back(Wpd.TheKind);
41210b57cec5SDimitry Andric   NameVals.push_back(StrtabBuilder.add(Wpd.SingleImplName));
41220b57cec5SDimitry Andric   NameVals.push_back(Wpd.SingleImplName.size());
41230b57cec5SDimitry Andric 
41240b57cec5SDimitry Andric   NameVals.push_back(Wpd.ResByArg.size());
41250b57cec5SDimitry Andric   for (auto &A : Wpd.ResByArg)
41260b57cec5SDimitry Andric     writeWholeProgramDevirtResolutionByArg(NameVals, A.first, A.second);
41270b57cec5SDimitry Andric }
41280b57cec5SDimitry Andric 
41290b57cec5SDimitry Andric static void writeTypeIdSummaryRecord(SmallVector<uint64_t, 64> &NameVals,
41300b57cec5SDimitry Andric                                      StringTableBuilder &StrtabBuilder,
41310b57cec5SDimitry Andric                                      const std::string &Id,
41320b57cec5SDimitry Andric                                      const TypeIdSummary &Summary) {
41330b57cec5SDimitry Andric   NameVals.push_back(StrtabBuilder.add(Id));
41340b57cec5SDimitry Andric   NameVals.push_back(Id.size());
41350b57cec5SDimitry Andric 
41360b57cec5SDimitry Andric   NameVals.push_back(Summary.TTRes.TheKind);
41370b57cec5SDimitry Andric   NameVals.push_back(Summary.TTRes.SizeM1BitWidth);
41380b57cec5SDimitry Andric   NameVals.push_back(Summary.TTRes.AlignLog2);
41390b57cec5SDimitry Andric   NameVals.push_back(Summary.TTRes.SizeM1);
41400b57cec5SDimitry Andric   NameVals.push_back(Summary.TTRes.BitMask);
41410b57cec5SDimitry Andric   NameVals.push_back(Summary.TTRes.InlineBits);
41420b57cec5SDimitry Andric 
41430b57cec5SDimitry Andric   for (auto &W : Summary.WPDRes)
41440b57cec5SDimitry Andric     writeWholeProgramDevirtResolution(NameVals, StrtabBuilder, W.first,
41450b57cec5SDimitry Andric                                       W.second);
41460b57cec5SDimitry Andric }
41470b57cec5SDimitry Andric 
41480b57cec5SDimitry Andric static void writeTypeIdCompatibleVtableSummaryRecord(
41490b57cec5SDimitry Andric     SmallVector<uint64_t, 64> &NameVals, StringTableBuilder &StrtabBuilder,
41500b57cec5SDimitry Andric     const std::string &Id, const TypeIdCompatibleVtableInfo &Summary,
41510b57cec5SDimitry Andric     ValueEnumerator &VE) {
41520b57cec5SDimitry Andric   NameVals.push_back(StrtabBuilder.add(Id));
41530b57cec5SDimitry Andric   NameVals.push_back(Id.size());
41540b57cec5SDimitry Andric 
41550b57cec5SDimitry Andric   for (auto &P : Summary) {
41560b57cec5SDimitry Andric     NameVals.push_back(P.AddressPointOffset);
41570b57cec5SDimitry Andric     NameVals.push_back(VE.getValueID(P.VTableVI.getValue()));
41580b57cec5SDimitry Andric   }
41590b57cec5SDimitry Andric }
41600b57cec5SDimitry Andric 
4161bdd1243dSDimitry Andric static void writeFunctionHeapProfileRecords(
4162bdd1243dSDimitry Andric     BitstreamWriter &Stream, FunctionSummary *FS, unsigned CallsiteAbbrev,
4163bdd1243dSDimitry Andric     unsigned AllocAbbrev, bool PerModule,
4164bdd1243dSDimitry Andric     std::function<unsigned(const ValueInfo &VI)> GetValueID,
4165bdd1243dSDimitry Andric     std::function<unsigned(unsigned)> GetStackIndex) {
4166bdd1243dSDimitry Andric   SmallVector<uint64_t> Record;
4167bdd1243dSDimitry Andric 
4168bdd1243dSDimitry Andric   for (auto &CI : FS->callsites()) {
4169bdd1243dSDimitry Andric     Record.clear();
4170bdd1243dSDimitry Andric     // Per module callsite clones should always have a single entry of
4171bdd1243dSDimitry Andric     // value 0.
4172bdd1243dSDimitry Andric     assert(!PerModule || (CI.Clones.size() == 1 && CI.Clones[0] == 0));
4173bdd1243dSDimitry Andric     Record.push_back(GetValueID(CI.Callee));
4174bdd1243dSDimitry Andric     if (!PerModule) {
4175bdd1243dSDimitry Andric       Record.push_back(CI.StackIdIndices.size());
4176bdd1243dSDimitry Andric       Record.push_back(CI.Clones.size());
4177bdd1243dSDimitry Andric     }
4178bdd1243dSDimitry Andric     for (auto Id : CI.StackIdIndices)
4179bdd1243dSDimitry Andric       Record.push_back(GetStackIndex(Id));
4180bdd1243dSDimitry Andric     if (!PerModule) {
4181bdd1243dSDimitry Andric       for (auto V : CI.Clones)
4182bdd1243dSDimitry Andric         Record.push_back(V);
4183bdd1243dSDimitry Andric     }
4184bdd1243dSDimitry Andric     Stream.EmitRecord(PerModule ? bitc::FS_PERMODULE_CALLSITE_INFO
4185bdd1243dSDimitry Andric                                 : bitc::FS_COMBINED_CALLSITE_INFO,
4186bdd1243dSDimitry Andric                       Record, CallsiteAbbrev);
4187bdd1243dSDimitry Andric   }
4188bdd1243dSDimitry Andric 
4189bdd1243dSDimitry Andric   for (auto &AI : FS->allocs()) {
4190bdd1243dSDimitry Andric     Record.clear();
4191bdd1243dSDimitry Andric     // Per module alloc versions should always have a single entry of
4192bdd1243dSDimitry Andric     // value 0.
4193bdd1243dSDimitry Andric     assert(!PerModule || (AI.Versions.size() == 1 && AI.Versions[0] == 0));
4194bdd1243dSDimitry Andric     Record.push_back(AI.MIBs.size());
4195*0fca6ea1SDimitry Andric     if (!PerModule)
4196bdd1243dSDimitry Andric       Record.push_back(AI.Versions.size());
4197bdd1243dSDimitry Andric     for (auto &MIB : AI.MIBs) {
4198bdd1243dSDimitry Andric       Record.push_back((uint8_t)MIB.AllocType);
4199bdd1243dSDimitry Andric       Record.push_back(MIB.StackIdIndices.size());
4200bdd1243dSDimitry Andric       for (auto Id : MIB.StackIdIndices)
4201bdd1243dSDimitry Andric         Record.push_back(GetStackIndex(Id));
4202bdd1243dSDimitry Andric     }
4203bdd1243dSDimitry Andric     if (!PerModule) {
4204bdd1243dSDimitry Andric       for (auto V : AI.Versions)
4205bdd1243dSDimitry Andric         Record.push_back(V);
4206bdd1243dSDimitry Andric     }
4207*0fca6ea1SDimitry Andric     assert(AI.TotalSizes.empty() || AI.TotalSizes.size() == AI.MIBs.size());
4208*0fca6ea1SDimitry Andric     if (!AI.TotalSizes.empty()) {
4209*0fca6ea1SDimitry Andric       for (auto Size : AI.TotalSizes)
4210*0fca6ea1SDimitry Andric         Record.push_back(Size);
4211*0fca6ea1SDimitry Andric     }
4212bdd1243dSDimitry Andric     Stream.EmitRecord(PerModule ? bitc::FS_PERMODULE_ALLOC_INFO
4213bdd1243dSDimitry Andric                                 : bitc::FS_COMBINED_ALLOC_INFO,
4214bdd1243dSDimitry Andric                       Record, AllocAbbrev);
4215bdd1243dSDimitry Andric   }
4216bdd1243dSDimitry Andric }
4217bdd1243dSDimitry Andric 
42180b57cec5SDimitry Andric // Helper to emit a single function summary record.
42190b57cec5SDimitry Andric void ModuleBitcodeWriterBase::writePerModuleFunctionSummaryRecord(
42200b57cec5SDimitry Andric     SmallVector<uint64_t, 64> &NameVals, GlobalValueSummary *Summary,
42215f757f3fSDimitry Andric     unsigned ValueID, unsigned FSCallsRelBFAbbrev,
42225f757f3fSDimitry Andric     unsigned FSCallsProfileAbbrev, unsigned CallsiteAbbrev,
42235f757f3fSDimitry Andric     unsigned AllocAbbrev, const Function &F) {
42240b57cec5SDimitry Andric   NameVals.push_back(ValueID);
42250b57cec5SDimitry Andric 
42260b57cec5SDimitry Andric   FunctionSummary *FS = cast<FunctionSummary>(Summary);
4227e8d8bef9SDimitry Andric 
4228e8d8bef9SDimitry Andric   writeFunctionTypeMetadataRecords(
4229bdd1243dSDimitry Andric       Stream, FS, [&](const ValueInfo &VI) -> std::optional<unsigned> {
4230e8d8bef9SDimitry Andric         return {VE.getValueID(VI.getValue())};
4231e8d8bef9SDimitry Andric       });
42320b57cec5SDimitry Andric 
4233bdd1243dSDimitry Andric   writeFunctionHeapProfileRecords(
4234bdd1243dSDimitry Andric       Stream, FS, CallsiteAbbrev, AllocAbbrev,
4235bdd1243dSDimitry Andric       /*PerModule*/ true,
4236bdd1243dSDimitry Andric       /*GetValueId*/ [&](const ValueInfo &VI) { return getValueId(VI); },
4237bdd1243dSDimitry Andric       /*GetStackIndex*/ [&](unsigned I) { return I; });
4238bdd1243dSDimitry Andric 
42390b57cec5SDimitry Andric   auto SpecialRefCnts = FS->specialRefCounts();
42400b57cec5SDimitry Andric   NameVals.push_back(getEncodedGVSummaryFlags(FS->flags()));
42410b57cec5SDimitry Andric   NameVals.push_back(FS->instCount());
42420b57cec5SDimitry Andric   NameVals.push_back(getEncodedFFlags(FS->fflags()));
42430b57cec5SDimitry Andric   NameVals.push_back(FS->refs().size());
42440b57cec5SDimitry Andric   NameVals.push_back(SpecialRefCnts.first);  // rorefcnt
42450b57cec5SDimitry Andric   NameVals.push_back(SpecialRefCnts.second); // worefcnt
42460b57cec5SDimitry Andric 
42470b57cec5SDimitry Andric   for (auto &RI : FS->refs())
4248*0fca6ea1SDimitry Andric     NameVals.push_back(getValueId(RI));
42490b57cec5SDimitry Andric 
42505f757f3fSDimitry Andric   const bool UseRelBFRecord =
42515f757f3fSDimitry Andric       WriteRelBFToSummary && !F.hasProfileData() &&
42525f757f3fSDimitry Andric       ForceSummaryEdgesCold == FunctionSummary::FSHT_None;
42530b57cec5SDimitry Andric   for (auto &ECI : FS->calls()) {
42540b57cec5SDimitry Andric     NameVals.push_back(getValueId(ECI.first));
42555f757f3fSDimitry Andric     if (UseRelBFRecord)
42565f757f3fSDimitry Andric       NameVals.push_back(getEncodedRelBFCallEdgeInfo(ECI.second));
42575f757f3fSDimitry Andric     else
42585f757f3fSDimitry Andric       NameVals.push_back(getEncodedHotnessCallEdgeInfo(ECI.second));
42590b57cec5SDimitry Andric   }
42600b57cec5SDimitry Andric 
42615f757f3fSDimitry Andric   unsigned FSAbbrev =
42625f757f3fSDimitry Andric       (UseRelBFRecord ? FSCallsRelBFAbbrev : FSCallsProfileAbbrev);
42630b57cec5SDimitry Andric   unsigned Code =
42645f757f3fSDimitry Andric       (UseRelBFRecord ? bitc::FS_PERMODULE_RELBF : bitc::FS_PERMODULE_PROFILE);
42650b57cec5SDimitry Andric 
42660b57cec5SDimitry Andric   // Emit the finished record.
42670b57cec5SDimitry Andric   Stream.EmitRecord(Code, NameVals, FSAbbrev);
42680b57cec5SDimitry Andric   NameVals.clear();
42690b57cec5SDimitry Andric }
42700b57cec5SDimitry Andric 
42710b57cec5SDimitry Andric // Collect the global value references in the given variable's initializer,
42720b57cec5SDimitry Andric // and emit them in a summary record.
42730b57cec5SDimitry Andric void ModuleBitcodeWriterBase::writeModuleLevelReferences(
42740b57cec5SDimitry Andric     const GlobalVariable &V, SmallVector<uint64_t, 64> &NameVals,
42750b57cec5SDimitry Andric     unsigned FSModRefsAbbrev, unsigned FSModVTableRefsAbbrev) {
42760b57cec5SDimitry Andric   auto VI = Index->getValueInfo(V.getGUID());
42770b57cec5SDimitry Andric   if (!VI || VI.getSummaryList().empty()) {
42780b57cec5SDimitry Andric     // Only declarations should not have a summary (a declaration might however
42790b57cec5SDimitry Andric     // have a summary if the def was in module level asm).
42800b57cec5SDimitry Andric     assert(V.isDeclaration());
42810b57cec5SDimitry Andric     return;
42820b57cec5SDimitry Andric   }
42830b57cec5SDimitry Andric   auto *Summary = VI.getSummaryList()[0].get();
42840b57cec5SDimitry Andric   NameVals.push_back(VE.getValueID(&V));
42850b57cec5SDimitry Andric   GlobalVarSummary *VS = cast<GlobalVarSummary>(Summary);
42860b57cec5SDimitry Andric   NameVals.push_back(getEncodedGVSummaryFlags(VS->flags()));
42870b57cec5SDimitry Andric   NameVals.push_back(getEncodedGVarFlags(VS->varflags()));
42880b57cec5SDimitry Andric 
42890b57cec5SDimitry Andric   auto VTableFuncs = VS->vTableFuncs();
42900b57cec5SDimitry Andric   if (!VTableFuncs.empty())
42910b57cec5SDimitry Andric     NameVals.push_back(VS->refs().size());
42920b57cec5SDimitry Andric 
42930b57cec5SDimitry Andric   unsigned SizeBeforeRefs = NameVals.size();
42940b57cec5SDimitry Andric   for (auto &RI : VS->refs())
42950b57cec5SDimitry Andric     NameVals.push_back(VE.getValueID(RI.getValue()));
42960b57cec5SDimitry Andric   // Sort the refs for determinism output, the vector returned by FS->refs() has
42970b57cec5SDimitry Andric   // been initialized from a DenseSet.
4298e8d8bef9SDimitry Andric   llvm::sort(drop_begin(NameVals, SizeBeforeRefs));
42990b57cec5SDimitry Andric 
43000b57cec5SDimitry Andric   if (VTableFuncs.empty())
43010b57cec5SDimitry Andric     Stream.EmitRecord(bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS, NameVals,
43020b57cec5SDimitry Andric                       FSModRefsAbbrev);
43030b57cec5SDimitry Andric   else {
43040b57cec5SDimitry Andric     // VTableFuncs pairs should already be sorted by offset.
43050b57cec5SDimitry Andric     for (auto &P : VTableFuncs) {
43060b57cec5SDimitry Andric       NameVals.push_back(VE.getValueID(P.FuncVI.getValue()));
43070b57cec5SDimitry Andric       NameVals.push_back(P.VTableOffset);
43080b57cec5SDimitry Andric     }
43090b57cec5SDimitry Andric 
43100b57cec5SDimitry Andric     Stream.EmitRecord(bitc::FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS, NameVals,
43110b57cec5SDimitry Andric                       FSModVTableRefsAbbrev);
43120b57cec5SDimitry Andric   }
43130b57cec5SDimitry Andric   NameVals.clear();
43140b57cec5SDimitry Andric }
43150b57cec5SDimitry Andric 
43160b57cec5SDimitry Andric /// Emit the per-module summary section alongside the rest of
43170b57cec5SDimitry Andric /// the module's bitcode.
43180b57cec5SDimitry Andric void ModuleBitcodeWriterBase::writePerModuleGlobalValueSummary() {
43190b57cec5SDimitry Andric   // By default we compile with ThinLTO if the module has a summary, but the
43200b57cec5SDimitry Andric   // client can request full LTO with a module flag.
43210b57cec5SDimitry Andric   bool IsThinLTO = true;
43220b57cec5SDimitry Andric   if (auto *MD =
43230b57cec5SDimitry Andric           mdconst::extract_or_null<ConstantInt>(M.getModuleFlag("ThinLTO")))
43240b57cec5SDimitry Andric     IsThinLTO = MD->getZExtValue();
43250b57cec5SDimitry Andric   Stream.EnterSubblock(IsThinLTO ? bitc::GLOBALVAL_SUMMARY_BLOCK_ID
43260b57cec5SDimitry Andric                                  : bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID,
43270b57cec5SDimitry Andric                        4);
43280b57cec5SDimitry Andric 
4329480093f4SDimitry Andric   Stream.EmitRecord(
4330480093f4SDimitry Andric       bitc::FS_VERSION,
4331480093f4SDimitry Andric       ArrayRef<uint64_t>{ModuleSummaryIndex::BitcodeSummaryVersion});
43320b57cec5SDimitry Andric 
43330b57cec5SDimitry Andric   // Write the index flags.
43340b57cec5SDimitry Andric   uint64_t Flags = 0;
43350b57cec5SDimitry Andric   // Bits 1-3 are set only in the combined index, skip them.
43360b57cec5SDimitry Andric   if (Index->enableSplitLTOUnit())
43370b57cec5SDimitry Andric     Flags |= 0x8;
433806c3fb27SDimitry Andric   if (Index->hasUnifiedLTO())
433906c3fb27SDimitry Andric     Flags |= 0x200;
434006c3fb27SDimitry Andric 
43410b57cec5SDimitry Andric   Stream.EmitRecord(bitc::FS_FLAGS, ArrayRef<uint64_t>{Flags});
43420b57cec5SDimitry Andric 
43430b57cec5SDimitry Andric   if (Index->begin() == Index->end()) {
43440b57cec5SDimitry Andric     Stream.ExitBlock();
43450b57cec5SDimitry Andric     return;
43460b57cec5SDimitry Andric   }
43470b57cec5SDimitry Andric 
43480b57cec5SDimitry Andric   for (const auto &GVI : valueIds()) {
43490b57cec5SDimitry Andric     Stream.EmitRecord(bitc::FS_VALUE_GUID,
43500b57cec5SDimitry Andric                       ArrayRef<uint64_t>{GVI.second, GVI.first});
43510b57cec5SDimitry Andric   }
43520b57cec5SDimitry Andric 
4353bdd1243dSDimitry Andric   if (!Index->stackIds().empty()) {
4354bdd1243dSDimitry Andric     auto StackIdAbbv = std::make_shared<BitCodeAbbrev>();
4355bdd1243dSDimitry Andric     StackIdAbbv->Add(BitCodeAbbrevOp(bitc::FS_STACK_IDS));
4356bdd1243dSDimitry Andric     // numids x stackid
4357bdd1243dSDimitry Andric     StackIdAbbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4358bdd1243dSDimitry Andric     StackIdAbbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4359bdd1243dSDimitry Andric     unsigned StackIdAbbvId = Stream.EmitAbbrev(std::move(StackIdAbbv));
4360bdd1243dSDimitry Andric     Stream.EmitRecord(bitc::FS_STACK_IDS, Index->stackIds(), StackIdAbbvId);
4361bdd1243dSDimitry Andric   }
4362bdd1243dSDimitry Andric 
43630b57cec5SDimitry Andric   // Abbrev for FS_PERMODULE_PROFILE.
43640b57cec5SDimitry Andric   auto Abbv = std::make_shared<BitCodeAbbrev>();
43650b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_PROFILE));
43660b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // valueid
436706c3fb27SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // flags
43680b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // instcount
43690b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // fflags
43700b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // numrefs
43710b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // rorefcnt
43720b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // worefcnt
43735f757f3fSDimitry Andric   // numrefs x valueid, n x (valueid, hotness+tailcall flags)
43740b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
43750b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
43760b57cec5SDimitry Andric   unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(std::move(Abbv));
43770b57cec5SDimitry Andric 
43785f757f3fSDimitry Andric   // Abbrev for FS_PERMODULE_RELBF.
43790b57cec5SDimitry Andric   Abbv = std::make_shared<BitCodeAbbrev>();
43800b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_RELBF));
43810b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // valueid
43820b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // flags
43830b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // instcount
43840b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // fflags
43850b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // numrefs
43860b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // rorefcnt
43870b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // worefcnt
43885f757f3fSDimitry Andric   // numrefs x valueid, n x (valueid, rel_block_freq+tailcall])
43890b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
43900b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
43915f757f3fSDimitry Andric   unsigned FSCallsRelBFAbbrev = Stream.EmitAbbrev(std::move(Abbv));
43920b57cec5SDimitry Andric 
43930b57cec5SDimitry Andric   // Abbrev for FS_PERMODULE_GLOBALVAR_INIT_REFS.
43940b57cec5SDimitry Andric   Abbv = std::make_shared<BitCodeAbbrev>();
43950b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS));
43960b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
43970b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
43980b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));  // valueids
43990b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
44000b57cec5SDimitry Andric   unsigned FSModRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
44010b57cec5SDimitry Andric 
44020b57cec5SDimitry Andric   // Abbrev for FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS.
44030b57cec5SDimitry Andric   Abbv = std::make_shared<BitCodeAbbrev>();
44040b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS));
44050b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
44060b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
44070b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
44080b57cec5SDimitry Andric   // numrefs x valueid, n x (valueid , offset)
44090b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
44100b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
44110b57cec5SDimitry Andric   unsigned FSModVTableRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
44120b57cec5SDimitry Andric 
44130b57cec5SDimitry Andric   // Abbrev for FS_ALIAS.
44140b57cec5SDimitry Andric   Abbv = std::make_shared<BitCodeAbbrev>();
44150b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::FS_ALIAS));
44160b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // valueid
44170b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // flags
44180b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // valueid
44190b57cec5SDimitry Andric   unsigned FSAliasAbbrev = Stream.EmitAbbrev(std::move(Abbv));
44200b57cec5SDimitry Andric 
44210b57cec5SDimitry Andric   // Abbrev for FS_TYPE_ID_METADATA
44220b57cec5SDimitry Andric   Abbv = std::make_shared<BitCodeAbbrev>();
44230b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::FS_TYPE_ID_METADATA));
44240b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // typeid strtab index
44250b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // typeid length
44260b57cec5SDimitry Andric   // n x (valueid , offset)
44270b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
44280b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
44290b57cec5SDimitry Andric   unsigned TypeIdCompatibleVtableAbbrev = Stream.EmitAbbrev(std::move(Abbv));
44300b57cec5SDimitry Andric 
4431bdd1243dSDimitry Andric   Abbv = std::make_shared<BitCodeAbbrev>();
4432bdd1243dSDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_CALLSITE_INFO));
4433bdd1243dSDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4434bdd1243dSDimitry Andric   // n x stackidindex
4435bdd1243dSDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4436bdd1243dSDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4437bdd1243dSDimitry Andric   unsigned CallsiteAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4438bdd1243dSDimitry Andric 
4439bdd1243dSDimitry Andric   Abbv = std::make_shared<BitCodeAbbrev>();
4440bdd1243dSDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_ALLOC_INFO));
4441*0fca6ea1SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // nummib
4442bdd1243dSDimitry Andric   // n x (alloc type, numstackids, numstackids x stackidindex)
4443*0fca6ea1SDimitry Andric   // optional: nummib x total size
4444bdd1243dSDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4445bdd1243dSDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4446bdd1243dSDimitry Andric   unsigned AllocAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4447bdd1243dSDimitry Andric 
44480b57cec5SDimitry Andric   SmallVector<uint64_t, 64> NameVals;
44490b57cec5SDimitry Andric   // Iterate over the list of functions instead of the Index to
44500b57cec5SDimitry Andric   // ensure the ordering is stable.
44510b57cec5SDimitry Andric   for (const Function &F : M) {
44520b57cec5SDimitry Andric     // Summary emission does not support anonymous functions, they have to
44530b57cec5SDimitry Andric     // renamed using the anonymous function renaming pass.
44540b57cec5SDimitry Andric     if (!F.hasName())
44550b57cec5SDimitry Andric       report_fatal_error("Unexpected anonymous function when writing summary");
44560b57cec5SDimitry Andric 
44570b57cec5SDimitry Andric     ValueInfo VI = Index->getValueInfo(F.getGUID());
44580b57cec5SDimitry Andric     if (!VI || VI.getSummaryList().empty()) {
44590b57cec5SDimitry Andric       // Only declarations should not have a summary (a declaration might
44600b57cec5SDimitry Andric       // however have a summary if the def was in module level asm).
44610b57cec5SDimitry Andric       assert(F.isDeclaration());
44620b57cec5SDimitry Andric       continue;
44630b57cec5SDimitry Andric     }
44640b57cec5SDimitry Andric     auto *Summary = VI.getSummaryList()[0].get();
44655f757f3fSDimitry Andric     writePerModuleFunctionSummaryRecord(
44665f757f3fSDimitry Andric         NameVals, Summary, VE.getValueID(&F), FSCallsRelBFAbbrev,
44675f757f3fSDimitry Andric         FSCallsProfileAbbrev, CallsiteAbbrev, AllocAbbrev, F);
44680b57cec5SDimitry Andric   }
44690b57cec5SDimitry Andric 
44700b57cec5SDimitry Andric   // Capture references from GlobalVariable initializers, which are outside
44710b57cec5SDimitry Andric   // of a function scope.
44720b57cec5SDimitry Andric   for (const GlobalVariable &G : M.globals())
44730b57cec5SDimitry Andric     writeModuleLevelReferences(G, NameVals, FSModRefsAbbrev,
44740b57cec5SDimitry Andric                                FSModVTableRefsAbbrev);
44750b57cec5SDimitry Andric 
44760b57cec5SDimitry Andric   for (const GlobalAlias &A : M.aliases()) {
4477349cc55cSDimitry Andric     auto *Aliasee = A.getAliaseeObject();
4478fcaf7f86SDimitry Andric     // Skip ifunc and nameless functions which don't have an entry in the
4479fcaf7f86SDimitry Andric     // summary.
4480fcaf7f86SDimitry Andric     if (!Aliasee->hasName() || isa<GlobalIFunc>(Aliasee))
44810b57cec5SDimitry Andric       continue;
44820b57cec5SDimitry Andric     auto AliasId = VE.getValueID(&A);
44830b57cec5SDimitry Andric     auto AliaseeId = VE.getValueID(Aliasee);
44840b57cec5SDimitry Andric     NameVals.push_back(AliasId);
44850b57cec5SDimitry Andric     auto *Summary = Index->getGlobalValueSummary(A);
44860b57cec5SDimitry Andric     AliasSummary *AS = cast<AliasSummary>(Summary);
44870b57cec5SDimitry Andric     NameVals.push_back(getEncodedGVSummaryFlags(AS->flags()));
44880b57cec5SDimitry Andric     NameVals.push_back(AliaseeId);
44890b57cec5SDimitry Andric     Stream.EmitRecord(bitc::FS_ALIAS, NameVals, FSAliasAbbrev);
44900b57cec5SDimitry Andric     NameVals.clear();
44910b57cec5SDimitry Andric   }
44920b57cec5SDimitry Andric 
44930b57cec5SDimitry Andric   for (auto &S : Index->typeIdCompatibleVtableMap()) {
44940b57cec5SDimitry Andric     writeTypeIdCompatibleVtableSummaryRecord(NameVals, StrtabBuilder, S.first,
44950b57cec5SDimitry Andric                                              S.second, VE);
44960b57cec5SDimitry Andric     Stream.EmitRecord(bitc::FS_TYPE_ID_METADATA, NameVals,
44970b57cec5SDimitry Andric                       TypeIdCompatibleVtableAbbrev);
44980b57cec5SDimitry Andric     NameVals.clear();
44990b57cec5SDimitry Andric   }
45000b57cec5SDimitry Andric 
450106c3fb27SDimitry Andric   if (Index->getBlockCount())
45025ffd83dbSDimitry Andric     Stream.EmitRecord(bitc::FS_BLOCK_COUNT,
45035ffd83dbSDimitry Andric                       ArrayRef<uint64_t>{Index->getBlockCount()});
45045ffd83dbSDimitry Andric 
45050b57cec5SDimitry Andric   Stream.ExitBlock();
45060b57cec5SDimitry Andric }
45070b57cec5SDimitry Andric 
45080b57cec5SDimitry Andric /// Emit the combined summary section into the combined index file.
45090b57cec5SDimitry Andric void IndexBitcodeWriter::writeCombinedGlobalValueSummary() {
4510bdd1243dSDimitry Andric   Stream.EnterSubblock(bitc::GLOBALVAL_SUMMARY_BLOCK_ID, 4);
4511480093f4SDimitry Andric   Stream.EmitRecord(
4512480093f4SDimitry Andric       bitc::FS_VERSION,
4513480093f4SDimitry Andric       ArrayRef<uint64_t>{ModuleSummaryIndex::BitcodeSummaryVersion});
45140b57cec5SDimitry Andric 
45150b57cec5SDimitry Andric   // Write the index flags.
45165ffd83dbSDimitry Andric   Stream.EmitRecord(bitc::FS_FLAGS, ArrayRef<uint64_t>{Index.getFlags()});
45170b57cec5SDimitry Andric 
45180b57cec5SDimitry Andric   for (const auto &GVI : valueIds()) {
45190b57cec5SDimitry Andric     Stream.EmitRecord(bitc::FS_VALUE_GUID,
45200b57cec5SDimitry Andric                       ArrayRef<uint64_t>{GVI.second, GVI.first});
45210b57cec5SDimitry Andric   }
45220b57cec5SDimitry Andric 
4523*0fca6ea1SDimitry Andric   // Write the stack ids used by this index, which will be a subset of those in
4524*0fca6ea1SDimitry Andric   // the full index in the case of distributed indexes.
4525*0fca6ea1SDimitry Andric   if (!StackIds.empty()) {
4526bdd1243dSDimitry Andric     auto StackIdAbbv = std::make_shared<BitCodeAbbrev>();
4527bdd1243dSDimitry Andric     StackIdAbbv->Add(BitCodeAbbrevOp(bitc::FS_STACK_IDS));
4528bdd1243dSDimitry Andric     // numids x stackid
4529bdd1243dSDimitry Andric     StackIdAbbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4530bdd1243dSDimitry Andric     StackIdAbbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4531bdd1243dSDimitry Andric     unsigned StackIdAbbvId = Stream.EmitAbbrev(std::move(StackIdAbbv));
4532bdd1243dSDimitry Andric     Stream.EmitRecord(bitc::FS_STACK_IDS, StackIds, StackIdAbbvId);
4533bdd1243dSDimitry Andric   }
4534bdd1243dSDimitry Andric 
45350b57cec5SDimitry Andric   // Abbrev for FS_COMBINED_PROFILE.
45365f757f3fSDimitry Andric   auto Abbv = std::make_shared<BitCodeAbbrev>();
45370b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_PROFILE));
45380b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // valueid
45390b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // modid
45400b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // flags
45410b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // instcount
45420b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // fflags
45430b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // entrycount
45440b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // numrefs
45450b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // rorefcnt
45460b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // worefcnt
45475f757f3fSDimitry Andric   // numrefs x valueid, n x (valueid, hotness+tailcall flags)
45480b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
45490b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
45500b57cec5SDimitry Andric   unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(std::move(Abbv));
45510b57cec5SDimitry Andric 
45520b57cec5SDimitry Andric   // Abbrev for FS_COMBINED_GLOBALVAR_INIT_REFS.
45530b57cec5SDimitry Andric   Abbv = std::make_shared<BitCodeAbbrev>();
45540b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_GLOBALVAR_INIT_REFS));
45550b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // valueid
45560b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // modid
45570b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // flags
45580b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));    // valueids
45590b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
45600b57cec5SDimitry Andric   unsigned FSModRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
45610b57cec5SDimitry Andric 
45620b57cec5SDimitry Andric   // Abbrev for FS_COMBINED_ALIAS.
45630b57cec5SDimitry Andric   Abbv = std::make_shared<BitCodeAbbrev>();
45640b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_ALIAS));
45650b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // valueid
45660b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // modid
45670b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // flags
45680b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // valueid
45690b57cec5SDimitry Andric   unsigned FSAliasAbbrev = Stream.EmitAbbrev(std::move(Abbv));
45700b57cec5SDimitry Andric 
4571bdd1243dSDimitry Andric   Abbv = std::make_shared<BitCodeAbbrev>();
4572bdd1243dSDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_CALLSITE_INFO));
4573bdd1243dSDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4574bdd1243dSDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numstackindices
4575bdd1243dSDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numver
4576bdd1243dSDimitry Andric   // numstackindices x stackidindex, numver x version
4577bdd1243dSDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4578bdd1243dSDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4579bdd1243dSDimitry Andric   unsigned CallsiteAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4580bdd1243dSDimitry Andric 
4581bdd1243dSDimitry Andric   Abbv = std::make_shared<BitCodeAbbrev>();
4582bdd1243dSDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_ALLOC_INFO));
4583bdd1243dSDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // nummib
4584bdd1243dSDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numver
4585bdd1243dSDimitry Andric   // nummib x (alloc type, numstackids, numstackids x stackidindex),
4586bdd1243dSDimitry Andric   // numver x version
4587*0fca6ea1SDimitry Andric   // optional: nummib x total size
4588bdd1243dSDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4589bdd1243dSDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4590bdd1243dSDimitry Andric   unsigned AllocAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4591bdd1243dSDimitry Andric 
4592*0fca6ea1SDimitry Andric   auto shouldImportValueAsDecl = [&](GlobalValueSummary *GVS) -> bool {
4593*0fca6ea1SDimitry Andric     if (DecSummaries == nullptr)
4594*0fca6ea1SDimitry Andric       return false;
4595*0fca6ea1SDimitry Andric     return DecSummaries->count(GVS);
4596*0fca6ea1SDimitry Andric   };
4597*0fca6ea1SDimitry Andric 
45980b57cec5SDimitry Andric   // The aliases are emitted as a post-pass, and will point to the value
45990b57cec5SDimitry Andric   // id of the aliasee. Save them in a vector for post-processing.
46000b57cec5SDimitry Andric   SmallVector<AliasSummary *, 64> Aliases;
46010b57cec5SDimitry Andric 
46020b57cec5SDimitry Andric   // Save the value id for each summary for alias emission.
46030b57cec5SDimitry Andric   DenseMap<const GlobalValueSummary *, unsigned> SummaryToValueIdMap;
46040b57cec5SDimitry Andric 
46050b57cec5SDimitry Andric   SmallVector<uint64_t, 64> NameVals;
46060b57cec5SDimitry Andric 
46070b57cec5SDimitry Andric   // Set that will be populated during call to writeFunctionTypeMetadataRecords
46080b57cec5SDimitry Andric   // with the type ids referenced by this index file.
46090b57cec5SDimitry Andric   std::set<GlobalValue::GUID> ReferencedTypeIds;
46100b57cec5SDimitry Andric 
46110b57cec5SDimitry Andric   // For local linkage, we also emit the original name separately
46120b57cec5SDimitry Andric   // immediately after the record.
46130b57cec5SDimitry Andric   auto MaybeEmitOriginalName = [&](GlobalValueSummary &S) {
4614349cc55cSDimitry Andric     // We don't need to emit the original name if we are writing the index for
4615349cc55cSDimitry Andric     // distributed backends (in which case ModuleToSummariesForIndex is
4616349cc55cSDimitry Andric     // non-null). The original name is only needed during the thin link, since
4617349cc55cSDimitry Andric     // for SamplePGO the indirect call targets for local functions have
4618349cc55cSDimitry Andric     // have the original name annotated in profile.
4619349cc55cSDimitry Andric     // Continue to emit it when writing out the entire combined index, which is
4620349cc55cSDimitry Andric     // used in testing the thin link via llvm-lto.
4621349cc55cSDimitry Andric     if (ModuleToSummariesForIndex || !GlobalValue::isLocalLinkage(S.linkage()))
46220b57cec5SDimitry Andric       return;
46230b57cec5SDimitry Andric     NameVals.push_back(S.getOriginalName());
46240b57cec5SDimitry Andric     Stream.EmitRecord(bitc::FS_COMBINED_ORIGINAL_NAME, NameVals);
46250b57cec5SDimitry Andric     NameVals.clear();
46260b57cec5SDimitry Andric   };
46270b57cec5SDimitry Andric 
46280b57cec5SDimitry Andric   std::set<GlobalValue::GUID> DefOrUseGUIDs;
46290b57cec5SDimitry Andric   forEachSummary([&](GVInfo I, bool IsAliasee) {
46300b57cec5SDimitry Andric     GlobalValueSummary *S = I.second;
46310b57cec5SDimitry Andric     assert(S);
46320b57cec5SDimitry Andric     DefOrUseGUIDs.insert(I.first);
46330b57cec5SDimitry Andric     for (const ValueInfo &VI : S->refs())
46340b57cec5SDimitry Andric       DefOrUseGUIDs.insert(VI.getGUID());
46350b57cec5SDimitry Andric 
46360b57cec5SDimitry Andric     auto ValueId = getValueId(I.first);
46370b57cec5SDimitry Andric     assert(ValueId);
46380b57cec5SDimitry Andric     SummaryToValueIdMap[S] = *ValueId;
46390b57cec5SDimitry Andric 
46400b57cec5SDimitry Andric     // If this is invoked for an aliasee, we want to record the above
46410b57cec5SDimitry Andric     // mapping, but then not emit a summary entry (if the aliasee is
46420b57cec5SDimitry Andric     // to be imported, we will invoke this separately with IsAliasee=false).
46430b57cec5SDimitry Andric     if (IsAliasee)
46440b57cec5SDimitry Andric       return;
46450b57cec5SDimitry Andric 
46460b57cec5SDimitry Andric     if (auto *AS = dyn_cast<AliasSummary>(S)) {
46470b57cec5SDimitry Andric       // Will process aliases as a post-pass because the reader wants all
46480b57cec5SDimitry Andric       // global to be loaded first.
46490b57cec5SDimitry Andric       Aliases.push_back(AS);
46500b57cec5SDimitry Andric       return;
46510b57cec5SDimitry Andric     }
46520b57cec5SDimitry Andric 
46530b57cec5SDimitry Andric     if (auto *VS = dyn_cast<GlobalVarSummary>(S)) {
46540b57cec5SDimitry Andric       NameVals.push_back(*ValueId);
46555f757f3fSDimitry Andric       assert(ModuleIdMap.count(VS->modulePath()));
46565f757f3fSDimitry Andric       NameVals.push_back(ModuleIdMap[VS->modulePath()]);
46570b57cec5SDimitry Andric       NameVals.push_back(getEncodedGVSummaryFlags(VS->flags()));
46580b57cec5SDimitry Andric       NameVals.push_back(getEncodedGVarFlags(VS->varflags()));
46590b57cec5SDimitry Andric       for (auto &RI : VS->refs()) {
46600b57cec5SDimitry Andric         auto RefValueId = getValueId(RI.getGUID());
46610b57cec5SDimitry Andric         if (!RefValueId)
46620b57cec5SDimitry Andric           continue;
46630b57cec5SDimitry Andric         NameVals.push_back(*RefValueId);
46640b57cec5SDimitry Andric       }
46650b57cec5SDimitry Andric 
46660b57cec5SDimitry Andric       // Emit the finished record.
46670b57cec5SDimitry Andric       Stream.EmitRecord(bitc::FS_COMBINED_GLOBALVAR_INIT_REFS, NameVals,
46680b57cec5SDimitry Andric                         FSModRefsAbbrev);
46690b57cec5SDimitry Andric       NameVals.clear();
46700b57cec5SDimitry Andric       MaybeEmitOriginalName(*S);
46710b57cec5SDimitry Andric       return;
46720b57cec5SDimitry Andric     }
46730b57cec5SDimitry Andric 
4674bdd1243dSDimitry Andric     auto GetValueId = [&](const ValueInfo &VI) -> std::optional<unsigned> {
4675bdd1243dSDimitry Andric       if (!VI)
4676bdd1243dSDimitry Andric         return std::nullopt;
4677349cc55cSDimitry Andric       return getValueId(VI.getGUID());
4678e8d8bef9SDimitry Andric     };
4679e8d8bef9SDimitry Andric 
46800b57cec5SDimitry Andric     auto *FS = cast<FunctionSummary>(S);
4681e8d8bef9SDimitry Andric     writeFunctionTypeMetadataRecords(Stream, FS, GetValueId);
46820b57cec5SDimitry Andric     getReferencedTypeIds(FS, ReferencedTypeIds);
46830b57cec5SDimitry Andric 
4684bdd1243dSDimitry Andric     writeFunctionHeapProfileRecords(
4685bdd1243dSDimitry Andric         Stream, FS, CallsiteAbbrev, AllocAbbrev,
4686bdd1243dSDimitry Andric         /*PerModule*/ false,
4687*0fca6ea1SDimitry Andric         /*GetValueId*/
4688*0fca6ea1SDimitry Andric         [&](const ValueInfo &VI) -> unsigned {
4689bdd1243dSDimitry Andric           std::optional<unsigned> ValueID = GetValueId(VI);
4690bdd1243dSDimitry Andric           // This can happen in shared index files for distributed ThinLTO if
4691bdd1243dSDimitry Andric           // the callee function summary is not included. Record 0 which we
4692bdd1243dSDimitry Andric           // will have to deal with conservatively when doing any kind of
4693bdd1243dSDimitry Andric           // validation in the ThinLTO backends.
4694bdd1243dSDimitry Andric           if (!ValueID)
4695bdd1243dSDimitry Andric             return 0;
4696bdd1243dSDimitry Andric           return *ValueID;
4697bdd1243dSDimitry Andric         },
4698*0fca6ea1SDimitry Andric         /*GetStackIndex*/
4699*0fca6ea1SDimitry Andric         [&](unsigned I) {
4700*0fca6ea1SDimitry Andric           // Get the corresponding index into the list of StackIds actually
4701*0fca6ea1SDimitry Andric           // being written for this combined index (which may be a subset in
4702*0fca6ea1SDimitry Andric           // the case of distributed indexes).
4703*0fca6ea1SDimitry Andric           assert(StackIdIndicesToIndex.contains(I));
4704*0fca6ea1SDimitry Andric           return StackIdIndicesToIndex[I];
4705bdd1243dSDimitry Andric         });
4706bdd1243dSDimitry Andric 
47070b57cec5SDimitry Andric     NameVals.push_back(*ValueId);
47085f757f3fSDimitry Andric     assert(ModuleIdMap.count(FS->modulePath()));
47095f757f3fSDimitry Andric     NameVals.push_back(ModuleIdMap[FS->modulePath()]);
4710*0fca6ea1SDimitry Andric     NameVals.push_back(
4711*0fca6ea1SDimitry Andric         getEncodedGVSummaryFlags(FS->flags(), shouldImportValueAsDecl(FS)));
47120b57cec5SDimitry Andric     NameVals.push_back(FS->instCount());
47130b57cec5SDimitry Andric     NameVals.push_back(getEncodedFFlags(FS->fflags()));
47140b57cec5SDimitry Andric     NameVals.push_back(FS->entryCount());
47150b57cec5SDimitry Andric 
47160b57cec5SDimitry Andric     // Fill in below
47170b57cec5SDimitry Andric     NameVals.push_back(0); // numrefs
47180b57cec5SDimitry Andric     NameVals.push_back(0); // rorefcnt
47190b57cec5SDimitry Andric     NameVals.push_back(0); // worefcnt
47200b57cec5SDimitry Andric 
47210b57cec5SDimitry Andric     unsigned Count = 0, RORefCnt = 0, WORefCnt = 0;
47220b57cec5SDimitry Andric     for (auto &RI : FS->refs()) {
47230b57cec5SDimitry Andric       auto RefValueId = getValueId(RI.getGUID());
47240b57cec5SDimitry Andric       if (!RefValueId)
47250b57cec5SDimitry Andric         continue;
47260b57cec5SDimitry Andric       NameVals.push_back(*RefValueId);
47270b57cec5SDimitry Andric       if (RI.isReadOnly())
47280b57cec5SDimitry Andric         RORefCnt++;
47290b57cec5SDimitry Andric       else if (RI.isWriteOnly())
47300b57cec5SDimitry Andric         WORefCnt++;
47310b57cec5SDimitry Andric       Count++;
47320b57cec5SDimitry Andric     }
47330b57cec5SDimitry Andric     NameVals[6] = Count;
47340b57cec5SDimitry Andric     NameVals[7] = RORefCnt;
47350b57cec5SDimitry Andric     NameVals[8] = WORefCnt;
47360b57cec5SDimitry Andric 
47370b57cec5SDimitry Andric     for (auto &EI : FS->calls()) {
47380b57cec5SDimitry Andric       // If this GUID doesn't have a value id, it doesn't have a function
47390b57cec5SDimitry Andric       // summary and we don't need to record any calls to it.
4740bdd1243dSDimitry Andric       std::optional<unsigned> CallValueId = GetValueId(EI.first);
47410b57cec5SDimitry Andric       if (!CallValueId)
47420b57cec5SDimitry Andric         continue;
47430b57cec5SDimitry Andric       NameVals.push_back(*CallValueId);
47445f757f3fSDimitry Andric       NameVals.push_back(getEncodedHotnessCallEdgeInfo(EI.second));
47450b57cec5SDimitry Andric     }
47460b57cec5SDimitry Andric 
47470b57cec5SDimitry Andric     // Emit the finished record.
47485f757f3fSDimitry Andric     Stream.EmitRecord(bitc::FS_COMBINED_PROFILE, NameVals,
47495f757f3fSDimitry Andric                       FSCallsProfileAbbrev);
47500b57cec5SDimitry Andric     NameVals.clear();
47510b57cec5SDimitry Andric     MaybeEmitOriginalName(*S);
47520b57cec5SDimitry Andric   });
47530b57cec5SDimitry Andric 
47540b57cec5SDimitry Andric   for (auto *AS : Aliases) {
47550b57cec5SDimitry Andric     auto AliasValueId = SummaryToValueIdMap[AS];
47560b57cec5SDimitry Andric     assert(AliasValueId);
47570b57cec5SDimitry Andric     NameVals.push_back(AliasValueId);
47585f757f3fSDimitry Andric     assert(ModuleIdMap.count(AS->modulePath()));
47595f757f3fSDimitry Andric     NameVals.push_back(ModuleIdMap[AS->modulePath()]);
4760*0fca6ea1SDimitry Andric     NameVals.push_back(
4761*0fca6ea1SDimitry Andric         getEncodedGVSummaryFlags(AS->flags(), shouldImportValueAsDecl(AS)));
47620b57cec5SDimitry Andric     auto AliaseeValueId = SummaryToValueIdMap[&AS->getAliasee()];
47630b57cec5SDimitry Andric     assert(AliaseeValueId);
47640b57cec5SDimitry Andric     NameVals.push_back(AliaseeValueId);
47650b57cec5SDimitry Andric 
47660b57cec5SDimitry Andric     // Emit the finished record.
47670b57cec5SDimitry Andric     Stream.EmitRecord(bitc::FS_COMBINED_ALIAS, NameVals, FSAliasAbbrev);
47680b57cec5SDimitry Andric     NameVals.clear();
47690b57cec5SDimitry Andric     MaybeEmitOriginalName(*AS);
47700b57cec5SDimitry Andric 
47710b57cec5SDimitry Andric     if (auto *FS = dyn_cast<FunctionSummary>(&AS->getAliasee()))
47720b57cec5SDimitry Andric       getReferencedTypeIds(FS, ReferencedTypeIds);
47730b57cec5SDimitry Andric   }
47740b57cec5SDimitry Andric 
47750b57cec5SDimitry Andric   if (!Index.cfiFunctionDefs().empty()) {
47760b57cec5SDimitry Andric     for (auto &S : Index.cfiFunctionDefs()) {
47770b57cec5SDimitry Andric       if (DefOrUseGUIDs.count(
47780b57cec5SDimitry Andric               GlobalValue::getGUID(GlobalValue::dropLLVMManglingEscape(S)))) {
47790b57cec5SDimitry Andric         NameVals.push_back(StrtabBuilder.add(S));
47800b57cec5SDimitry Andric         NameVals.push_back(S.size());
47810b57cec5SDimitry Andric       }
47820b57cec5SDimitry Andric     }
47830b57cec5SDimitry Andric     if (!NameVals.empty()) {
47840b57cec5SDimitry Andric       Stream.EmitRecord(bitc::FS_CFI_FUNCTION_DEFS, NameVals);
47850b57cec5SDimitry Andric       NameVals.clear();
47860b57cec5SDimitry Andric     }
47870b57cec5SDimitry Andric   }
47880b57cec5SDimitry Andric 
47890b57cec5SDimitry Andric   if (!Index.cfiFunctionDecls().empty()) {
47900b57cec5SDimitry Andric     for (auto &S : Index.cfiFunctionDecls()) {
47910b57cec5SDimitry Andric       if (DefOrUseGUIDs.count(
47920b57cec5SDimitry Andric               GlobalValue::getGUID(GlobalValue::dropLLVMManglingEscape(S)))) {
47930b57cec5SDimitry Andric         NameVals.push_back(StrtabBuilder.add(S));
47940b57cec5SDimitry Andric         NameVals.push_back(S.size());
47950b57cec5SDimitry Andric       }
47960b57cec5SDimitry Andric     }
47970b57cec5SDimitry Andric     if (!NameVals.empty()) {
47980b57cec5SDimitry Andric       Stream.EmitRecord(bitc::FS_CFI_FUNCTION_DECLS, NameVals);
47990b57cec5SDimitry Andric       NameVals.clear();
48000b57cec5SDimitry Andric     }
48010b57cec5SDimitry Andric   }
48020b57cec5SDimitry Andric 
48030b57cec5SDimitry Andric   // Walk the GUIDs that were referenced, and write the
48040b57cec5SDimitry Andric   // corresponding type id records.
48050b57cec5SDimitry Andric   for (auto &T : ReferencedTypeIds) {
48060b57cec5SDimitry Andric     auto TidIter = Index.typeIds().equal_range(T);
48070b57cec5SDimitry Andric     for (auto It = TidIter.first; It != TidIter.second; ++It) {
48080b57cec5SDimitry Andric       writeTypeIdSummaryRecord(NameVals, StrtabBuilder, It->second.first,
48090b57cec5SDimitry Andric                                It->second.second);
48100b57cec5SDimitry Andric       Stream.EmitRecord(bitc::FS_TYPE_ID, NameVals);
48110b57cec5SDimitry Andric       NameVals.clear();
48120b57cec5SDimitry Andric     }
48130b57cec5SDimitry Andric   }
48140b57cec5SDimitry Andric 
481506c3fb27SDimitry Andric   if (Index.getBlockCount())
48165ffd83dbSDimitry Andric     Stream.EmitRecord(bitc::FS_BLOCK_COUNT,
48175ffd83dbSDimitry Andric                       ArrayRef<uint64_t>{Index.getBlockCount()});
48185ffd83dbSDimitry Andric 
48190b57cec5SDimitry Andric   Stream.ExitBlock();
48200b57cec5SDimitry Andric }
48210b57cec5SDimitry Andric 
48220b57cec5SDimitry Andric /// Create the "IDENTIFICATION_BLOCK_ID" containing a single string with the
48230b57cec5SDimitry Andric /// current llvm version, and a record for the epoch number.
48240b57cec5SDimitry Andric static void writeIdentificationBlock(BitstreamWriter &Stream) {
48250b57cec5SDimitry Andric   Stream.EnterSubblock(bitc::IDENTIFICATION_BLOCK_ID, 5);
48260b57cec5SDimitry Andric 
48270b57cec5SDimitry Andric   // Write the "user readable" string identifying the bitcode producer
48280b57cec5SDimitry Andric   auto Abbv = std::make_shared<BitCodeAbbrev>();
48290b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::IDENTIFICATION_CODE_STRING));
48300b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
48310b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
48320b57cec5SDimitry Andric   auto StringAbbrev = Stream.EmitAbbrev(std::move(Abbv));
48330b57cec5SDimitry Andric   writeStringRecord(Stream, bitc::IDENTIFICATION_CODE_STRING,
48340b57cec5SDimitry Andric                     "LLVM" LLVM_VERSION_STRING, StringAbbrev);
48350b57cec5SDimitry Andric 
48360b57cec5SDimitry Andric   // Write the epoch version
48370b57cec5SDimitry Andric   Abbv = std::make_shared<BitCodeAbbrev>();
48380b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::IDENTIFICATION_CODE_EPOCH));
48390b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
48400b57cec5SDimitry Andric   auto EpochAbbrev = Stream.EmitAbbrev(std::move(Abbv));
48415ffd83dbSDimitry Andric   constexpr std::array<unsigned, 1> Vals = {{bitc::BITCODE_CURRENT_EPOCH}};
48420b57cec5SDimitry Andric   Stream.EmitRecord(bitc::IDENTIFICATION_CODE_EPOCH, Vals, EpochAbbrev);
48430b57cec5SDimitry Andric   Stream.ExitBlock();
48440b57cec5SDimitry Andric }
48450b57cec5SDimitry Andric 
4846*0fca6ea1SDimitry Andric void ModuleBitcodeWriter::writeModuleHash(StringRef View) {
48470b57cec5SDimitry Andric   // Emit the module's hash.
48480b57cec5SDimitry Andric   // MODULE_CODE_HASH: [5*i32]
48490b57cec5SDimitry Andric   if (GenerateHash) {
48500b57cec5SDimitry Andric     uint32_t Vals[5];
4851*0fca6ea1SDimitry Andric     Hasher.update(ArrayRef<uint8_t>(
4852*0fca6ea1SDimitry Andric         reinterpret_cast<const uint8_t *>(View.data()), View.size()));
485381ad6265SDimitry Andric     std::array<uint8_t, 20> Hash = Hasher.result();
48540b57cec5SDimitry Andric     for (int Pos = 0; Pos < 20; Pos += 4) {
48550b57cec5SDimitry Andric       Vals[Pos / 4] = support::endian::read32be(Hash.data() + Pos);
48560b57cec5SDimitry Andric     }
48570b57cec5SDimitry Andric 
48580b57cec5SDimitry Andric     // Emit the finished record.
48590b57cec5SDimitry Andric     Stream.EmitRecord(bitc::MODULE_CODE_HASH, Vals);
48600b57cec5SDimitry Andric 
48610b57cec5SDimitry Andric     if (ModHash)
48620b57cec5SDimitry Andric       // Save the written hash value.
48630b57cec5SDimitry Andric       llvm::copy(Vals, std::begin(*ModHash));
48640b57cec5SDimitry Andric   }
48650b57cec5SDimitry Andric }
48660b57cec5SDimitry Andric 
48670b57cec5SDimitry Andric void ModuleBitcodeWriter::write() {
48680b57cec5SDimitry Andric   writeIdentificationBlock(Stream);
48690b57cec5SDimitry Andric 
48700b57cec5SDimitry Andric   Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
4871*0fca6ea1SDimitry Andric   // We will want to write the module hash at this point. Block any flushing so
4872*0fca6ea1SDimitry Andric   // we can have access to the whole underlying data later.
4873*0fca6ea1SDimitry Andric   Stream.markAndBlockFlushing();
48740b57cec5SDimitry Andric 
48750b57cec5SDimitry Andric   writeModuleVersion();
48760b57cec5SDimitry Andric 
48770b57cec5SDimitry Andric   // Emit blockinfo, which defines the standard abbreviations etc.
48780b57cec5SDimitry Andric   writeBlockInfo();
48790b57cec5SDimitry Andric 
48800b57cec5SDimitry Andric   // Emit information describing all of the types in the module.
48810b57cec5SDimitry Andric   writeTypeTable();
48820b57cec5SDimitry Andric 
48830b57cec5SDimitry Andric   // Emit information about attribute groups.
48840b57cec5SDimitry Andric   writeAttributeGroupTable();
48850b57cec5SDimitry Andric 
48860b57cec5SDimitry Andric   // Emit information about parameter attributes.
48870b57cec5SDimitry Andric   writeAttributeTable();
48880b57cec5SDimitry Andric 
48890b57cec5SDimitry Andric   writeComdats();
48900b57cec5SDimitry Andric 
48910b57cec5SDimitry Andric   // Emit top-level description of module, including target triple, inline asm,
48920b57cec5SDimitry Andric   // descriptors for global variables, and function prototype info.
48930b57cec5SDimitry Andric   writeModuleInfo();
48940b57cec5SDimitry Andric 
48950b57cec5SDimitry Andric   // Emit constants.
48960b57cec5SDimitry Andric   writeModuleConstants();
48970b57cec5SDimitry Andric 
48980b57cec5SDimitry Andric   // Emit metadata kind names.
48990b57cec5SDimitry Andric   writeModuleMetadataKinds();
49000b57cec5SDimitry Andric 
49010b57cec5SDimitry Andric   // Emit metadata.
49020b57cec5SDimitry Andric   writeModuleMetadata();
49030b57cec5SDimitry Andric 
49040b57cec5SDimitry Andric   // Emit module-level use-lists.
49050b57cec5SDimitry Andric   if (VE.shouldPreserveUseListOrder())
49060b57cec5SDimitry Andric     writeUseListBlock(nullptr);
49070b57cec5SDimitry Andric 
49080b57cec5SDimitry Andric   writeOperandBundleTags();
49090b57cec5SDimitry Andric   writeSyncScopeNames();
49100b57cec5SDimitry Andric 
49110b57cec5SDimitry Andric   // Emit function bodies.
49120b57cec5SDimitry Andric   DenseMap<const Function *, uint64_t> FunctionToBitcodeIndex;
49134824e7fdSDimitry Andric   for (const Function &F : M)
49144824e7fdSDimitry Andric     if (!F.isDeclaration())
49154824e7fdSDimitry Andric       writeFunction(F, FunctionToBitcodeIndex);
49160b57cec5SDimitry Andric 
49170b57cec5SDimitry Andric   // Need to write after the above call to WriteFunction which populates
49180b57cec5SDimitry Andric   // the summary information in the index.
49190b57cec5SDimitry Andric   if (Index)
49200b57cec5SDimitry Andric     writePerModuleGlobalValueSummary();
49210b57cec5SDimitry Andric 
49220b57cec5SDimitry Andric   writeGlobalValueSymbolTable(FunctionToBitcodeIndex);
49230b57cec5SDimitry Andric 
4924*0fca6ea1SDimitry Andric   writeModuleHash(Stream.getMarkedBufferAndResumeFlushing());
49250b57cec5SDimitry Andric 
49260b57cec5SDimitry Andric   Stream.ExitBlock();
49270b57cec5SDimitry Andric }
49280b57cec5SDimitry Andric 
49290b57cec5SDimitry Andric static void writeInt32ToBuffer(uint32_t Value, SmallVectorImpl<char> &Buffer,
49300b57cec5SDimitry Andric                                uint32_t &Position) {
49310b57cec5SDimitry Andric   support::endian::write32le(&Buffer[Position], Value);
49320b57cec5SDimitry Andric   Position += 4;
49330b57cec5SDimitry Andric }
49340b57cec5SDimitry Andric 
49350b57cec5SDimitry Andric /// If generating a bc file on darwin, we have to emit a
49360b57cec5SDimitry Andric /// header and trailer to make it compatible with the system archiver.  To do
49370b57cec5SDimitry Andric /// this we emit the following header, and then emit a trailer that pads the
49380b57cec5SDimitry Andric /// file out to be a multiple of 16 bytes.
49390b57cec5SDimitry Andric ///
49400b57cec5SDimitry Andric /// struct bc_header {
49410b57cec5SDimitry Andric ///   uint32_t Magic;         // 0x0B17C0DE
49420b57cec5SDimitry Andric ///   uint32_t Version;       // Version, currently always 0.
49430b57cec5SDimitry Andric ///   uint32_t BitcodeOffset; // Offset to traditional bitcode file.
49440b57cec5SDimitry Andric ///   uint32_t BitcodeSize;   // Size of traditional bitcode file.
49450b57cec5SDimitry Andric ///   uint32_t CPUType;       // CPU specifier.
49460b57cec5SDimitry Andric ///   ... potentially more later ...
49470b57cec5SDimitry Andric /// };
49480b57cec5SDimitry Andric static void emitDarwinBCHeaderAndTrailer(SmallVectorImpl<char> &Buffer,
49490b57cec5SDimitry Andric                                          const Triple &TT) {
49500b57cec5SDimitry Andric   unsigned CPUType = ~0U;
49510b57cec5SDimitry Andric 
49520b57cec5SDimitry Andric   // Match x86_64-*, i[3-9]86-*, powerpc-*, powerpc64-*, arm-*, thumb-*,
49530b57cec5SDimitry Andric   // armv[0-9]-*, thumbv[0-9]-*, armv5te-*, or armv6t2-*. The CPUType is a magic
49540b57cec5SDimitry Andric   // number from /usr/include/mach/machine.h.  It is ok to reproduce the
49550b57cec5SDimitry Andric   // specific constants here because they are implicitly part of the Darwin ABI.
49560b57cec5SDimitry Andric   enum {
49570b57cec5SDimitry Andric     DARWIN_CPU_ARCH_ABI64      = 0x01000000,
49580b57cec5SDimitry Andric     DARWIN_CPU_TYPE_X86        = 7,
49590b57cec5SDimitry Andric     DARWIN_CPU_TYPE_ARM        = 12,
49600b57cec5SDimitry Andric     DARWIN_CPU_TYPE_POWERPC    = 18
49610b57cec5SDimitry Andric   };
49620b57cec5SDimitry Andric 
49630b57cec5SDimitry Andric   Triple::ArchType Arch = TT.getArch();
49640b57cec5SDimitry Andric   if (Arch == Triple::x86_64)
49650b57cec5SDimitry Andric     CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64;
49660b57cec5SDimitry Andric   else if (Arch == Triple::x86)
49670b57cec5SDimitry Andric     CPUType = DARWIN_CPU_TYPE_X86;
49680b57cec5SDimitry Andric   else if (Arch == Triple::ppc)
49690b57cec5SDimitry Andric     CPUType = DARWIN_CPU_TYPE_POWERPC;
49700b57cec5SDimitry Andric   else if (Arch == Triple::ppc64)
49710b57cec5SDimitry Andric     CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64;
49720b57cec5SDimitry Andric   else if (Arch == Triple::arm || Arch == Triple::thumb)
49730b57cec5SDimitry Andric     CPUType = DARWIN_CPU_TYPE_ARM;
49740b57cec5SDimitry Andric 
49750b57cec5SDimitry Andric   // Traditional Bitcode starts after header.
49760b57cec5SDimitry Andric   assert(Buffer.size() >= BWH_HeaderSize &&
49770b57cec5SDimitry Andric          "Expected header size to be reserved");
49780b57cec5SDimitry Andric   unsigned BCOffset = BWH_HeaderSize;
49790b57cec5SDimitry Andric   unsigned BCSize = Buffer.size() - BWH_HeaderSize;
49800b57cec5SDimitry Andric 
49810b57cec5SDimitry Andric   // Write the magic and version.
49820b57cec5SDimitry Andric   unsigned Position = 0;
49830b57cec5SDimitry Andric   writeInt32ToBuffer(0x0B17C0DE, Buffer, Position);
49840b57cec5SDimitry Andric   writeInt32ToBuffer(0, Buffer, Position); // Version.
49850b57cec5SDimitry Andric   writeInt32ToBuffer(BCOffset, Buffer, Position);
49860b57cec5SDimitry Andric   writeInt32ToBuffer(BCSize, Buffer, Position);
49870b57cec5SDimitry Andric   writeInt32ToBuffer(CPUType, Buffer, Position);
49880b57cec5SDimitry Andric 
49890b57cec5SDimitry Andric   // If the file is not a multiple of 16 bytes, insert dummy padding.
49900b57cec5SDimitry Andric   while (Buffer.size() & 15)
49910b57cec5SDimitry Andric     Buffer.push_back(0);
49920b57cec5SDimitry Andric }
49930b57cec5SDimitry Andric 
49940b57cec5SDimitry Andric /// Helper to write the header common to all bitcode files.
49950b57cec5SDimitry Andric static void writeBitcodeHeader(BitstreamWriter &Stream) {
49960b57cec5SDimitry Andric   // Emit the file header.
49970b57cec5SDimitry Andric   Stream.Emit((unsigned)'B', 8);
49980b57cec5SDimitry Andric   Stream.Emit((unsigned)'C', 8);
49990b57cec5SDimitry Andric   Stream.Emit(0x0, 4);
50000b57cec5SDimitry Andric   Stream.Emit(0xC, 4);
50010b57cec5SDimitry Andric   Stream.Emit(0xE, 4);
50020b57cec5SDimitry Andric   Stream.Emit(0xD, 4);
50030b57cec5SDimitry Andric }
50040b57cec5SDimitry Andric 
5005*0fca6ea1SDimitry Andric BitcodeWriter::BitcodeWriter(SmallVectorImpl<char> &Buffer)
5006*0fca6ea1SDimitry Andric     : Stream(new BitstreamWriter(Buffer)) {
5007*0fca6ea1SDimitry Andric   writeBitcodeHeader(*Stream);
5008*0fca6ea1SDimitry Andric }
5009*0fca6ea1SDimitry Andric 
5010*0fca6ea1SDimitry Andric BitcodeWriter::BitcodeWriter(raw_ostream &FS)
5011*0fca6ea1SDimitry Andric     : Stream(new BitstreamWriter(FS, FlushThreshold)) {
50120b57cec5SDimitry Andric   writeBitcodeHeader(*Stream);
50130b57cec5SDimitry Andric }
50140b57cec5SDimitry Andric 
50150b57cec5SDimitry Andric BitcodeWriter::~BitcodeWriter() { assert(WroteStrtab); }
50160b57cec5SDimitry Andric 
50170b57cec5SDimitry Andric void BitcodeWriter::writeBlob(unsigned Block, unsigned Record, StringRef Blob) {
50180b57cec5SDimitry Andric   Stream->EnterSubblock(Block, 3);
50190b57cec5SDimitry Andric 
50200b57cec5SDimitry Andric   auto Abbv = std::make_shared<BitCodeAbbrev>();
50210b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(Record));
50220b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
50230b57cec5SDimitry Andric   auto AbbrevNo = Stream->EmitAbbrev(std::move(Abbv));
50240b57cec5SDimitry Andric 
50250b57cec5SDimitry Andric   Stream->EmitRecordWithBlob(AbbrevNo, ArrayRef<uint64_t>{Record}, Blob);
50260b57cec5SDimitry Andric 
50270b57cec5SDimitry Andric   Stream->ExitBlock();
50280b57cec5SDimitry Andric }
50290b57cec5SDimitry Andric 
50300b57cec5SDimitry Andric void BitcodeWriter::writeSymtab() {
50310b57cec5SDimitry Andric   assert(!WroteStrtab && !WroteSymtab);
50320b57cec5SDimitry Andric 
50330b57cec5SDimitry Andric   // If any module has module-level inline asm, we will require a registered asm
50340b57cec5SDimitry Andric   // parser for the target so that we can create an accurate symbol table for
50350b57cec5SDimitry Andric   // the module.
50360b57cec5SDimitry Andric   for (Module *M : Mods) {
50370b57cec5SDimitry Andric     if (M->getModuleInlineAsm().empty())
50380b57cec5SDimitry Andric       continue;
50390b57cec5SDimitry Andric 
50400b57cec5SDimitry Andric     std::string Err;
50410b57cec5SDimitry Andric     const Triple TT(M->getTargetTriple());
50420b57cec5SDimitry Andric     const Target *T = TargetRegistry::lookupTarget(TT.str(), Err);
50430b57cec5SDimitry Andric     if (!T || !T->hasMCAsmParser())
50440b57cec5SDimitry Andric       return;
50450b57cec5SDimitry Andric   }
50460b57cec5SDimitry Andric 
50470b57cec5SDimitry Andric   WroteSymtab = true;
50480b57cec5SDimitry Andric   SmallVector<char, 0> Symtab;
50490b57cec5SDimitry Andric   // The irsymtab::build function may be unable to create a symbol table if the
50500b57cec5SDimitry Andric   // module is malformed (e.g. it contains an invalid alias). Writing a symbol
50510b57cec5SDimitry Andric   // table is not required for correctness, but we still want to be able to
50520b57cec5SDimitry Andric   // write malformed modules to bitcode files, so swallow the error.
50530b57cec5SDimitry Andric   if (Error E = irsymtab::build(Mods, Symtab, StrtabBuilder, Alloc)) {
50540b57cec5SDimitry Andric     consumeError(std::move(E));
50550b57cec5SDimitry Andric     return;
50560b57cec5SDimitry Andric   }
50570b57cec5SDimitry Andric 
50580b57cec5SDimitry Andric   writeBlob(bitc::SYMTAB_BLOCK_ID, bitc::SYMTAB_BLOB,
50590b57cec5SDimitry Andric             {Symtab.data(), Symtab.size()});
50600b57cec5SDimitry Andric }
50610b57cec5SDimitry Andric 
50620b57cec5SDimitry Andric void BitcodeWriter::writeStrtab() {
50630b57cec5SDimitry Andric   assert(!WroteStrtab);
50640b57cec5SDimitry Andric 
50650b57cec5SDimitry Andric   std::vector<char> Strtab;
50660b57cec5SDimitry Andric   StrtabBuilder.finalizeInOrder();
50670b57cec5SDimitry Andric   Strtab.resize(StrtabBuilder.getSize());
50680b57cec5SDimitry Andric   StrtabBuilder.write((uint8_t *)Strtab.data());
50690b57cec5SDimitry Andric 
50700b57cec5SDimitry Andric   writeBlob(bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB,
50710b57cec5SDimitry Andric             {Strtab.data(), Strtab.size()});
50720b57cec5SDimitry Andric 
50730b57cec5SDimitry Andric   WroteStrtab = true;
50740b57cec5SDimitry Andric }
50750b57cec5SDimitry Andric 
50760b57cec5SDimitry Andric void BitcodeWriter::copyStrtab(StringRef Strtab) {
50770b57cec5SDimitry Andric   writeBlob(bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB, Strtab);
50780b57cec5SDimitry Andric   WroteStrtab = true;
50790b57cec5SDimitry Andric }
50800b57cec5SDimitry Andric 
50810b57cec5SDimitry Andric void BitcodeWriter::writeModule(const Module &M,
50820b57cec5SDimitry Andric                                 bool ShouldPreserveUseListOrder,
50830b57cec5SDimitry Andric                                 const ModuleSummaryIndex *Index,
50840b57cec5SDimitry Andric                                 bool GenerateHash, ModuleHash *ModHash) {
50850b57cec5SDimitry Andric   assert(!WroteStrtab);
50860b57cec5SDimitry Andric 
50870b57cec5SDimitry Andric   // The Mods vector is used by irsymtab::build, which requires non-const
50880b57cec5SDimitry Andric   // Modules in case it needs to materialize metadata. But the bitcode writer
50890b57cec5SDimitry Andric   // requires that the module is materialized, so we can cast to non-const here,
50900b57cec5SDimitry Andric   // after checking that it is in fact materialized.
50910b57cec5SDimitry Andric   assert(M.isMaterialized());
50920b57cec5SDimitry Andric   Mods.push_back(const_cast<Module *>(&M));
50930b57cec5SDimitry Andric 
5094*0fca6ea1SDimitry Andric   ModuleBitcodeWriter ModuleWriter(M, StrtabBuilder, *Stream,
50950b57cec5SDimitry Andric                                    ShouldPreserveUseListOrder, Index,
50960b57cec5SDimitry Andric                                    GenerateHash, ModHash);
50970b57cec5SDimitry Andric   ModuleWriter.write();
50980b57cec5SDimitry Andric }
50990b57cec5SDimitry Andric 
51000b57cec5SDimitry Andric void BitcodeWriter::writeIndex(
51010b57cec5SDimitry Andric     const ModuleSummaryIndex *Index,
5102*0fca6ea1SDimitry Andric     const std::map<std::string, GVSummaryMapTy> *ModuleToSummariesForIndex,
5103*0fca6ea1SDimitry Andric     const GVSummaryPtrSet *DecSummaries) {
5104*0fca6ea1SDimitry Andric   IndexBitcodeWriter IndexWriter(*Stream, StrtabBuilder, *Index, DecSummaries,
51050b57cec5SDimitry Andric                                  ModuleToSummariesForIndex);
51060b57cec5SDimitry Andric   IndexWriter.write();
51070b57cec5SDimitry Andric }
51080b57cec5SDimitry Andric 
51090b57cec5SDimitry Andric /// Write the specified module to the specified output stream.
51100b57cec5SDimitry Andric void llvm::WriteBitcodeToFile(const Module &M, raw_ostream &Out,
51110b57cec5SDimitry Andric                               bool ShouldPreserveUseListOrder,
51120b57cec5SDimitry Andric                               const ModuleSummaryIndex *Index,
51130b57cec5SDimitry Andric                               bool GenerateHash, ModuleHash *ModHash) {
5114*0fca6ea1SDimitry Andric   auto Write = [&](BitcodeWriter &Writer) {
51150b57cec5SDimitry Andric     Writer.writeModule(M, ShouldPreserveUseListOrder, Index, GenerateHash,
51160b57cec5SDimitry Andric                        ModHash);
51170b57cec5SDimitry Andric     Writer.writeSymtab();
51180b57cec5SDimitry Andric     Writer.writeStrtab();
5119*0fca6ea1SDimitry Andric   };
5120*0fca6ea1SDimitry Andric   Triple TT(M.getTargetTriple());
5121*0fca6ea1SDimitry Andric   if (TT.isOSDarwin() || TT.isOSBinFormatMachO()) {
5122*0fca6ea1SDimitry Andric     // If this is darwin or another generic macho target, reserve space for the
5123*0fca6ea1SDimitry Andric     // header. Note that the header is computed *after* the output is known, so
5124*0fca6ea1SDimitry Andric     // we currently explicitly use a buffer, write to it, and then subsequently
5125*0fca6ea1SDimitry Andric     // flush to Out.
5126*0fca6ea1SDimitry Andric     SmallVector<char, 0> Buffer;
5127*0fca6ea1SDimitry Andric     Buffer.reserve(256 * 1024);
5128*0fca6ea1SDimitry Andric     Buffer.insert(Buffer.begin(), BWH_HeaderSize, 0);
5129*0fca6ea1SDimitry Andric     BitcodeWriter Writer(Buffer);
5130*0fca6ea1SDimitry Andric     Write(Writer);
51310b57cec5SDimitry Andric     emitDarwinBCHeaderAndTrailer(Buffer, TT);
5132*0fca6ea1SDimitry Andric     Out.write(Buffer.data(), Buffer.size());
5133*0fca6ea1SDimitry Andric   } else {
5134*0fca6ea1SDimitry Andric     BitcodeWriter Writer(Out);
5135*0fca6ea1SDimitry Andric     Write(Writer);
5136*0fca6ea1SDimitry Andric   }
51370b57cec5SDimitry Andric }
51380b57cec5SDimitry Andric 
51390b57cec5SDimitry Andric void IndexBitcodeWriter::write() {
51400b57cec5SDimitry Andric   Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
51410b57cec5SDimitry Andric 
51420b57cec5SDimitry Andric   writeModuleVersion();
51430b57cec5SDimitry Andric 
51440b57cec5SDimitry Andric   // Write the module paths in the combined index.
51450b57cec5SDimitry Andric   writeModStrings();
51460b57cec5SDimitry Andric 
51470b57cec5SDimitry Andric   // Write the summary combined index records.
51480b57cec5SDimitry Andric   writeCombinedGlobalValueSummary();
51490b57cec5SDimitry Andric 
51500b57cec5SDimitry Andric   Stream.ExitBlock();
51510b57cec5SDimitry Andric }
51520b57cec5SDimitry Andric 
51530b57cec5SDimitry Andric // Write the specified module summary index to the given raw output stream,
51540b57cec5SDimitry Andric // where it will be written in a new bitcode block. This is used when
51550b57cec5SDimitry Andric // writing the combined index file for ThinLTO. When writing a subset of the
51560b57cec5SDimitry Andric // index for a distributed backend, provide a \p ModuleToSummariesForIndex map.
51571fd87a68SDimitry Andric void llvm::writeIndexToFile(
51580b57cec5SDimitry Andric     const ModuleSummaryIndex &Index, raw_ostream &Out,
5159*0fca6ea1SDimitry Andric     const std::map<std::string, GVSummaryMapTy> *ModuleToSummariesForIndex,
5160*0fca6ea1SDimitry Andric     const GVSummaryPtrSet *DecSummaries) {
51610b57cec5SDimitry Andric   SmallVector<char, 0> Buffer;
51620b57cec5SDimitry Andric   Buffer.reserve(256 * 1024);
51630b57cec5SDimitry Andric 
51640b57cec5SDimitry Andric   BitcodeWriter Writer(Buffer);
5165*0fca6ea1SDimitry Andric   Writer.writeIndex(&Index, ModuleToSummariesForIndex, DecSummaries);
51660b57cec5SDimitry Andric   Writer.writeStrtab();
51670b57cec5SDimitry Andric 
51680b57cec5SDimitry Andric   Out.write((char *)&Buffer.front(), Buffer.size());
51690b57cec5SDimitry Andric }
51700b57cec5SDimitry Andric 
51710b57cec5SDimitry Andric namespace {
51720b57cec5SDimitry Andric 
51730b57cec5SDimitry Andric /// Class to manage the bitcode writing for a thin link bitcode file.
51740b57cec5SDimitry Andric class ThinLinkBitcodeWriter : public ModuleBitcodeWriterBase {
51750b57cec5SDimitry Andric   /// ModHash is for use in ThinLTO incremental build, generated while writing
51760b57cec5SDimitry Andric   /// the module bitcode file.
51770b57cec5SDimitry Andric   const ModuleHash *ModHash;
51780b57cec5SDimitry Andric 
51790b57cec5SDimitry Andric public:
51800b57cec5SDimitry Andric   ThinLinkBitcodeWriter(const Module &M, StringTableBuilder &StrtabBuilder,
51810b57cec5SDimitry Andric                         BitstreamWriter &Stream,
51820b57cec5SDimitry Andric                         const ModuleSummaryIndex &Index,
51830b57cec5SDimitry Andric                         const ModuleHash &ModHash)
51840b57cec5SDimitry Andric       : ModuleBitcodeWriterBase(M, StrtabBuilder, Stream,
51850b57cec5SDimitry Andric                                 /*ShouldPreserveUseListOrder=*/false, &Index),
51860b57cec5SDimitry Andric         ModHash(&ModHash) {}
51870b57cec5SDimitry Andric 
51880b57cec5SDimitry Andric   void write();
51890b57cec5SDimitry Andric 
51900b57cec5SDimitry Andric private:
51910b57cec5SDimitry Andric   void writeSimplifiedModuleInfo();
51920b57cec5SDimitry Andric };
51930b57cec5SDimitry Andric 
51940b57cec5SDimitry Andric } // end anonymous namespace
51950b57cec5SDimitry Andric 
51960b57cec5SDimitry Andric // This function writes a simpilified module info for thin link bitcode file.
51970b57cec5SDimitry Andric // It only contains the source file name along with the name(the offset and
51980b57cec5SDimitry Andric // size in strtab) and linkage for global values. For the global value info
51990b57cec5SDimitry Andric // entry, in order to keep linkage at offset 5, there are three zeros used
52000b57cec5SDimitry Andric // as padding.
52010b57cec5SDimitry Andric void ThinLinkBitcodeWriter::writeSimplifiedModuleInfo() {
52020b57cec5SDimitry Andric   SmallVector<unsigned, 64> Vals;
52030b57cec5SDimitry Andric   // Emit the module's source file name.
52040b57cec5SDimitry Andric   {
52050b57cec5SDimitry Andric     StringEncoding Bits = getStringEncoding(M.getSourceFileName());
52060b57cec5SDimitry Andric     BitCodeAbbrevOp AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8);
52070b57cec5SDimitry Andric     if (Bits == SE_Char6)
52080b57cec5SDimitry Andric       AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Char6);
52090b57cec5SDimitry Andric     else if (Bits == SE_Fixed7)
52100b57cec5SDimitry Andric       AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7);
52110b57cec5SDimitry Andric 
52120b57cec5SDimitry Andric     // MODULE_CODE_SOURCE_FILENAME: [namechar x N]
52130b57cec5SDimitry Andric     auto Abbv = std::make_shared<BitCodeAbbrev>();
52140b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_SOURCE_FILENAME));
52150b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
52160b57cec5SDimitry Andric     Abbv->Add(AbbrevOpToUse);
52170b57cec5SDimitry Andric     unsigned FilenameAbbrev = Stream.EmitAbbrev(std::move(Abbv));
52180b57cec5SDimitry Andric 
52190b57cec5SDimitry Andric     for (const auto P : M.getSourceFileName())
52200b57cec5SDimitry Andric       Vals.push_back((unsigned char)P);
52210b57cec5SDimitry Andric 
52220b57cec5SDimitry Andric     Stream.EmitRecord(bitc::MODULE_CODE_SOURCE_FILENAME, Vals, FilenameAbbrev);
52230b57cec5SDimitry Andric     Vals.clear();
52240b57cec5SDimitry Andric   }
52250b57cec5SDimitry Andric 
52260b57cec5SDimitry Andric   // Emit the global variable information.
52270b57cec5SDimitry Andric   for (const GlobalVariable &GV : M.globals()) {
52280b57cec5SDimitry Andric     // GLOBALVAR: [strtab offset, strtab size, 0, 0, 0, linkage]
52290b57cec5SDimitry Andric     Vals.push_back(StrtabBuilder.add(GV.getName()));
52300b57cec5SDimitry Andric     Vals.push_back(GV.getName().size());
52310b57cec5SDimitry Andric     Vals.push_back(0);
52320b57cec5SDimitry Andric     Vals.push_back(0);
52330b57cec5SDimitry Andric     Vals.push_back(0);
52340b57cec5SDimitry Andric     Vals.push_back(getEncodedLinkage(GV));
52350b57cec5SDimitry Andric 
52360b57cec5SDimitry Andric     Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals);
52370b57cec5SDimitry Andric     Vals.clear();
52380b57cec5SDimitry Andric   }
52390b57cec5SDimitry Andric 
52400b57cec5SDimitry Andric   // Emit the function proto information.
52410b57cec5SDimitry Andric   for (const Function &F : M) {
52420b57cec5SDimitry Andric     // FUNCTION:  [strtab offset, strtab size, 0, 0, 0, linkage]
52430b57cec5SDimitry Andric     Vals.push_back(StrtabBuilder.add(F.getName()));
52440b57cec5SDimitry Andric     Vals.push_back(F.getName().size());
52450b57cec5SDimitry Andric     Vals.push_back(0);
52460b57cec5SDimitry Andric     Vals.push_back(0);
52470b57cec5SDimitry Andric     Vals.push_back(0);
52480b57cec5SDimitry Andric     Vals.push_back(getEncodedLinkage(F));
52490b57cec5SDimitry Andric 
52500b57cec5SDimitry Andric     Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals);
52510b57cec5SDimitry Andric     Vals.clear();
52520b57cec5SDimitry Andric   }
52530b57cec5SDimitry Andric 
52540b57cec5SDimitry Andric   // Emit the alias information.
52550b57cec5SDimitry Andric   for (const GlobalAlias &A : M.aliases()) {
52560b57cec5SDimitry Andric     // ALIAS: [strtab offset, strtab size, 0, 0, 0, linkage]
52570b57cec5SDimitry Andric     Vals.push_back(StrtabBuilder.add(A.getName()));
52580b57cec5SDimitry Andric     Vals.push_back(A.getName().size());
52590b57cec5SDimitry Andric     Vals.push_back(0);
52600b57cec5SDimitry Andric     Vals.push_back(0);
52610b57cec5SDimitry Andric     Vals.push_back(0);
52620b57cec5SDimitry Andric     Vals.push_back(getEncodedLinkage(A));
52630b57cec5SDimitry Andric 
52640b57cec5SDimitry Andric     Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals);
52650b57cec5SDimitry Andric     Vals.clear();
52660b57cec5SDimitry Andric   }
52670b57cec5SDimitry Andric 
52680b57cec5SDimitry Andric   // Emit the ifunc information.
52690b57cec5SDimitry Andric   for (const GlobalIFunc &I : M.ifuncs()) {
52700b57cec5SDimitry Andric     // IFUNC: [strtab offset, strtab size, 0, 0, 0, linkage]
52710b57cec5SDimitry Andric     Vals.push_back(StrtabBuilder.add(I.getName()));
52720b57cec5SDimitry Andric     Vals.push_back(I.getName().size());
52730b57cec5SDimitry Andric     Vals.push_back(0);
52740b57cec5SDimitry Andric     Vals.push_back(0);
52750b57cec5SDimitry Andric     Vals.push_back(0);
52760b57cec5SDimitry Andric     Vals.push_back(getEncodedLinkage(I));
52770b57cec5SDimitry Andric 
52780b57cec5SDimitry Andric     Stream.EmitRecord(bitc::MODULE_CODE_IFUNC, Vals);
52790b57cec5SDimitry Andric     Vals.clear();
52800b57cec5SDimitry Andric   }
52810b57cec5SDimitry Andric }
52820b57cec5SDimitry Andric 
52830b57cec5SDimitry Andric void ThinLinkBitcodeWriter::write() {
52840b57cec5SDimitry Andric   Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
52850b57cec5SDimitry Andric 
52860b57cec5SDimitry Andric   writeModuleVersion();
52870b57cec5SDimitry Andric 
52880b57cec5SDimitry Andric   writeSimplifiedModuleInfo();
52890b57cec5SDimitry Andric 
52900b57cec5SDimitry Andric   writePerModuleGlobalValueSummary();
52910b57cec5SDimitry Andric 
52920b57cec5SDimitry Andric   // Write module hash.
52930b57cec5SDimitry Andric   Stream.EmitRecord(bitc::MODULE_CODE_HASH, ArrayRef<uint32_t>(*ModHash));
52940b57cec5SDimitry Andric 
52950b57cec5SDimitry Andric   Stream.ExitBlock();
52960b57cec5SDimitry Andric }
52970b57cec5SDimitry Andric 
52980b57cec5SDimitry Andric void BitcodeWriter::writeThinLinkBitcode(const Module &M,
52990b57cec5SDimitry Andric                                          const ModuleSummaryIndex &Index,
53000b57cec5SDimitry Andric                                          const ModuleHash &ModHash) {
53010b57cec5SDimitry Andric   assert(!WroteStrtab);
53020b57cec5SDimitry Andric 
53030b57cec5SDimitry Andric   // The Mods vector is used by irsymtab::build, which requires non-const
53040b57cec5SDimitry Andric   // Modules in case it needs to materialize metadata. But the bitcode writer
53050b57cec5SDimitry Andric   // requires that the module is materialized, so we can cast to non-const here,
53060b57cec5SDimitry Andric   // after checking that it is in fact materialized.
53070b57cec5SDimitry Andric   assert(M.isMaterialized());
53080b57cec5SDimitry Andric   Mods.push_back(const_cast<Module *>(&M));
53090b57cec5SDimitry Andric 
53100b57cec5SDimitry Andric   ThinLinkBitcodeWriter ThinLinkWriter(M, StrtabBuilder, *Stream, Index,
53110b57cec5SDimitry Andric                                        ModHash);
53120b57cec5SDimitry Andric   ThinLinkWriter.write();
53130b57cec5SDimitry Andric }
53140b57cec5SDimitry Andric 
53150b57cec5SDimitry Andric // Write the specified thin link bitcode file to the given raw output stream,
53160b57cec5SDimitry Andric // where it will be written in a new bitcode block. This is used when
53170b57cec5SDimitry Andric // writing the per-module index file for ThinLTO.
53181fd87a68SDimitry Andric void llvm::writeThinLinkBitcodeToFile(const Module &M, raw_ostream &Out,
53190b57cec5SDimitry Andric                                       const ModuleSummaryIndex &Index,
53200b57cec5SDimitry Andric                                       const ModuleHash &ModHash) {
53210b57cec5SDimitry Andric   SmallVector<char, 0> Buffer;
53220b57cec5SDimitry Andric   Buffer.reserve(256 * 1024);
53230b57cec5SDimitry Andric 
53240b57cec5SDimitry Andric   BitcodeWriter Writer(Buffer);
53250b57cec5SDimitry Andric   Writer.writeThinLinkBitcode(M, Index, ModHash);
53260b57cec5SDimitry Andric   Writer.writeSymtab();
53270b57cec5SDimitry Andric   Writer.writeStrtab();
53280b57cec5SDimitry Andric 
53290b57cec5SDimitry Andric   Out.write((char *)&Buffer.front(), Buffer.size());
53300b57cec5SDimitry Andric }
5331480093f4SDimitry Andric 
5332480093f4SDimitry Andric static const char *getSectionNameForBitcode(const Triple &T) {
5333480093f4SDimitry Andric   switch (T.getObjectFormat()) {
5334480093f4SDimitry Andric   case Triple::MachO:
5335480093f4SDimitry Andric     return "__LLVM,__bitcode";
5336480093f4SDimitry Andric   case Triple::COFF:
5337480093f4SDimitry Andric   case Triple::ELF:
5338480093f4SDimitry Andric   case Triple::Wasm:
5339480093f4SDimitry Andric   case Triple::UnknownObjectFormat:
5340480093f4SDimitry Andric     return ".llvmbc";
5341e8d8bef9SDimitry Andric   case Triple::GOFF:
5342e8d8bef9SDimitry Andric     llvm_unreachable("GOFF is not yet implemented");
5343e8d8bef9SDimitry Andric     break;
534481ad6265SDimitry Andric   case Triple::SPIRV:
5345*0fca6ea1SDimitry Andric     if (T.getVendor() == Triple::AMD)
5346*0fca6ea1SDimitry Andric       return ".llvmbc";
534781ad6265SDimitry Andric     llvm_unreachable("SPIRV is not yet implemented");
534881ad6265SDimitry Andric     break;
5349480093f4SDimitry Andric   case Triple::XCOFF:
5350480093f4SDimitry Andric     llvm_unreachable("XCOFF is not yet implemented");
5351480093f4SDimitry Andric     break;
535281ad6265SDimitry Andric   case Triple::DXContainer:
535381ad6265SDimitry Andric     llvm_unreachable("DXContainer is not yet implemented");
535481ad6265SDimitry Andric     break;
5355480093f4SDimitry Andric   }
5356480093f4SDimitry Andric   llvm_unreachable("Unimplemented ObjectFormatType");
5357480093f4SDimitry Andric }
5358480093f4SDimitry Andric 
5359480093f4SDimitry Andric static const char *getSectionNameForCommandline(const Triple &T) {
5360480093f4SDimitry Andric   switch (T.getObjectFormat()) {
5361480093f4SDimitry Andric   case Triple::MachO:
5362480093f4SDimitry Andric     return "__LLVM,__cmdline";
5363480093f4SDimitry Andric   case Triple::COFF:
5364480093f4SDimitry Andric   case Triple::ELF:
5365480093f4SDimitry Andric   case Triple::Wasm:
5366480093f4SDimitry Andric   case Triple::UnknownObjectFormat:
5367480093f4SDimitry Andric     return ".llvmcmd";
5368e8d8bef9SDimitry Andric   case Triple::GOFF:
5369e8d8bef9SDimitry Andric     llvm_unreachable("GOFF is not yet implemented");
5370e8d8bef9SDimitry Andric     break;
537181ad6265SDimitry Andric   case Triple::SPIRV:
5372*0fca6ea1SDimitry Andric     if (T.getVendor() == Triple::AMD)
5373*0fca6ea1SDimitry Andric       return ".llvmcmd";
537481ad6265SDimitry Andric     llvm_unreachable("SPIRV is not yet implemented");
537581ad6265SDimitry Andric     break;
5376480093f4SDimitry Andric   case Triple::XCOFF:
5377480093f4SDimitry Andric     llvm_unreachable("XCOFF is not yet implemented");
5378480093f4SDimitry Andric     break;
537981ad6265SDimitry Andric   case Triple::DXContainer:
538081ad6265SDimitry Andric     llvm_unreachable("DXC is not yet implemented");
538181ad6265SDimitry Andric     break;
5382480093f4SDimitry Andric   }
5383480093f4SDimitry Andric   llvm_unreachable("Unimplemented ObjectFormatType");
5384480093f4SDimitry Andric }
5385480093f4SDimitry Andric 
53861fd87a68SDimitry Andric void llvm::embedBitcodeInModule(llvm::Module &M, llvm::MemoryBufferRef Buf,
5387e8d8bef9SDimitry Andric                                 bool EmbedBitcode, bool EmbedCmdline,
5388e8d8bef9SDimitry Andric                                 const std::vector<uint8_t> &CmdArgs) {
5389480093f4SDimitry Andric   // Save llvm.compiler.used and remove it.
5390480093f4SDimitry Andric   SmallVector<Constant *, 2> UsedArray;
5391fe6060f1SDimitry Andric   SmallVector<GlobalValue *, 4> UsedGlobals;
53925f757f3fSDimitry Andric   Type *UsedElementType = PointerType::getUnqual(M.getContext());
5393480093f4SDimitry Andric   GlobalVariable *Used = collectUsedGlobalVariables(M, UsedGlobals, true);
5394480093f4SDimitry Andric   for (auto *GV : UsedGlobals) {
5395480093f4SDimitry Andric     if (GV->getName() != "llvm.embedded.module" &&
5396480093f4SDimitry Andric         GV->getName() != "llvm.cmdline")
5397480093f4SDimitry Andric       UsedArray.push_back(
5398480093f4SDimitry Andric           ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
5399480093f4SDimitry Andric   }
5400480093f4SDimitry Andric   if (Used)
5401480093f4SDimitry Andric     Used->eraseFromParent();
5402480093f4SDimitry Andric 
5403480093f4SDimitry Andric   // Embed the bitcode for the llvm module.
5404480093f4SDimitry Andric   std::string Data;
5405480093f4SDimitry Andric   ArrayRef<uint8_t> ModuleData;
5406480093f4SDimitry Andric   Triple T(M.getTargetTriple());
5407e8d8bef9SDimitry Andric 
5408480093f4SDimitry Andric   if (EmbedBitcode) {
5409e8d8bef9SDimitry Andric     if (Buf.getBufferSize() == 0 ||
5410e8d8bef9SDimitry Andric         !isBitcode((const unsigned char *)Buf.getBufferStart(),
5411480093f4SDimitry Andric                    (const unsigned char *)Buf.getBufferEnd())) {
5412480093f4SDimitry Andric       // If the input is LLVM Assembly, bitcode is produced by serializing
5413480093f4SDimitry Andric       // the module. Use-lists order need to be preserved in this case.
5414480093f4SDimitry Andric       llvm::raw_string_ostream OS(Data);
5415480093f4SDimitry Andric       llvm::WriteBitcodeToFile(M, OS, /* ShouldPreserveUseListOrder */ true);
5416480093f4SDimitry Andric       ModuleData =
5417480093f4SDimitry Andric           ArrayRef<uint8_t>((const uint8_t *)OS.str().data(), OS.str().size());
5418480093f4SDimitry Andric     } else
5419480093f4SDimitry Andric       // If the input is LLVM bitcode, write the input byte stream directly.
5420480093f4SDimitry Andric       ModuleData = ArrayRef<uint8_t>((const uint8_t *)Buf.getBufferStart(),
5421480093f4SDimitry Andric                                      Buf.getBufferSize());
5422480093f4SDimitry Andric   }
5423480093f4SDimitry Andric   llvm::Constant *ModuleConstant =
5424480093f4SDimitry Andric       llvm::ConstantDataArray::get(M.getContext(), ModuleData);
5425480093f4SDimitry Andric   llvm::GlobalVariable *GV = new llvm::GlobalVariable(
5426480093f4SDimitry Andric       M, ModuleConstant->getType(), true, llvm::GlobalValue::PrivateLinkage,
5427480093f4SDimitry Andric       ModuleConstant);
5428480093f4SDimitry Andric   GV->setSection(getSectionNameForBitcode(T));
5429e8d8bef9SDimitry Andric   // Set alignment to 1 to prevent padding between two contributions from input
5430e8d8bef9SDimitry Andric   // sections after linking.
5431e8d8bef9SDimitry Andric   GV->setAlignment(Align(1));
5432480093f4SDimitry Andric   UsedArray.push_back(
5433480093f4SDimitry Andric       ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
5434480093f4SDimitry Andric   if (llvm::GlobalVariable *Old =
5435480093f4SDimitry Andric           M.getGlobalVariable("llvm.embedded.module", true)) {
543681ad6265SDimitry Andric     assert(Old->hasZeroLiveUses() &&
5437480093f4SDimitry Andric            "llvm.embedded.module can only be used once in llvm.compiler.used");
5438480093f4SDimitry Andric     GV->takeName(Old);
5439480093f4SDimitry Andric     Old->eraseFromParent();
5440480093f4SDimitry Andric   } else {
5441480093f4SDimitry Andric     GV->setName("llvm.embedded.module");
5442480093f4SDimitry Andric   }
5443480093f4SDimitry Andric 
5444480093f4SDimitry Andric   // Skip if only bitcode needs to be embedded.
5445e8d8bef9SDimitry Andric   if (EmbedCmdline) {
5446480093f4SDimitry Andric     // Embed command-line options.
5447e8d8bef9SDimitry Andric     ArrayRef<uint8_t> CmdData(const_cast<uint8_t *>(CmdArgs.data()),
5448e8d8bef9SDimitry Andric                               CmdArgs.size());
5449480093f4SDimitry Andric     llvm::Constant *CmdConstant =
5450480093f4SDimitry Andric         llvm::ConstantDataArray::get(M.getContext(), CmdData);
5451480093f4SDimitry Andric     GV = new llvm::GlobalVariable(M, CmdConstant->getType(), true,
5452480093f4SDimitry Andric                                   llvm::GlobalValue::PrivateLinkage,
5453480093f4SDimitry Andric                                   CmdConstant);
5454480093f4SDimitry Andric     GV->setSection(getSectionNameForCommandline(T));
5455e8d8bef9SDimitry Andric     GV->setAlignment(Align(1));
5456480093f4SDimitry Andric     UsedArray.push_back(
5457480093f4SDimitry Andric         ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
5458480093f4SDimitry Andric     if (llvm::GlobalVariable *Old = M.getGlobalVariable("llvm.cmdline", true)) {
545981ad6265SDimitry Andric       assert(Old->hasZeroLiveUses() &&
5460480093f4SDimitry Andric              "llvm.cmdline can only be used once in llvm.compiler.used");
5461480093f4SDimitry Andric       GV->takeName(Old);
5462480093f4SDimitry Andric       Old->eraseFromParent();
5463480093f4SDimitry Andric     } else {
5464480093f4SDimitry Andric       GV->setName("llvm.cmdline");
5465480093f4SDimitry Andric     }
5466480093f4SDimitry Andric   }
5467480093f4SDimitry Andric 
5468480093f4SDimitry Andric   if (UsedArray.empty())
5469480093f4SDimitry Andric     return;
5470480093f4SDimitry Andric 
5471480093f4SDimitry Andric   // Recreate llvm.compiler.used.
5472480093f4SDimitry Andric   ArrayType *ATy = ArrayType::get(UsedElementType, UsedArray.size());
5473480093f4SDimitry Andric   auto *NewUsed = new GlobalVariable(
5474480093f4SDimitry Andric       M, ATy, false, llvm::GlobalValue::AppendingLinkage,
5475480093f4SDimitry Andric       llvm::ConstantArray::get(ATy, UsedArray), "llvm.compiler.used");
5476480093f4SDimitry Andric   NewUsed->setSection("llvm.metadata");
5477480093f4SDimitry Andric }
5478