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"
360b57cec5SDimitry Andric #include "llvm/IR/Constants.h"
370b57cec5SDimitry Andric #include "llvm/IR/DebugInfoMetadata.h"
380b57cec5SDimitry Andric #include "llvm/IR/DebugLoc.h"
390b57cec5SDimitry Andric #include "llvm/IR/DerivedTypes.h"
400b57cec5SDimitry Andric #include "llvm/IR/Function.h"
410b57cec5SDimitry Andric #include "llvm/IR/GlobalAlias.h"
420b57cec5SDimitry Andric #include "llvm/IR/GlobalIFunc.h"
430b57cec5SDimitry Andric #include "llvm/IR/GlobalObject.h"
440b57cec5SDimitry Andric #include "llvm/IR/GlobalValue.h"
450b57cec5SDimitry Andric #include "llvm/IR/GlobalVariable.h"
460b57cec5SDimitry Andric #include "llvm/IR/InlineAsm.h"
470b57cec5SDimitry Andric #include "llvm/IR/InstrTypes.h"
480b57cec5SDimitry Andric #include "llvm/IR/Instruction.h"
490b57cec5SDimitry Andric #include "llvm/IR/Instructions.h"
500b57cec5SDimitry Andric #include "llvm/IR/LLVMContext.h"
510b57cec5SDimitry Andric #include "llvm/IR/Metadata.h"
520b57cec5SDimitry Andric #include "llvm/IR/Module.h"
530b57cec5SDimitry Andric #include "llvm/IR/ModuleSummaryIndex.h"
540b57cec5SDimitry Andric #include "llvm/IR/Operator.h"
550b57cec5SDimitry Andric #include "llvm/IR/Type.h"
560b57cec5SDimitry Andric #include "llvm/IR/UseListOrder.h"
570b57cec5SDimitry Andric #include "llvm/IR/Value.h"
580b57cec5SDimitry Andric #include "llvm/IR/ValueSymbolTable.h"
590b57cec5SDimitry Andric #include "llvm/MC/StringTableBuilder.h"
60349cc55cSDimitry Andric #include "llvm/MC/TargetRegistry.h"
610b57cec5SDimitry Andric #include "llvm/Object/IRSymtab.h"
620b57cec5SDimitry Andric #include "llvm/Support/AtomicOrdering.h"
630b57cec5SDimitry Andric #include "llvm/Support/Casting.h"
640b57cec5SDimitry Andric #include "llvm/Support/CommandLine.h"
650b57cec5SDimitry Andric #include "llvm/Support/Endian.h"
660b57cec5SDimitry Andric #include "llvm/Support/Error.h"
670b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h"
680b57cec5SDimitry Andric #include "llvm/Support/MathExtras.h"
690b57cec5SDimitry Andric #include "llvm/Support/SHA1.h"
700b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
71fe013be4SDimitry Andric #include "llvm/TargetParser/Triple.h"
720b57cec5SDimitry Andric #include <algorithm>
730b57cec5SDimitry Andric #include <cassert>
740b57cec5SDimitry Andric #include <cstddef>
750b57cec5SDimitry Andric #include <cstdint>
760b57cec5SDimitry Andric #include <iterator>
770b57cec5SDimitry Andric #include <map>
780b57cec5SDimitry Andric #include <memory>
79bdd1243dSDimitry Andric #include <optional>
800b57cec5SDimitry Andric #include <string>
810b57cec5SDimitry Andric #include <utility>
820b57cec5SDimitry Andric #include <vector>
830b57cec5SDimitry Andric 
840b57cec5SDimitry Andric using namespace llvm;
850b57cec5SDimitry Andric 
860b57cec5SDimitry Andric static cl::opt<unsigned>
870b57cec5SDimitry Andric     IndexThreshold("bitcode-mdindex-threshold", cl::Hidden, cl::init(25),
880b57cec5SDimitry Andric                    cl::desc("Number of metadatas above which we emit an index "
890b57cec5SDimitry Andric                             "to enable lazy-loading"));
90e8d8bef9SDimitry Andric static cl::opt<uint32_t> FlushThreshold(
91e8d8bef9SDimitry Andric     "bitcode-flush-threshold", cl::Hidden, cl::init(512),
92e8d8bef9SDimitry Andric     cl::desc("The threshold (unit M) for flushing LLVM bitcode."));
930b57cec5SDimitry Andric 
948bcb0991SDimitry Andric static cl::opt<bool> WriteRelBFToSummary(
950b57cec5SDimitry Andric     "write-relbf-to-summary", cl::Hidden, cl::init(false),
960b57cec5SDimitry Andric     cl::desc("Write relative block frequency to function summary "));
970b57cec5SDimitry Andric 
98bdd1243dSDimitry Andric namespace llvm {
990b57cec5SDimitry Andric extern FunctionSummary::ForceSummaryHotnessType ForceSummaryEdgesCold;
100bdd1243dSDimitry Andric }
1010b57cec5SDimitry Andric 
1020b57cec5SDimitry Andric namespace {
1030b57cec5SDimitry Andric 
1040b57cec5SDimitry Andric /// These are manifest constants used by the bitcode writer. They do not need to
1050b57cec5SDimitry Andric /// be kept in sync with the reader, but need to be consistent within this file.
1060b57cec5SDimitry Andric enum {
1070b57cec5SDimitry Andric   // VALUE_SYMTAB_BLOCK abbrev id's.
1080b57cec5SDimitry Andric   VST_ENTRY_8_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
1090b57cec5SDimitry Andric   VST_ENTRY_7_ABBREV,
1100b57cec5SDimitry Andric   VST_ENTRY_6_ABBREV,
1110b57cec5SDimitry Andric   VST_BBENTRY_6_ABBREV,
1120b57cec5SDimitry Andric 
1130b57cec5SDimitry Andric   // CONSTANTS_BLOCK abbrev id's.
1140b57cec5SDimitry Andric   CONSTANTS_SETTYPE_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
1150b57cec5SDimitry Andric   CONSTANTS_INTEGER_ABBREV,
1160b57cec5SDimitry Andric   CONSTANTS_CE_CAST_Abbrev,
1170b57cec5SDimitry Andric   CONSTANTS_NULL_Abbrev,
1180b57cec5SDimitry Andric 
1190b57cec5SDimitry Andric   // FUNCTION_BLOCK abbrev id's.
1200b57cec5SDimitry Andric   FUNCTION_INST_LOAD_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
1210b57cec5SDimitry Andric   FUNCTION_INST_UNOP_ABBREV,
1220b57cec5SDimitry Andric   FUNCTION_INST_UNOP_FLAGS_ABBREV,
1230b57cec5SDimitry Andric   FUNCTION_INST_BINOP_ABBREV,
1240b57cec5SDimitry Andric   FUNCTION_INST_BINOP_FLAGS_ABBREV,
1250b57cec5SDimitry Andric   FUNCTION_INST_CAST_ABBREV,
126c9157d92SDimitry Andric   FUNCTION_INST_CAST_FLAGS_ABBREV,
1270b57cec5SDimitry Andric   FUNCTION_INST_RET_VOID_ABBREV,
1280b57cec5SDimitry Andric   FUNCTION_INST_RET_VAL_ABBREV,
1290b57cec5SDimitry Andric   FUNCTION_INST_UNREACHABLE_ABBREV,
1300b57cec5SDimitry Andric   FUNCTION_INST_GEP_ABBREV,
1310b57cec5SDimitry Andric };
1320b57cec5SDimitry Andric 
1330b57cec5SDimitry Andric /// Abstract class to manage the bitcode writing, subclassed for each bitcode
1340b57cec5SDimitry Andric /// file type.
1350b57cec5SDimitry Andric class BitcodeWriterBase {
1360b57cec5SDimitry Andric protected:
1370b57cec5SDimitry Andric   /// The stream created and owned by the client.
1380b57cec5SDimitry Andric   BitstreamWriter &Stream;
1390b57cec5SDimitry Andric 
1400b57cec5SDimitry Andric   StringTableBuilder &StrtabBuilder;
1410b57cec5SDimitry Andric 
1420b57cec5SDimitry Andric public:
1430b57cec5SDimitry Andric   /// Constructs a BitcodeWriterBase object that writes to the provided
1440b57cec5SDimitry Andric   /// \p Stream.
BitcodeWriterBase(BitstreamWriter & Stream,StringTableBuilder & StrtabBuilder)1450b57cec5SDimitry Andric   BitcodeWriterBase(BitstreamWriter &Stream, StringTableBuilder &StrtabBuilder)
1460b57cec5SDimitry Andric       : Stream(Stream), StrtabBuilder(StrtabBuilder) {}
1470b57cec5SDimitry Andric 
1480b57cec5SDimitry Andric protected:
1490b57cec5SDimitry Andric   void writeModuleVersion();
1500b57cec5SDimitry Andric };
1510b57cec5SDimitry Andric 
writeModuleVersion()1520b57cec5SDimitry Andric void BitcodeWriterBase::writeModuleVersion() {
1530b57cec5SDimitry Andric   // VERSION: [version#]
1540b57cec5SDimitry Andric   Stream.EmitRecord(bitc::MODULE_CODE_VERSION, ArrayRef<uint64_t>{2});
1550b57cec5SDimitry Andric }
1560b57cec5SDimitry Andric 
1570b57cec5SDimitry Andric /// Base class to manage the module bitcode writing, currently subclassed for
1580b57cec5SDimitry Andric /// ModuleBitcodeWriter and ThinLinkBitcodeWriter.
1590b57cec5SDimitry Andric class ModuleBitcodeWriterBase : public BitcodeWriterBase {
1600b57cec5SDimitry Andric protected:
1610b57cec5SDimitry Andric   /// The Module to write to bitcode.
1620b57cec5SDimitry Andric   const Module &M;
1630b57cec5SDimitry Andric 
1640b57cec5SDimitry Andric   /// Enumerates ids for all values in the module.
1650b57cec5SDimitry Andric   ValueEnumerator VE;
1660b57cec5SDimitry Andric 
1670b57cec5SDimitry Andric   /// Optional per-module index to write for ThinLTO.
1680b57cec5SDimitry Andric   const ModuleSummaryIndex *Index;
1690b57cec5SDimitry Andric 
1700b57cec5SDimitry Andric   /// Map that holds the correspondence between GUIDs in the summary index,
1710b57cec5SDimitry Andric   /// that came from indirect call profiles, and a value id generated by this
1720b57cec5SDimitry Andric   /// class to use in the VST and summary block records.
1730b57cec5SDimitry Andric   std::map<GlobalValue::GUID, unsigned> GUIDToValueIdMap;
1740b57cec5SDimitry Andric 
1750b57cec5SDimitry Andric   /// Tracks the last value id recorded in the GUIDToValueMap.
1760b57cec5SDimitry Andric   unsigned GlobalValueId;
1770b57cec5SDimitry Andric 
1780b57cec5SDimitry Andric   /// Saves the offset of the VSTOffset record that must eventually be
1790b57cec5SDimitry Andric   /// backpatched with the offset of the actual VST.
1800b57cec5SDimitry Andric   uint64_t VSTOffsetPlaceholder = 0;
1810b57cec5SDimitry Andric 
1820b57cec5SDimitry Andric public:
1830b57cec5SDimitry Andric   /// Constructs a ModuleBitcodeWriterBase object for the given Module,
1840b57cec5SDimitry Andric   /// writing to the provided \p Buffer.
ModuleBitcodeWriterBase(const Module & M,StringTableBuilder & StrtabBuilder,BitstreamWriter & Stream,bool ShouldPreserveUseListOrder,const ModuleSummaryIndex * Index)1850b57cec5SDimitry Andric   ModuleBitcodeWriterBase(const Module &M, StringTableBuilder &StrtabBuilder,
1860b57cec5SDimitry Andric                           BitstreamWriter &Stream,
1870b57cec5SDimitry Andric                           bool ShouldPreserveUseListOrder,
1880b57cec5SDimitry Andric                           const ModuleSummaryIndex *Index)
1890b57cec5SDimitry Andric       : BitcodeWriterBase(Stream, StrtabBuilder), M(M),
1900b57cec5SDimitry Andric         VE(M, ShouldPreserveUseListOrder), Index(Index) {
1910b57cec5SDimitry Andric     // Assign ValueIds to any callee values in the index that came from
1920b57cec5SDimitry Andric     // indirect call profiles and were recorded as a GUID not a Value*
1930b57cec5SDimitry Andric     // (which would have been assigned an ID by the ValueEnumerator).
1940b57cec5SDimitry Andric     // The starting ValueId is just after the number of values in the
1950b57cec5SDimitry Andric     // ValueEnumerator, so that they can be emitted in the VST.
1960b57cec5SDimitry Andric     GlobalValueId = VE.getValues().size();
1970b57cec5SDimitry Andric     if (!Index)
1980b57cec5SDimitry Andric       return;
1990b57cec5SDimitry Andric     for (const auto &GUIDSummaryLists : *Index)
2000b57cec5SDimitry Andric       // Examine all summaries for this GUID.
2010b57cec5SDimitry Andric       for (auto &Summary : GUIDSummaryLists.second.SummaryList)
2020b57cec5SDimitry Andric         if (auto FS = dyn_cast<FunctionSummary>(Summary.get()))
2030b57cec5SDimitry Andric           // For each call in the function summary, see if the call
2040b57cec5SDimitry Andric           // is to a GUID (which means it is for an indirect call,
2050b57cec5SDimitry Andric           // otherwise we would have a Value for it). If so, synthesize
2060b57cec5SDimitry Andric           // a value id.
2070b57cec5SDimitry Andric           for (auto &CallEdge : FS->calls())
2080b57cec5SDimitry Andric             if (!CallEdge.first.haveGVs() || !CallEdge.first.getValue())
2090b57cec5SDimitry Andric               assignValueId(CallEdge.first.getGUID());
2100b57cec5SDimitry Andric   }
2110b57cec5SDimitry Andric 
2120b57cec5SDimitry Andric protected:
2130b57cec5SDimitry Andric   void writePerModuleGlobalValueSummary();
2140b57cec5SDimitry Andric 
2150b57cec5SDimitry Andric private:
216bdd1243dSDimitry Andric   void writePerModuleFunctionSummaryRecord(
217bdd1243dSDimitry Andric       SmallVector<uint64_t, 64> &NameVals, GlobalValueSummary *Summary,
218bdd1243dSDimitry Andric       unsigned ValueID, unsigned FSCallsAbbrev, unsigned FSCallsProfileAbbrev,
219bdd1243dSDimitry Andric       unsigned CallsiteAbbrev, unsigned AllocAbbrev, const Function &F);
2200b57cec5SDimitry Andric   void writeModuleLevelReferences(const GlobalVariable &V,
2210b57cec5SDimitry Andric                                   SmallVector<uint64_t, 64> &NameVals,
2220b57cec5SDimitry Andric                                   unsigned FSModRefsAbbrev,
2230b57cec5SDimitry Andric                                   unsigned FSModVTableRefsAbbrev);
2240b57cec5SDimitry Andric 
assignValueId(GlobalValue::GUID ValGUID)2250b57cec5SDimitry Andric   void assignValueId(GlobalValue::GUID ValGUID) {
2260b57cec5SDimitry Andric     GUIDToValueIdMap[ValGUID] = ++GlobalValueId;
2270b57cec5SDimitry Andric   }
2280b57cec5SDimitry Andric 
getValueId(GlobalValue::GUID ValGUID)2290b57cec5SDimitry Andric   unsigned getValueId(GlobalValue::GUID ValGUID) {
2300b57cec5SDimitry Andric     const auto &VMI = GUIDToValueIdMap.find(ValGUID);
2310b57cec5SDimitry Andric     // Expect that any GUID value had a value Id assigned by an
2320b57cec5SDimitry Andric     // earlier call to assignValueId.
2330b57cec5SDimitry Andric     assert(VMI != GUIDToValueIdMap.end() &&
2340b57cec5SDimitry Andric            "GUID does not have assigned value Id");
2350b57cec5SDimitry Andric     return VMI->second;
2360b57cec5SDimitry Andric   }
2370b57cec5SDimitry Andric 
2380b57cec5SDimitry Andric   // Helper to get the valueId for the type of value recorded in VI.
getValueId(ValueInfo VI)2390b57cec5SDimitry Andric   unsigned getValueId(ValueInfo VI) {
2400b57cec5SDimitry Andric     if (!VI.haveGVs() || !VI.getValue())
2410b57cec5SDimitry Andric       return getValueId(VI.getGUID());
2420b57cec5SDimitry Andric     return VE.getValueID(VI.getValue());
2430b57cec5SDimitry Andric   }
2440b57cec5SDimitry Andric 
valueIds()2450b57cec5SDimitry Andric   std::map<GlobalValue::GUID, unsigned> &valueIds() { return GUIDToValueIdMap; }
2460b57cec5SDimitry Andric };
2470b57cec5SDimitry Andric 
2480b57cec5SDimitry Andric /// Class to manage the bitcode writing for a module.
2490b57cec5SDimitry Andric class ModuleBitcodeWriter : public ModuleBitcodeWriterBase {
2500b57cec5SDimitry Andric   /// Pointer to the buffer allocated by caller for bitcode writing.
2510b57cec5SDimitry Andric   const SmallVectorImpl<char> &Buffer;
2520b57cec5SDimitry Andric 
2530b57cec5SDimitry Andric   /// True if a module hash record should be written.
2540b57cec5SDimitry Andric   bool GenerateHash;
2550b57cec5SDimitry Andric 
2560b57cec5SDimitry Andric   /// If non-null, when GenerateHash is true, the resulting hash is written
2570b57cec5SDimitry Andric   /// into ModHash.
2580b57cec5SDimitry Andric   ModuleHash *ModHash;
2590b57cec5SDimitry Andric 
2600b57cec5SDimitry Andric   SHA1 Hasher;
2610b57cec5SDimitry Andric 
2620b57cec5SDimitry Andric   /// The start bit of the identification block.
2630b57cec5SDimitry Andric   uint64_t BitcodeStartBit;
2640b57cec5SDimitry Andric 
2650b57cec5SDimitry Andric public:
2660b57cec5SDimitry Andric   /// Constructs a ModuleBitcodeWriter object for the given Module,
2670b57cec5SDimitry Andric   /// writing to the provided \p Buffer.
ModuleBitcodeWriter(const Module & M,SmallVectorImpl<char> & Buffer,StringTableBuilder & StrtabBuilder,BitstreamWriter & Stream,bool ShouldPreserveUseListOrder,const ModuleSummaryIndex * Index,bool GenerateHash,ModuleHash * ModHash=nullptr)2680b57cec5SDimitry Andric   ModuleBitcodeWriter(const Module &M, SmallVectorImpl<char> &Buffer,
2690b57cec5SDimitry Andric                       StringTableBuilder &StrtabBuilder,
2700b57cec5SDimitry Andric                       BitstreamWriter &Stream, bool ShouldPreserveUseListOrder,
2710b57cec5SDimitry Andric                       const ModuleSummaryIndex *Index, bool GenerateHash,
2720b57cec5SDimitry Andric                       ModuleHash *ModHash = nullptr)
2730b57cec5SDimitry Andric       : ModuleBitcodeWriterBase(M, StrtabBuilder, Stream,
2740b57cec5SDimitry Andric                                 ShouldPreserveUseListOrder, Index),
2750b57cec5SDimitry Andric         Buffer(Buffer), GenerateHash(GenerateHash), ModHash(ModHash),
2760b57cec5SDimitry Andric         BitcodeStartBit(Stream.GetCurrentBitNo()) {}
2770b57cec5SDimitry Andric 
2780b57cec5SDimitry Andric   /// Emit the current module to the bitstream.
2790b57cec5SDimitry Andric   void write();
2800b57cec5SDimitry Andric 
2810b57cec5SDimitry Andric private:
bitcodeStartBit()2820b57cec5SDimitry Andric   uint64_t bitcodeStartBit() { return BitcodeStartBit; }
2830b57cec5SDimitry Andric 
2840b57cec5SDimitry Andric   size_t addToStrtab(StringRef Str);
2850b57cec5SDimitry Andric 
2860b57cec5SDimitry Andric   void writeAttributeGroupTable();
2870b57cec5SDimitry Andric   void writeAttributeTable();
2880b57cec5SDimitry Andric   void writeTypeTable();
2890b57cec5SDimitry Andric   void writeComdats();
2900b57cec5SDimitry Andric   void writeValueSymbolTableForwardDecl();
2910b57cec5SDimitry Andric   void writeModuleInfo();
2920b57cec5SDimitry Andric   void writeValueAsMetadata(const ValueAsMetadata *MD,
2930b57cec5SDimitry Andric                             SmallVectorImpl<uint64_t> &Record);
2940b57cec5SDimitry Andric   void writeMDTuple(const MDTuple *N, SmallVectorImpl<uint64_t> &Record,
2950b57cec5SDimitry Andric                     unsigned Abbrev);
2960b57cec5SDimitry Andric   unsigned createDILocationAbbrev();
2970b57cec5SDimitry Andric   void writeDILocation(const DILocation *N, SmallVectorImpl<uint64_t> &Record,
2980b57cec5SDimitry Andric                        unsigned &Abbrev);
2990b57cec5SDimitry Andric   unsigned createGenericDINodeAbbrev();
3000b57cec5SDimitry Andric   void writeGenericDINode(const GenericDINode *N,
3010b57cec5SDimitry Andric                           SmallVectorImpl<uint64_t> &Record, unsigned &Abbrev);
3020b57cec5SDimitry Andric   void writeDISubrange(const DISubrange *N, SmallVectorImpl<uint64_t> &Record,
3030b57cec5SDimitry Andric                        unsigned Abbrev);
304e8d8bef9SDimitry Andric   void writeDIGenericSubrange(const DIGenericSubrange *N,
305e8d8bef9SDimitry Andric                               SmallVectorImpl<uint64_t> &Record,
306e8d8bef9SDimitry Andric                               unsigned Abbrev);
3070b57cec5SDimitry Andric   void writeDIEnumerator(const DIEnumerator *N,
3080b57cec5SDimitry Andric                          SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
3090b57cec5SDimitry Andric   void writeDIBasicType(const DIBasicType *N, SmallVectorImpl<uint64_t> &Record,
3100b57cec5SDimitry Andric                         unsigned Abbrev);
311e8d8bef9SDimitry Andric   void writeDIStringType(const DIStringType *N,
312e8d8bef9SDimitry Andric                          SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
3130b57cec5SDimitry Andric   void writeDIDerivedType(const DIDerivedType *N,
3140b57cec5SDimitry Andric                           SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
3150b57cec5SDimitry Andric   void writeDICompositeType(const DICompositeType *N,
3160b57cec5SDimitry Andric                             SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
3170b57cec5SDimitry Andric   void writeDISubroutineType(const DISubroutineType *N,
3180b57cec5SDimitry Andric                              SmallVectorImpl<uint64_t> &Record,
3190b57cec5SDimitry Andric                              unsigned Abbrev);
3200b57cec5SDimitry Andric   void writeDIFile(const DIFile *N, SmallVectorImpl<uint64_t> &Record,
3210b57cec5SDimitry Andric                    unsigned Abbrev);
3220b57cec5SDimitry Andric   void writeDICompileUnit(const DICompileUnit *N,
3230b57cec5SDimitry Andric                           SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
3240b57cec5SDimitry Andric   void writeDISubprogram(const DISubprogram *N,
3250b57cec5SDimitry Andric                          SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
3260b57cec5SDimitry Andric   void writeDILexicalBlock(const DILexicalBlock *N,
3270b57cec5SDimitry Andric                            SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
3280b57cec5SDimitry Andric   void writeDILexicalBlockFile(const DILexicalBlockFile *N,
3290b57cec5SDimitry Andric                                SmallVectorImpl<uint64_t> &Record,
3300b57cec5SDimitry Andric                                unsigned Abbrev);
3310b57cec5SDimitry Andric   void writeDICommonBlock(const DICommonBlock *N,
3320b57cec5SDimitry Andric                           SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
3330b57cec5SDimitry Andric   void writeDINamespace(const DINamespace *N, SmallVectorImpl<uint64_t> &Record,
3340b57cec5SDimitry Andric                         unsigned Abbrev);
3350b57cec5SDimitry Andric   void writeDIMacro(const DIMacro *N, SmallVectorImpl<uint64_t> &Record,
3360b57cec5SDimitry Andric                     unsigned Abbrev);
3370b57cec5SDimitry Andric   void writeDIMacroFile(const DIMacroFile *N, SmallVectorImpl<uint64_t> &Record,
3380b57cec5SDimitry Andric                         unsigned Abbrev);
339c9157d92SDimitry Andric   void writeDIArgList(const DIArgList *N, SmallVectorImpl<uint64_t> &Record);
3400b57cec5SDimitry Andric   void writeDIModule(const DIModule *N, SmallVectorImpl<uint64_t> &Record,
3410b57cec5SDimitry Andric                      unsigned Abbrev);
342bdd1243dSDimitry Andric   void writeDIAssignID(const DIAssignID *N, SmallVectorImpl<uint64_t> &Record,
343bdd1243dSDimitry Andric                        unsigned Abbrev);
3440b57cec5SDimitry Andric   void writeDITemplateTypeParameter(const DITemplateTypeParameter *N,
3450b57cec5SDimitry Andric                                     SmallVectorImpl<uint64_t> &Record,
3460b57cec5SDimitry Andric                                     unsigned Abbrev);
3470b57cec5SDimitry Andric   void writeDITemplateValueParameter(const DITemplateValueParameter *N,
3480b57cec5SDimitry Andric                                      SmallVectorImpl<uint64_t> &Record,
3490b57cec5SDimitry Andric                                      unsigned Abbrev);
3500b57cec5SDimitry Andric   void writeDIGlobalVariable(const DIGlobalVariable *N,
3510b57cec5SDimitry Andric                              SmallVectorImpl<uint64_t> &Record,
3520b57cec5SDimitry Andric                              unsigned Abbrev);
3530b57cec5SDimitry Andric   void writeDILocalVariable(const DILocalVariable *N,
3540b57cec5SDimitry Andric                             SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
3550b57cec5SDimitry Andric   void writeDILabel(const DILabel *N,
3560b57cec5SDimitry Andric                     SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
3570b57cec5SDimitry Andric   void writeDIExpression(const DIExpression *N,
3580b57cec5SDimitry Andric                          SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
3590b57cec5SDimitry Andric   void writeDIGlobalVariableExpression(const DIGlobalVariableExpression *N,
3600b57cec5SDimitry Andric                                        SmallVectorImpl<uint64_t> &Record,
3610b57cec5SDimitry Andric                                        unsigned Abbrev);
3620b57cec5SDimitry Andric   void writeDIObjCProperty(const DIObjCProperty *N,
3630b57cec5SDimitry Andric                            SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
3640b57cec5SDimitry Andric   void writeDIImportedEntity(const DIImportedEntity *N,
3650b57cec5SDimitry Andric                              SmallVectorImpl<uint64_t> &Record,
3660b57cec5SDimitry Andric                              unsigned Abbrev);
3670b57cec5SDimitry Andric   unsigned createNamedMetadataAbbrev();
3680b57cec5SDimitry Andric   void writeNamedMetadata(SmallVectorImpl<uint64_t> &Record);
3690b57cec5SDimitry Andric   unsigned createMetadataStringsAbbrev();
3700b57cec5SDimitry Andric   void writeMetadataStrings(ArrayRef<const Metadata *> Strings,
3710b57cec5SDimitry Andric                             SmallVectorImpl<uint64_t> &Record);
3720b57cec5SDimitry Andric   void writeMetadataRecords(ArrayRef<const Metadata *> MDs,
3730b57cec5SDimitry Andric                             SmallVectorImpl<uint64_t> &Record,
3740b57cec5SDimitry Andric                             std::vector<unsigned> *MDAbbrevs = nullptr,
3750b57cec5SDimitry Andric                             std::vector<uint64_t> *IndexPos = nullptr);
3760b57cec5SDimitry Andric   void writeModuleMetadata();
3770b57cec5SDimitry Andric   void writeFunctionMetadata(const Function &F);
3780b57cec5SDimitry Andric   void writeFunctionMetadataAttachment(const Function &F);
3790b57cec5SDimitry Andric   void pushGlobalMetadataAttachment(SmallVectorImpl<uint64_t> &Record,
3800b57cec5SDimitry Andric                                     const GlobalObject &GO);
3810b57cec5SDimitry Andric   void writeModuleMetadataKinds();
3820b57cec5SDimitry Andric   void writeOperandBundleTags();
3830b57cec5SDimitry Andric   void writeSyncScopeNames();
3840b57cec5SDimitry Andric   void writeConstants(unsigned FirstVal, unsigned LastVal, bool isGlobal);
3850b57cec5SDimitry Andric   void writeModuleConstants();
3860b57cec5SDimitry Andric   bool pushValueAndType(const Value *V, unsigned InstID,
3870b57cec5SDimitry Andric                         SmallVectorImpl<unsigned> &Vals);
3885ffd83dbSDimitry Andric   void writeOperandBundles(const CallBase &CB, unsigned InstID);
3890b57cec5SDimitry Andric   void pushValue(const Value *V, unsigned InstID,
3900b57cec5SDimitry Andric                  SmallVectorImpl<unsigned> &Vals);
3910b57cec5SDimitry Andric   void pushValueSigned(const Value *V, unsigned InstID,
3920b57cec5SDimitry Andric                        SmallVectorImpl<uint64_t> &Vals);
3930b57cec5SDimitry Andric   void writeInstruction(const Instruction &I, unsigned InstID,
3940b57cec5SDimitry Andric                         SmallVectorImpl<unsigned> &Vals);
3950b57cec5SDimitry Andric   void writeFunctionLevelValueSymbolTable(const ValueSymbolTable &VST);
3960b57cec5SDimitry Andric   void writeGlobalValueSymbolTable(
3970b57cec5SDimitry Andric       DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex);
3980b57cec5SDimitry Andric   void writeUseList(UseListOrder &&Order);
3990b57cec5SDimitry Andric   void writeUseListBlock(const Function *F);
4000b57cec5SDimitry Andric   void
4010b57cec5SDimitry Andric   writeFunction(const Function &F,
4020b57cec5SDimitry Andric                 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex);
4030b57cec5SDimitry Andric   void writeBlockInfo();
4040b57cec5SDimitry Andric   void writeModuleHash(size_t BlockStartPos);
4050b57cec5SDimitry Andric 
getEncodedSyncScopeID(SyncScope::ID SSID)4060b57cec5SDimitry Andric   unsigned getEncodedSyncScopeID(SyncScope::ID SSID) {
4070b57cec5SDimitry Andric     return unsigned(SSID);
4080b57cec5SDimitry Andric   }
409e8d8bef9SDimitry Andric 
getEncodedAlign(MaybeAlign Alignment)410e8d8bef9SDimitry Andric   unsigned getEncodedAlign(MaybeAlign Alignment) { return encode(Alignment); }
4110b57cec5SDimitry Andric };
4120b57cec5SDimitry Andric 
4130b57cec5SDimitry Andric /// Class to manage the bitcode writing for a combined index.
4140b57cec5SDimitry Andric class IndexBitcodeWriter : public BitcodeWriterBase {
4150b57cec5SDimitry Andric   /// The combined index to write to bitcode.
4160b57cec5SDimitry Andric   const ModuleSummaryIndex &Index;
4170b57cec5SDimitry Andric 
4180b57cec5SDimitry Andric   /// When writing a subset of the index for distributed backends, client
4190b57cec5SDimitry Andric   /// provides a map of modules to the corresponding GUIDs/summaries to write.
4200b57cec5SDimitry Andric   const std::map<std::string, GVSummaryMapTy> *ModuleToSummariesForIndex;
4210b57cec5SDimitry Andric 
4220b57cec5SDimitry Andric   /// Map that holds the correspondence between the GUID used in the combined
4230b57cec5SDimitry Andric   /// index and a value id generated by this class to use in references.
4240b57cec5SDimitry Andric   std::map<GlobalValue::GUID, unsigned> GUIDToValueIdMap;
4250b57cec5SDimitry Andric 
426bdd1243dSDimitry Andric   // The sorted stack id indices actually used in the summary entries being
427bdd1243dSDimitry Andric   // written, which will be a subset of those in the full index in the case of
428bdd1243dSDimitry Andric   // distributed indexes.
429bdd1243dSDimitry Andric   std::vector<unsigned> StackIdIndices;
430bdd1243dSDimitry Andric 
4310b57cec5SDimitry Andric   /// Tracks the last value id recorded in the GUIDToValueMap.
4320b57cec5SDimitry Andric   unsigned GlobalValueId = 0;
4330b57cec5SDimitry Andric 
434c9157d92SDimitry Andric   /// Tracks the assignment of module paths in the module path string table to
435c9157d92SDimitry Andric   /// an id assigned for use in summary references to the module path.
436c9157d92SDimitry Andric   DenseMap<StringRef, uint64_t> ModuleIdMap;
437c9157d92SDimitry Andric 
4380b57cec5SDimitry Andric public:
4390b57cec5SDimitry Andric   /// Constructs a IndexBitcodeWriter object for the given combined index,
4400b57cec5SDimitry Andric   /// writing to the provided \p Buffer. When writing a subset of the index
4410b57cec5SDimitry Andric   /// for a distributed backend, provide a \p ModuleToSummariesForIndex map.
IndexBitcodeWriter(BitstreamWriter & Stream,StringTableBuilder & StrtabBuilder,const ModuleSummaryIndex & Index,const std::map<std::string,GVSummaryMapTy> * ModuleToSummariesForIndex=nullptr)4420b57cec5SDimitry Andric   IndexBitcodeWriter(BitstreamWriter &Stream, StringTableBuilder &StrtabBuilder,
4430b57cec5SDimitry Andric                      const ModuleSummaryIndex &Index,
4440b57cec5SDimitry Andric                      const std::map<std::string, GVSummaryMapTy>
4450b57cec5SDimitry Andric                          *ModuleToSummariesForIndex = nullptr)
4460b57cec5SDimitry Andric       : BitcodeWriterBase(Stream, StrtabBuilder), Index(Index),
4470b57cec5SDimitry Andric         ModuleToSummariesForIndex(ModuleToSummariesForIndex) {
4480b57cec5SDimitry Andric     // Assign unique value ids to all summaries to be written, for use
4490b57cec5SDimitry Andric     // in writing out the call graph edges. Save the mapping from GUID
4500b57cec5SDimitry Andric     // to the new global value id to use when writing those edges, which
4510b57cec5SDimitry Andric     // are currently saved in the index in terms of GUID.
452bdd1243dSDimitry Andric     forEachSummary([&](GVInfo I, bool IsAliasee) {
4530b57cec5SDimitry Andric       GUIDToValueIdMap[I.first] = ++GlobalValueId;
454bdd1243dSDimitry Andric       if (IsAliasee)
455bdd1243dSDimitry Andric         return;
456bdd1243dSDimitry Andric       auto *FS = dyn_cast<FunctionSummary>(I.second);
457bdd1243dSDimitry Andric       if (!FS)
458bdd1243dSDimitry Andric         return;
459bdd1243dSDimitry Andric       // Record all stack id indices actually used in the summary entries being
460bdd1243dSDimitry Andric       // written, so that we can compact them in the case of distributed ThinLTO
461bdd1243dSDimitry Andric       // indexes.
462*6c20abcdSDimitry Andric       for (auto &CI : FS->callsites()) {
463*6c20abcdSDimitry Andric         // If the stack id list is empty, this callsite info was synthesized for
464*6c20abcdSDimitry Andric         // a missing tail call frame. Ensure that the callee's GUID gets a value
465*6c20abcdSDimitry Andric         // id. Normally we only generate these for defined summaries, which in
466*6c20abcdSDimitry Andric         // the case of distributed ThinLTO is only the functions already defined
467*6c20abcdSDimitry Andric         // in the module or that we want to import. We don't bother to include
468*6c20abcdSDimitry Andric         // all the callee symbols as they aren't normally needed in the backend.
469*6c20abcdSDimitry Andric         // However, for the synthesized callsite infos we do need the callee
470*6c20abcdSDimitry Andric         // GUID in the backend so that we can correlate the identified callee
471*6c20abcdSDimitry Andric         // with this callsite info (which for non-tail calls is done by the
472*6c20abcdSDimitry Andric         // ordering of the callsite infos and verified via stack ids).
473*6c20abcdSDimitry Andric         if (CI.StackIdIndices.empty()) {
474*6c20abcdSDimitry Andric           GUIDToValueIdMap[CI.Callee.getGUID()] = ++GlobalValueId;
475*6c20abcdSDimitry Andric           continue;
476*6c20abcdSDimitry Andric         }
477bdd1243dSDimitry Andric         for (auto Idx : CI.StackIdIndices)
478bdd1243dSDimitry Andric           StackIdIndices.push_back(Idx);
479*6c20abcdSDimitry Andric       }
480bdd1243dSDimitry Andric       for (auto &AI : FS->allocs())
481bdd1243dSDimitry Andric         for (auto &MIB : AI.MIBs)
482bdd1243dSDimitry Andric           for (auto Idx : MIB.StackIdIndices)
483bdd1243dSDimitry Andric             StackIdIndices.push_back(Idx);
4840b57cec5SDimitry Andric     });
485bdd1243dSDimitry Andric     llvm::sort(StackIdIndices);
486bdd1243dSDimitry Andric     StackIdIndices.erase(
487bdd1243dSDimitry Andric         std::unique(StackIdIndices.begin(), StackIdIndices.end()),
488bdd1243dSDimitry Andric         StackIdIndices.end());
4890b57cec5SDimitry Andric   }
4900b57cec5SDimitry Andric 
4910b57cec5SDimitry Andric   /// The below iterator returns the GUID and associated summary.
4920b57cec5SDimitry Andric   using GVInfo = std::pair<GlobalValue::GUID, GlobalValueSummary *>;
4930b57cec5SDimitry Andric 
4940b57cec5SDimitry Andric   /// Calls the callback for each value GUID and summary to be written to
4950b57cec5SDimitry Andric   /// bitcode. This hides the details of whether they are being pulled from the
4960b57cec5SDimitry Andric   /// entire index or just those in a provided ModuleToSummariesForIndex map.
4970b57cec5SDimitry Andric   template<typename Functor>
forEachSummary(Functor Callback)4980b57cec5SDimitry Andric   void forEachSummary(Functor Callback) {
4990b57cec5SDimitry Andric     if (ModuleToSummariesForIndex) {
5000b57cec5SDimitry Andric       for (auto &M : *ModuleToSummariesForIndex)
5010b57cec5SDimitry Andric         for (auto &Summary : M.second) {
5020b57cec5SDimitry Andric           Callback(Summary, false);
5030b57cec5SDimitry Andric           // Ensure aliasee is handled, e.g. for assigning a valueId,
5040b57cec5SDimitry Andric           // even if we are not importing the aliasee directly (the
5050b57cec5SDimitry Andric           // imported alias will contain a copy of aliasee).
5060b57cec5SDimitry Andric           if (auto *AS = dyn_cast<AliasSummary>(Summary.getSecond()))
5070b57cec5SDimitry Andric             Callback({AS->getAliaseeGUID(), &AS->getAliasee()}, true);
5080b57cec5SDimitry Andric         }
5090b57cec5SDimitry Andric     } else {
5100b57cec5SDimitry Andric       for (auto &Summaries : Index)
5110b57cec5SDimitry Andric         for (auto &Summary : Summaries.second.SummaryList)
5120b57cec5SDimitry Andric           Callback({Summaries.first, Summary.get()}, false);
5130b57cec5SDimitry Andric     }
5140b57cec5SDimitry Andric   }
5150b57cec5SDimitry Andric 
5160b57cec5SDimitry Andric   /// Calls the callback for each entry in the modulePaths StringMap that
5170b57cec5SDimitry Andric   /// should be written to the module path string table. This hides the details
5180b57cec5SDimitry Andric   /// of whether they are being pulled from the entire index or just those in a
5190b57cec5SDimitry Andric   /// provided ModuleToSummariesForIndex map.
forEachModule(Functor Callback)5200b57cec5SDimitry Andric   template <typename Functor> void forEachModule(Functor Callback) {
5210b57cec5SDimitry Andric     if (ModuleToSummariesForIndex) {
5220b57cec5SDimitry Andric       for (const auto &M : *ModuleToSummariesForIndex) {
5230b57cec5SDimitry Andric         const auto &MPI = Index.modulePaths().find(M.first);
5240b57cec5SDimitry Andric         if (MPI == Index.modulePaths().end()) {
5250b57cec5SDimitry Andric           // This should only happen if the bitcode file was empty, in which
5260b57cec5SDimitry Andric           // case we shouldn't be importing (the ModuleToSummariesForIndex
5270b57cec5SDimitry Andric           // would only include the module we are writing and index for).
5280b57cec5SDimitry Andric           assert(ModuleToSummariesForIndex->size() == 1);
5290b57cec5SDimitry Andric           continue;
5300b57cec5SDimitry Andric         }
5310b57cec5SDimitry Andric         Callback(*MPI);
5320b57cec5SDimitry Andric       }
5330b57cec5SDimitry Andric     } else {
534c9157d92SDimitry Andric       // Since StringMap iteration order isn't guaranteed, order by path string
535c9157d92SDimitry Andric       // first.
536c9157d92SDimitry Andric       // FIXME: Make this a vector of StringMapEntry instead to avoid the later
537c9157d92SDimitry Andric       // map lookup.
538c9157d92SDimitry Andric       std::vector<StringRef> ModulePaths;
539c9157d92SDimitry Andric       for (auto &[ModPath, _] : Index.modulePaths())
540c9157d92SDimitry Andric         ModulePaths.push_back(ModPath);
541c9157d92SDimitry Andric       llvm::sort(ModulePaths.begin(), ModulePaths.end());
542c9157d92SDimitry Andric       for (auto &ModPath : ModulePaths)
543c9157d92SDimitry Andric         Callback(*Index.modulePaths().find(ModPath));
5440b57cec5SDimitry Andric     }
5450b57cec5SDimitry Andric   }
5460b57cec5SDimitry Andric 
5470b57cec5SDimitry Andric   /// Main entry point for writing a combined index to bitcode.
5480b57cec5SDimitry Andric   void write();
5490b57cec5SDimitry Andric 
5500b57cec5SDimitry Andric private:
5510b57cec5SDimitry Andric   void writeModStrings();
5520b57cec5SDimitry Andric   void writeCombinedGlobalValueSummary();
5530b57cec5SDimitry Andric 
getValueId(GlobalValue::GUID ValGUID)554bdd1243dSDimitry Andric   std::optional<unsigned> getValueId(GlobalValue::GUID ValGUID) {
5550b57cec5SDimitry Andric     auto VMI = GUIDToValueIdMap.find(ValGUID);
5560b57cec5SDimitry Andric     if (VMI == GUIDToValueIdMap.end())
557bdd1243dSDimitry Andric       return std::nullopt;
5580b57cec5SDimitry Andric     return VMI->second;
5590b57cec5SDimitry Andric   }
5600b57cec5SDimitry Andric 
valueIds()5610b57cec5SDimitry Andric   std::map<GlobalValue::GUID, unsigned> &valueIds() { return GUIDToValueIdMap; }
5620b57cec5SDimitry Andric };
5630b57cec5SDimitry Andric 
5640b57cec5SDimitry Andric } // end anonymous namespace
5650b57cec5SDimitry Andric 
getEncodedCastOpcode(unsigned Opcode)5660b57cec5SDimitry Andric static unsigned getEncodedCastOpcode(unsigned Opcode) {
5670b57cec5SDimitry Andric   switch (Opcode) {
5680b57cec5SDimitry Andric   default: llvm_unreachable("Unknown cast instruction!");
5690b57cec5SDimitry Andric   case Instruction::Trunc   : return bitc::CAST_TRUNC;
5700b57cec5SDimitry Andric   case Instruction::ZExt    : return bitc::CAST_ZEXT;
5710b57cec5SDimitry Andric   case Instruction::SExt    : return bitc::CAST_SEXT;
5720b57cec5SDimitry Andric   case Instruction::FPToUI  : return bitc::CAST_FPTOUI;
5730b57cec5SDimitry Andric   case Instruction::FPToSI  : return bitc::CAST_FPTOSI;
5740b57cec5SDimitry Andric   case Instruction::UIToFP  : return bitc::CAST_UITOFP;
5750b57cec5SDimitry Andric   case Instruction::SIToFP  : return bitc::CAST_SITOFP;
5760b57cec5SDimitry Andric   case Instruction::FPTrunc : return bitc::CAST_FPTRUNC;
5770b57cec5SDimitry Andric   case Instruction::FPExt   : return bitc::CAST_FPEXT;
5780b57cec5SDimitry Andric   case Instruction::PtrToInt: return bitc::CAST_PTRTOINT;
5790b57cec5SDimitry Andric   case Instruction::IntToPtr: return bitc::CAST_INTTOPTR;
5800b57cec5SDimitry Andric   case Instruction::BitCast : return bitc::CAST_BITCAST;
5810b57cec5SDimitry Andric   case Instruction::AddrSpaceCast: return bitc::CAST_ADDRSPACECAST;
5820b57cec5SDimitry Andric   }
5830b57cec5SDimitry Andric }
5840b57cec5SDimitry Andric 
getEncodedUnaryOpcode(unsigned Opcode)5850b57cec5SDimitry Andric static unsigned getEncodedUnaryOpcode(unsigned Opcode) {
5860b57cec5SDimitry Andric   switch (Opcode) {
5870b57cec5SDimitry Andric   default: llvm_unreachable("Unknown binary instruction!");
5888bcb0991SDimitry Andric   case Instruction::FNeg: return bitc::UNOP_FNEG;
5890b57cec5SDimitry Andric   }
5900b57cec5SDimitry Andric }
5910b57cec5SDimitry Andric 
getEncodedBinaryOpcode(unsigned Opcode)5920b57cec5SDimitry Andric static unsigned getEncodedBinaryOpcode(unsigned Opcode) {
5930b57cec5SDimitry Andric   switch (Opcode) {
5940b57cec5SDimitry Andric   default: llvm_unreachable("Unknown binary instruction!");
5950b57cec5SDimitry Andric   case Instruction::Add:
5960b57cec5SDimitry Andric   case Instruction::FAdd: return bitc::BINOP_ADD;
5970b57cec5SDimitry Andric   case Instruction::Sub:
5980b57cec5SDimitry Andric   case Instruction::FSub: return bitc::BINOP_SUB;
5990b57cec5SDimitry Andric   case Instruction::Mul:
6000b57cec5SDimitry Andric   case Instruction::FMul: return bitc::BINOP_MUL;
6010b57cec5SDimitry Andric   case Instruction::UDiv: return bitc::BINOP_UDIV;
6020b57cec5SDimitry Andric   case Instruction::FDiv:
6030b57cec5SDimitry Andric   case Instruction::SDiv: return bitc::BINOP_SDIV;
6040b57cec5SDimitry Andric   case Instruction::URem: return bitc::BINOP_UREM;
6050b57cec5SDimitry Andric   case Instruction::FRem:
6060b57cec5SDimitry Andric   case Instruction::SRem: return bitc::BINOP_SREM;
6070b57cec5SDimitry Andric   case Instruction::Shl:  return bitc::BINOP_SHL;
6080b57cec5SDimitry Andric   case Instruction::LShr: return bitc::BINOP_LSHR;
6090b57cec5SDimitry Andric   case Instruction::AShr: return bitc::BINOP_ASHR;
6100b57cec5SDimitry Andric   case Instruction::And:  return bitc::BINOP_AND;
6110b57cec5SDimitry Andric   case Instruction::Or:   return bitc::BINOP_OR;
6120b57cec5SDimitry Andric   case Instruction::Xor:  return bitc::BINOP_XOR;
6130b57cec5SDimitry Andric   }
6140b57cec5SDimitry Andric }
6150b57cec5SDimitry Andric 
getEncodedRMWOperation(AtomicRMWInst::BinOp Op)6160b57cec5SDimitry Andric static unsigned getEncodedRMWOperation(AtomicRMWInst::BinOp Op) {
6170b57cec5SDimitry Andric   switch (Op) {
6180b57cec5SDimitry Andric   default: llvm_unreachable("Unknown RMW operation!");
6190b57cec5SDimitry Andric   case AtomicRMWInst::Xchg: return bitc::RMW_XCHG;
6200b57cec5SDimitry Andric   case AtomicRMWInst::Add: return bitc::RMW_ADD;
6210b57cec5SDimitry Andric   case AtomicRMWInst::Sub: return bitc::RMW_SUB;
6220b57cec5SDimitry Andric   case AtomicRMWInst::And: return bitc::RMW_AND;
6230b57cec5SDimitry Andric   case AtomicRMWInst::Nand: return bitc::RMW_NAND;
6240b57cec5SDimitry Andric   case AtomicRMWInst::Or: return bitc::RMW_OR;
6250b57cec5SDimitry Andric   case AtomicRMWInst::Xor: return bitc::RMW_XOR;
6260b57cec5SDimitry Andric   case AtomicRMWInst::Max: return bitc::RMW_MAX;
6270b57cec5SDimitry Andric   case AtomicRMWInst::Min: return bitc::RMW_MIN;
6280b57cec5SDimitry Andric   case AtomicRMWInst::UMax: return bitc::RMW_UMAX;
6290b57cec5SDimitry Andric   case AtomicRMWInst::UMin: return bitc::RMW_UMIN;
6300b57cec5SDimitry Andric   case AtomicRMWInst::FAdd: return bitc::RMW_FADD;
6310b57cec5SDimitry Andric   case AtomicRMWInst::FSub: return bitc::RMW_FSUB;
632753f127fSDimitry Andric   case AtomicRMWInst::FMax: return bitc::RMW_FMAX;
633753f127fSDimitry Andric   case AtomicRMWInst::FMin: return bitc::RMW_FMIN;
634bdd1243dSDimitry Andric   case AtomicRMWInst::UIncWrap:
635bdd1243dSDimitry Andric     return bitc::RMW_UINC_WRAP;
636bdd1243dSDimitry Andric   case AtomicRMWInst::UDecWrap:
637bdd1243dSDimitry Andric     return bitc::RMW_UDEC_WRAP;
6380b57cec5SDimitry Andric   }
6390b57cec5SDimitry Andric }
6400b57cec5SDimitry Andric 
getEncodedOrdering(AtomicOrdering Ordering)6410b57cec5SDimitry Andric static unsigned getEncodedOrdering(AtomicOrdering Ordering) {
6420b57cec5SDimitry Andric   switch (Ordering) {
6430b57cec5SDimitry Andric   case AtomicOrdering::NotAtomic: return bitc::ORDERING_NOTATOMIC;
6440b57cec5SDimitry Andric   case AtomicOrdering::Unordered: return bitc::ORDERING_UNORDERED;
6450b57cec5SDimitry Andric   case AtomicOrdering::Monotonic: return bitc::ORDERING_MONOTONIC;
6460b57cec5SDimitry Andric   case AtomicOrdering::Acquire: return bitc::ORDERING_ACQUIRE;
6470b57cec5SDimitry Andric   case AtomicOrdering::Release: return bitc::ORDERING_RELEASE;
6480b57cec5SDimitry Andric   case AtomicOrdering::AcquireRelease: return bitc::ORDERING_ACQREL;
6490b57cec5SDimitry Andric   case AtomicOrdering::SequentiallyConsistent: return bitc::ORDERING_SEQCST;
6500b57cec5SDimitry Andric   }
6510b57cec5SDimitry Andric   llvm_unreachable("Invalid ordering");
6520b57cec5SDimitry Andric }
6530b57cec5SDimitry Andric 
writeStringRecord(BitstreamWriter & Stream,unsigned Code,StringRef Str,unsigned AbbrevToUse)6540b57cec5SDimitry Andric static void writeStringRecord(BitstreamWriter &Stream, unsigned Code,
6550b57cec5SDimitry Andric                               StringRef Str, unsigned AbbrevToUse) {
6560b57cec5SDimitry Andric   SmallVector<unsigned, 64> Vals;
6570b57cec5SDimitry Andric 
6580b57cec5SDimitry Andric   // Code: [strchar x N]
6594824e7fdSDimitry Andric   for (char C : Str) {
6604824e7fdSDimitry Andric     if (AbbrevToUse && !BitCodeAbbrevOp::isChar6(C))
6610b57cec5SDimitry Andric       AbbrevToUse = 0;
6624824e7fdSDimitry Andric     Vals.push_back(C);
6630b57cec5SDimitry Andric   }
6640b57cec5SDimitry Andric 
6650b57cec5SDimitry Andric   // Emit the finished record.
6660b57cec5SDimitry Andric   Stream.EmitRecord(Code, Vals, AbbrevToUse);
6670b57cec5SDimitry Andric }
6680b57cec5SDimitry Andric 
getAttrKindEncoding(Attribute::AttrKind Kind)6690b57cec5SDimitry Andric static uint64_t getAttrKindEncoding(Attribute::AttrKind Kind) {
6700b57cec5SDimitry Andric   switch (Kind) {
6710b57cec5SDimitry Andric   case Attribute::Alignment:
6720b57cec5SDimitry Andric     return bitc::ATTR_KIND_ALIGNMENT;
67381ad6265SDimitry Andric   case Attribute::AllocAlign:
67481ad6265SDimitry Andric     return bitc::ATTR_KIND_ALLOC_ALIGN;
6750b57cec5SDimitry Andric   case Attribute::AllocSize:
6760b57cec5SDimitry Andric     return bitc::ATTR_KIND_ALLOC_SIZE;
6770b57cec5SDimitry Andric   case Attribute::AlwaysInline:
6780b57cec5SDimitry Andric     return bitc::ATTR_KIND_ALWAYS_INLINE;
6790b57cec5SDimitry Andric   case Attribute::Builtin:
6800b57cec5SDimitry Andric     return bitc::ATTR_KIND_BUILTIN;
6810b57cec5SDimitry Andric   case Attribute::ByVal:
6820b57cec5SDimitry Andric     return bitc::ATTR_KIND_BY_VAL;
6830b57cec5SDimitry Andric   case Attribute::Convergent:
6840b57cec5SDimitry Andric     return bitc::ATTR_KIND_CONVERGENT;
6850b57cec5SDimitry Andric   case Attribute::InAlloca:
6860b57cec5SDimitry Andric     return bitc::ATTR_KIND_IN_ALLOCA;
6870b57cec5SDimitry Andric   case Attribute::Cold:
6880b57cec5SDimitry Andric     return bitc::ATTR_KIND_COLD;
689349cc55cSDimitry Andric   case Attribute::DisableSanitizerInstrumentation:
690349cc55cSDimitry Andric     return bitc::ATTR_KIND_DISABLE_SANITIZER_INSTRUMENTATION;
691753f127fSDimitry Andric   case Attribute::FnRetThunkExtern:
692753f127fSDimitry Andric     return bitc::ATTR_KIND_FNRETTHUNK_EXTERN;
693e8d8bef9SDimitry Andric   case Attribute::Hot:
694e8d8bef9SDimitry Andric     return bitc::ATTR_KIND_HOT;
695fe6060f1SDimitry Andric   case Attribute::ElementType:
696fe6060f1SDimitry Andric     return bitc::ATTR_KIND_ELEMENTTYPE;
6970b57cec5SDimitry Andric   case Attribute::InlineHint:
6980b57cec5SDimitry Andric     return bitc::ATTR_KIND_INLINE_HINT;
6990b57cec5SDimitry Andric   case Attribute::InReg:
7000b57cec5SDimitry Andric     return bitc::ATTR_KIND_IN_REG;
7010b57cec5SDimitry Andric   case Attribute::JumpTable:
7020b57cec5SDimitry Andric     return bitc::ATTR_KIND_JUMP_TABLE;
7030b57cec5SDimitry Andric   case Attribute::MinSize:
7040b57cec5SDimitry Andric     return bitc::ATTR_KIND_MIN_SIZE;
70581ad6265SDimitry Andric   case Attribute::AllocatedPointer:
70681ad6265SDimitry Andric     return bitc::ATTR_KIND_ALLOCATED_POINTER;
70781ad6265SDimitry Andric   case Attribute::AllocKind:
70881ad6265SDimitry Andric     return bitc::ATTR_KIND_ALLOC_KIND;
709bdd1243dSDimitry Andric   case Attribute::Memory:
710bdd1243dSDimitry Andric     return bitc::ATTR_KIND_MEMORY;
711fe013be4SDimitry Andric   case Attribute::NoFPClass:
712fe013be4SDimitry Andric     return bitc::ATTR_KIND_NOFPCLASS;
7130b57cec5SDimitry Andric   case Attribute::Naked:
7140b57cec5SDimitry Andric     return bitc::ATTR_KIND_NAKED;
7150b57cec5SDimitry Andric   case Attribute::Nest:
7160b57cec5SDimitry Andric     return bitc::ATTR_KIND_NEST;
7170b57cec5SDimitry Andric   case Attribute::NoAlias:
7180b57cec5SDimitry Andric     return bitc::ATTR_KIND_NO_ALIAS;
7190b57cec5SDimitry Andric   case Attribute::NoBuiltin:
7200b57cec5SDimitry Andric     return bitc::ATTR_KIND_NO_BUILTIN;
721e8d8bef9SDimitry Andric   case Attribute::NoCallback:
722e8d8bef9SDimitry Andric     return bitc::ATTR_KIND_NO_CALLBACK;
7230b57cec5SDimitry Andric   case Attribute::NoCapture:
7240b57cec5SDimitry Andric     return bitc::ATTR_KIND_NO_CAPTURE;
7250b57cec5SDimitry Andric   case Attribute::NoDuplicate:
7260b57cec5SDimitry Andric     return bitc::ATTR_KIND_NO_DUPLICATE;
7270b57cec5SDimitry Andric   case Attribute::NoFree:
7280b57cec5SDimitry Andric     return bitc::ATTR_KIND_NOFREE;
7290b57cec5SDimitry Andric   case Attribute::NoImplicitFloat:
7300b57cec5SDimitry Andric     return bitc::ATTR_KIND_NO_IMPLICIT_FLOAT;
7310b57cec5SDimitry Andric   case Attribute::NoInline:
7320b57cec5SDimitry Andric     return bitc::ATTR_KIND_NO_INLINE;
7330b57cec5SDimitry Andric   case Attribute::NoRecurse:
7340b57cec5SDimitry Andric     return bitc::ATTR_KIND_NO_RECURSE;
7355ffd83dbSDimitry Andric   case Attribute::NoMerge:
7365ffd83dbSDimitry Andric     return bitc::ATTR_KIND_NO_MERGE;
7370b57cec5SDimitry Andric   case Attribute::NonLazyBind:
7380b57cec5SDimitry Andric     return bitc::ATTR_KIND_NON_LAZY_BIND;
7390b57cec5SDimitry Andric   case Attribute::NonNull:
7400b57cec5SDimitry Andric     return bitc::ATTR_KIND_NON_NULL;
7410b57cec5SDimitry Andric   case Attribute::Dereferenceable:
7420b57cec5SDimitry Andric     return bitc::ATTR_KIND_DEREFERENCEABLE;
7430b57cec5SDimitry Andric   case Attribute::DereferenceableOrNull:
7440b57cec5SDimitry Andric     return bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL;
7450b57cec5SDimitry Andric   case Attribute::NoRedZone:
7460b57cec5SDimitry Andric     return bitc::ATTR_KIND_NO_RED_ZONE;
7470b57cec5SDimitry Andric   case Attribute::NoReturn:
7480b57cec5SDimitry Andric     return bitc::ATTR_KIND_NO_RETURN;
7490b57cec5SDimitry Andric   case Attribute::NoSync:
7500b57cec5SDimitry Andric     return bitc::ATTR_KIND_NOSYNC;
7510b57cec5SDimitry Andric   case Attribute::NoCfCheck:
7520b57cec5SDimitry Andric     return bitc::ATTR_KIND_NOCF_CHECK;
753e8d8bef9SDimitry Andric   case Attribute::NoProfile:
754e8d8bef9SDimitry Andric     return bitc::ATTR_KIND_NO_PROFILE;
755bdd1243dSDimitry Andric   case Attribute::SkipProfile:
756bdd1243dSDimitry Andric     return bitc::ATTR_KIND_SKIP_PROFILE;
7570b57cec5SDimitry Andric   case Attribute::NoUnwind:
7580b57cec5SDimitry Andric     return bitc::ATTR_KIND_NO_UNWIND;
75981ad6265SDimitry Andric   case Attribute::NoSanitizeBounds:
76081ad6265SDimitry Andric     return bitc::ATTR_KIND_NO_SANITIZE_BOUNDS;
761fe6060f1SDimitry Andric   case Attribute::NoSanitizeCoverage:
762fe6060f1SDimitry Andric     return bitc::ATTR_KIND_NO_SANITIZE_COVERAGE;
7635ffd83dbSDimitry Andric   case Attribute::NullPointerIsValid:
7645ffd83dbSDimitry Andric     return bitc::ATTR_KIND_NULL_POINTER_IS_VALID;
765c9157d92SDimitry Andric   case Attribute::OptimizeForDebugging:
766c9157d92SDimitry Andric     return bitc::ATTR_KIND_OPTIMIZE_FOR_DEBUGGING;
7670b57cec5SDimitry Andric   case Attribute::OptForFuzzing:
7680b57cec5SDimitry Andric     return bitc::ATTR_KIND_OPT_FOR_FUZZING;
7690b57cec5SDimitry Andric   case Attribute::OptimizeForSize:
7700b57cec5SDimitry Andric     return bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE;
7710b57cec5SDimitry Andric   case Attribute::OptimizeNone:
7720b57cec5SDimitry Andric     return bitc::ATTR_KIND_OPTIMIZE_NONE;
7730b57cec5SDimitry Andric   case Attribute::ReadNone:
7740b57cec5SDimitry Andric     return bitc::ATTR_KIND_READ_NONE;
7750b57cec5SDimitry Andric   case Attribute::ReadOnly:
7760b57cec5SDimitry Andric     return bitc::ATTR_KIND_READ_ONLY;
7770b57cec5SDimitry Andric   case Attribute::Returned:
7780b57cec5SDimitry Andric     return bitc::ATTR_KIND_RETURNED;
7790b57cec5SDimitry Andric   case Attribute::ReturnsTwice:
7800b57cec5SDimitry Andric     return bitc::ATTR_KIND_RETURNS_TWICE;
7810b57cec5SDimitry Andric   case Attribute::SExt:
7820b57cec5SDimitry Andric     return bitc::ATTR_KIND_S_EXT;
7830b57cec5SDimitry Andric   case Attribute::Speculatable:
7840b57cec5SDimitry Andric     return bitc::ATTR_KIND_SPECULATABLE;
7850b57cec5SDimitry Andric   case Attribute::StackAlignment:
7860b57cec5SDimitry Andric     return bitc::ATTR_KIND_STACK_ALIGNMENT;
7870b57cec5SDimitry Andric   case Attribute::StackProtect:
7880b57cec5SDimitry Andric     return bitc::ATTR_KIND_STACK_PROTECT;
7890b57cec5SDimitry Andric   case Attribute::StackProtectReq:
7900b57cec5SDimitry Andric     return bitc::ATTR_KIND_STACK_PROTECT_REQ;
7910b57cec5SDimitry Andric   case Attribute::StackProtectStrong:
7920b57cec5SDimitry Andric     return bitc::ATTR_KIND_STACK_PROTECT_STRONG;
7930b57cec5SDimitry Andric   case Attribute::SafeStack:
7940b57cec5SDimitry Andric     return bitc::ATTR_KIND_SAFESTACK;
7950b57cec5SDimitry Andric   case Attribute::ShadowCallStack:
7960b57cec5SDimitry Andric     return bitc::ATTR_KIND_SHADOWCALLSTACK;
7970b57cec5SDimitry Andric   case Attribute::StrictFP:
7980b57cec5SDimitry Andric     return bitc::ATTR_KIND_STRICT_FP;
7990b57cec5SDimitry Andric   case Attribute::StructRet:
8000b57cec5SDimitry Andric     return bitc::ATTR_KIND_STRUCT_RET;
8010b57cec5SDimitry Andric   case Attribute::SanitizeAddress:
8020b57cec5SDimitry Andric     return bitc::ATTR_KIND_SANITIZE_ADDRESS;
8030b57cec5SDimitry Andric   case Attribute::SanitizeHWAddress:
8040b57cec5SDimitry Andric     return bitc::ATTR_KIND_SANITIZE_HWADDRESS;
8050b57cec5SDimitry Andric   case Attribute::SanitizeThread:
8060b57cec5SDimitry Andric     return bitc::ATTR_KIND_SANITIZE_THREAD;
8070b57cec5SDimitry Andric   case Attribute::SanitizeMemory:
8080b57cec5SDimitry Andric     return bitc::ATTR_KIND_SANITIZE_MEMORY;
8090b57cec5SDimitry Andric   case Attribute::SpeculativeLoadHardening:
8100b57cec5SDimitry Andric     return bitc::ATTR_KIND_SPECULATIVE_LOAD_HARDENING;
8110b57cec5SDimitry Andric   case Attribute::SwiftError:
8120b57cec5SDimitry Andric     return bitc::ATTR_KIND_SWIFT_ERROR;
8130b57cec5SDimitry Andric   case Attribute::SwiftSelf:
8140b57cec5SDimitry Andric     return bitc::ATTR_KIND_SWIFT_SELF;
815fe6060f1SDimitry Andric   case Attribute::SwiftAsync:
816fe6060f1SDimitry Andric     return bitc::ATTR_KIND_SWIFT_ASYNC;
8170b57cec5SDimitry Andric   case Attribute::UWTable:
8180b57cec5SDimitry Andric     return bitc::ATTR_KIND_UW_TABLE;
819fe6060f1SDimitry Andric   case Attribute::VScaleRange:
820fe6060f1SDimitry Andric     return bitc::ATTR_KIND_VSCALE_RANGE;
8210b57cec5SDimitry Andric   case Attribute::WillReturn:
8220b57cec5SDimitry Andric     return bitc::ATTR_KIND_WILLRETURN;
8230b57cec5SDimitry Andric   case Attribute::WriteOnly:
8240b57cec5SDimitry Andric     return bitc::ATTR_KIND_WRITEONLY;
8250b57cec5SDimitry Andric   case Attribute::ZExt:
8260b57cec5SDimitry Andric     return bitc::ATTR_KIND_Z_EXT;
8270b57cec5SDimitry Andric   case Attribute::ImmArg:
8280b57cec5SDimitry Andric     return bitc::ATTR_KIND_IMMARG;
8290b57cec5SDimitry Andric   case Attribute::SanitizeMemTag:
8300b57cec5SDimitry Andric     return bitc::ATTR_KIND_SANITIZE_MEMTAG;
8315ffd83dbSDimitry Andric   case Attribute::Preallocated:
8325ffd83dbSDimitry Andric     return bitc::ATTR_KIND_PREALLOCATED;
8335ffd83dbSDimitry Andric   case Attribute::NoUndef:
8345ffd83dbSDimitry Andric     return bitc::ATTR_KIND_NOUNDEF;
835e8d8bef9SDimitry Andric   case Attribute::ByRef:
836e8d8bef9SDimitry Andric     return bitc::ATTR_KIND_BYREF;
837e8d8bef9SDimitry Andric   case Attribute::MustProgress:
838e8d8bef9SDimitry Andric     return bitc::ATTR_KIND_MUSTPROGRESS;
83981ad6265SDimitry Andric   case Attribute::PresplitCoroutine:
84081ad6265SDimitry Andric     return bitc::ATTR_KIND_PRESPLIT_COROUTINE;
841c9157d92SDimitry Andric   case Attribute::Writable:
842c9157d92SDimitry Andric     return bitc::ATTR_KIND_WRITABLE;
843c9157d92SDimitry Andric   case Attribute::CoroDestroyOnlyWhenComplete:
844c9157d92SDimitry Andric     return bitc::ATTR_KIND_CORO_ONLY_DESTROY_WHEN_COMPLETE;
845c9157d92SDimitry Andric   case Attribute::DeadOnUnwind:
846c9157d92SDimitry Andric     return bitc::ATTR_KIND_DEAD_ON_UNWIND;
8470b57cec5SDimitry Andric   case Attribute::EndAttrKinds:
8480b57cec5SDimitry Andric     llvm_unreachable("Can not encode end-attribute kinds marker.");
8490b57cec5SDimitry Andric   case Attribute::None:
8500b57cec5SDimitry Andric     llvm_unreachable("Can not encode none-attribute.");
8515ffd83dbSDimitry Andric   case Attribute::EmptyKey:
8525ffd83dbSDimitry Andric   case Attribute::TombstoneKey:
8535ffd83dbSDimitry Andric     llvm_unreachable("Trying to encode EmptyKey/TombstoneKey");
8540b57cec5SDimitry Andric   }
8550b57cec5SDimitry Andric 
8560b57cec5SDimitry Andric   llvm_unreachable("Trying to encode unknown attribute");
8570b57cec5SDimitry Andric }
8580b57cec5SDimitry Andric 
writeAttributeGroupTable()8590b57cec5SDimitry Andric void ModuleBitcodeWriter::writeAttributeGroupTable() {
8600b57cec5SDimitry Andric   const std::vector<ValueEnumerator::IndexAndAttrSet> &AttrGrps =
8610b57cec5SDimitry Andric       VE.getAttributeGroups();
8620b57cec5SDimitry Andric   if (AttrGrps.empty()) return;
8630b57cec5SDimitry Andric 
8640b57cec5SDimitry Andric   Stream.EnterSubblock(bitc::PARAMATTR_GROUP_BLOCK_ID, 3);
8650b57cec5SDimitry Andric 
8660b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
8670b57cec5SDimitry Andric   for (ValueEnumerator::IndexAndAttrSet Pair : AttrGrps) {
8680b57cec5SDimitry Andric     unsigned AttrListIndex = Pair.first;
8690b57cec5SDimitry Andric     AttributeSet AS = Pair.second;
8700b57cec5SDimitry Andric     Record.push_back(VE.getAttributeGroupID(Pair));
8710b57cec5SDimitry Andric     Record.push_back(AttrListIndex);
8720b57cec5SDimitry Andric 
8730b57cec5SDimitry Andric     for (Attribute Attr : AS) {
8740b57cec5SDimitry Andric       if (Attr.isEnumAttribute()) {
8750b57cec5SDimitry Andric         Record.push_back(0);
8760b57cec5SDimitry Andric         Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
8770b57cec5SDimitry Andric       } else if (Attr.isIntAttribute()) {
8780b57cec5SDimitry Andric         Record.push_back(1);
8790b57cec5SDimitry Andric         Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
8800b57cec5SDimitry Andric         Record.push_back(Attr.getValueAsInt());
8810b57cec5SDimitry Andric       } else if (Attr.isStringAttribute()) {
8820b57cec5SDimitry Andric         StringRef Kind = Attr.getKindAsString();
8830b57cec5SDimitry Andric         StringRef Val = Attr.getValueAsString();
8840b57cec5SDimitry Andric 
8850b57cec5SDimitry Andric         Record.push_back(Val.empty() ? 3 : 4);
8860b57cec5SDimitry Andric         Record.append(Kind.begin(), Kind.end());
8870b57cec5SDimitry Andric         Record.push_back(0);
8880b57cec5SDimitry Andric         if (!Val.empty()) {
8890b57cec5SDimitry Andric           Record.append(Val.begin(), Val.end());
8900b57cec5SDimitry Andric           Record.push_back(0);
8910b57cec5SDimitry Andric         }
8920b57cec5SDimitry Andric       } else {
8930b57cec5SDimitry Andric         assert(Attr.isTypeAttribute());
8940b57cec5SDimitry Andric         Type *Ty = Attr.getValueAsType();
8950b57cec5SDimitry Andric         Record.push_back(Ty ? 6 : 5);
8960b57cec5SDimitry Andric         Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
8970b57cec5SDimitry Andric         if (Ty)
8980b57cec5SDimitry Andric           Record.push_back(VE.getTypeID(Attr.getValueAsType()));
8990b57cec5SDimitry Andric       }
9000b57cec5SDimitry Andric     }
9010b57cec5SDimitry Andric 
9020b57cec5SDimitry Andric     Stream.EmitRecord(bitc::PARAMATTR_GRP_CODE_ENTRY, Record);
9030b57cec5SDimitry Andric     Record.clear();
9040b57cec5SDimitry Andric   }
9050b57cec5SDimitry Andric 
9060b57cec5SDimitry Andric   Stream.ExitBlock();
9070b57cec5SDimitry Andric }
9080b57cec5SDimitry Andric 
writeAttributeTable()9090b57cec5SDimitry Andric void ModuleBitcodeWriter::writeAttributeTable() {
9100b57cec5SDimitry Andric   const std::vector<AttributeList> &Attrs = VE.getAttributeLists();
9110b57cec5SDimitry Andric   if (Attrs.empty()) return;
9120b57cec5SDimitry Andric 
9130b57cec5SDimitry Andric   Stream.EnterSubblock(bitc::PARAMATTR_BLOCK_ID, 3);
9140b57cec5SDimitry Andric 
9150b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
9160eae32dcSDimitry Andric   for (const AttributeList &AL : Attrs) {
917349cc55cSDimitry Andric     for (unsigned i : AL.indexes()) {
9180b57cec5SDimitry Andric       AttributeSet AS = AL.getAttributes(i);
9190b57cec5SDimitry Andric       if (AS.hasAttributes())
9200b57cec5SDimitry Andric         Record.push_back(VE.getAttributeGroupID({i, AS}));
9210b57cec5SDimitry Andric     }
9220b57cec5SDimitry Andric 
9230b57cec5SDimitry Andric     Stream.EmitRecord(bitc::PARAMATTR_CODE_ENTRY, Record);
9240b57cec5SDimitry Andric     Record.clear();
9250b57cec5SDimitry Andric   }
9260b57cec5SDimitry Andric 
9270b57cec5SDimitry Andric   Stream.ExitBlock();
9280b57cec5SDimitry Andric }
9290b57cec5SDimitry Andric 
9300b57cec5SDimitry Andric /// WriteTypeTable - Write out the type table for a module.
writeTypeTable()9310b57cec5SDimitry Andric void ModuleBitcodeWriter::writeTypeTable() {
9320b57cec5SDimitry Andric   const ValueEnumerator::TypeList &TypeList = VE.getTypes();
9330b57cec5SDimitry Andric 
9340b57cec5SDimitry Andric   Stream.EnterSubblock(bitc::TYPE_BLOCK_ID_NEW, 4 /*count from # abbrevs */);
9350b57cec5SDimitry Andric   SmallVector<uint64_t, 64> TypeVals;
9360b57cec5SDimitry Andric 
9370b57cec5SDimitry Andric   uint64_t NumBits = VE.computeBitsRequiredForTypeIndicies();
9380b57cec5SDimitry Andric 
939fe6060f1SDimitry Andric   // Abbrev for TYPE_CODE_OPAQUE_POINTER.
940fe013be4SDimitry Andric   auto Abbv = std::make_shared<BitCodeAbbrev>();
941fe6060f1SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_OPAQUE_POINTER));
942fe6060f1SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(0)); // Addrspace = 0
943fe6060f1SDimitry Andric   unsigned OpaquePtrAbbrev = Stream.EmitAbbrev(std::move(Abbv));
944fe6060f1SDimitry Andric 
9450b57cec5SDimitry Andric   // Abbrev for TYPE_CODE_FUNCTION.
9460b57cec5SDimitry Andric   Abbv = std::make_shared<BitCodeAbbrev>();
9470b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_FUNCTION));
9480b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));  // isvararg
9490b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
9500b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
9510b57cec5SDimitry Andric   unsigned FunctionAbbrev = Stream.EmitAbbrev(std::move(Abbv));
9520b57cec5SDimitry Andric 
9530b57cec5SDimitry Andric   // Abbrev for TYPE_CODE_STRUCT_ANON.
9540b57cec5SDimitry Andric   Abbv = std::make_shared<BitCodeAbbrev>();
9550b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_ANON));
9560b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));  // ispacked
9570b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
9580b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
9590b57cec5SDimitry Andric   unsigned StructAnonAbbrev = Stream.EmitAbbrev(std::move(Abbv));
9600b57cec5SDimitry Andric 
9610b57cec5SDimitry Andric   // Abbrev for TYPE_CODE_STRUCT_NAME.
9620b57cec5SDimitry Andric   Abbv = std::make_shared<BitCodeAbbrev>();
9630b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAME));
9640b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
9650b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
9660b57cec5SDimitry Andric   unsigned StructNameAbbrev = Stream.EmitAbbrev(std::move(Abbv));
9670b57cec5SDimitry Andric 
9680b57cec5SDimitry Andric   // Abbrev for TYPE_CODE_STRUCT_NAMED.
9690b57cec5SDimitry Andric   Abbv = std::make_shared<BitCodeAbbrev>();
9700b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAMED));
9710b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));  // ispacked
9720b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
9730b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
9740b57cec5SDimitry Andric   unsigned StructNamedAbbrev = Stream.EmitAbbrev(std::move(Abbv));
9750b57cec5SDimitry Andric 
9760b57cec5SDimitry Andric   // Abbrev for TYPE_CODE_ARRAY.
9770b57cec5SDimitry Andric   Abbv = std::make_shared<BitCodeAbbrev>();
9780b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_ARRAY));
9790b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // size
9800b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
9810b57cec5SDimitry Andric   unsigned ArrayAbbrev = Stream.EmitAbbrev(std::move(Abbv));
9820b57cec5SDimitry Andric 
9830b57cec5SDimitry Andric   // Emit an entry count so the reader can reserve space.
9840b57cec5SDimitry Andric   TypeVals.push_back(TypeList.size());
9850b57cec5SDimitry Andric   Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals);
9860b57cec5SDimitry Andric   TypeVals.clear();
9870b57cec5SDimitry Andric 
9880b57cec5SDimitry Andric   // Loop over all of the types, emitting each in turn.
9894824e7fdSDimitry Andric   for (Type *T : TypeList) {
9900b57cec5SDimitry Andric     int AbbrevToUse = 0;
9910b57cec5SDimitry Andric     unsigned Code = 0;
9920b57cec5SDimitry Andric 
9930b57cec5SDimitry Andric     switch (T->getTypeID()) {
9940b57cec5SDimitry Andric     case Type::VoidTyID:      Code = bitc::TYPE_CODE_VOID;      break;
9950b57cec5SDimitry Andric     case Type::HalfTyID:      Code = bitc::TYPE_CODE_HALF;      break;
9965ffd83dbSDimitry Andric     case Type::BFloatTyID:    Code = bitc::TYPE_CODE_BFLOAT;    break;
9970b57cec5SDimitry Andric     case Type::FloatTyID:     Code = bitc::TYPE_CODE_FLOAT;     break;
9980b57cec5SDimitry Andric     case Type::DoubleTyID:    Code = bitc::TYPE_CODE_DOUBLE;    break;
9990b57cec5SDimitry Andric     case Type::X86_FP80TyID:  Code = bitc::TYPE_CODE_X86_FP80;  break;
10000b57cec5SDimitry Andric     case Type::FP128TyID:     Code = bitc::TYPE_CODE_FP128;     break;
10010b57cec5SDimitry Andric     case Type::PPC_FP128TyID: Code = bitc::TYPE_CODE_PPC_FP128; break;
10020b57cec5SDimitry Andric     case Type::LabelTyID:     Code = bitc::TYPE_CODE_LABEL;     break;
10030b57cec5SDimitry Andric     case Type::MetadataTyID:  Code = bitc::TYPE_CODE_METADATA;  break;
10040b57cec5SDimitry Andric     case Type::X86_MMXTyID:   Code = bitc::TYPE_CODE_X86_MMX;   break;
1005e8d8bef9SDimitry Andric     case Type::X86_AMXTyID:   Code = bitc::TYPE_CODE_X86_AMX;   break;
10060b57cec5SDimitry Andric     case Type::TokenTyID:     Code = bitc::TYPE_CODE_TOKEN;     break;
10070b57cec5SDimitry Andric     case Type::IntegerTyID:
10080b57cec5SDimitry Andric       // INTEGER: [width]
10090b57cec5SDimitry Andric       Code = bitc::TYPE_CODE_INTEGER;
10100b57cec5SDimitry Andric       TypeVals.push_back(cast<IntegerType>(T)->getBitWidth());
10110b57cec5SDimitry Andric       break;
10120b57cec5SDimitry Andric     case Type::PointerTyID: {
10130b57cec5SDimitry Andric       PointerType *PTy = cast<PointerType>(T);
1014fe6060f1SDimitry Andric       unsigned AddressSpace = PTy->getAddressSpace();
1015fe6060f1SDimitry Andric       // OPAQUE_POINTER: [address space]
1016fe6060f1SDimitry Andric       Code = bitc::TYPE_CODE_OPAQUE_POINTER;
1017fe6060f1SDimitry Andric       TypeVals.push_back(AddressSpace);
1018fe6060f1SDimitry Andric       if (AddressSpace == 0)
1019fe6060f1SDimitry Andric         AbbrevToUse = OpaquePtrAbbrev;
10200b57cec5SDimitry Andric       break;
10210b57cec5SDimitry Andric     }
10220b57cec5SDimitry Andric     case Type::FunctionTyID: {
10230b57cec5SDimitry Andric       FunctionType *FT = cast<FunctionType>(T);
10240b57cec5SDimitry Andric       // FUNCTION: [isvararg, retty, paramty x N]
10250b57cec5SDimitry Andric       Code = bitc::TYPE_CODE_FUNCTION;
10260b57cec5SDimitry Andric       TypeVals.push_back(FT->isVarArg());
10270b57cec5SDimitry Andric       TypeVals.push_back(VE.getTypeID(FT->getReturnType()));
10280b57cec5SDimitry Andric       for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
10290b57cec5SDimitry Andric         TypeVals.push_back(VE.getTypeID(FT->getParamType(i)));
10300b57cec5SDimitry Andric       AbbrevToUse = FunctionAbbrev;
10310b57cec5SDimitry Andric       break;
10320b57cec5SDimitry Andric     }
10330b57cec5SDimitry Andric     case Type::StructTyID: {
10340b57cec5SDimitry Andric       StructType *ST = cast<StructType>(T);
10350b57cec5SDimitry Andric       // STRUCT: [ispacked, eltty x N]
10360b57cec5SDimitry Andric       TypeVals.push_back(ST->isPacked());
10370b57cec5SDimitry Andric       // Output all of the element types.
1038349cc55cSDimitry Andric       for (Type *ET : ST->elements())
1039349cc55cSDimitry Andric         TypeVals.push_back(VE.getTypeID(ET));
10400b57cec5SDimitry Andric 
10410b57cec5SDimitry Andric       if (ST->isLiteral()) {
10420b57cec5SDimitry Andric         Code = bitc::TYPE_CODE_STRUCT_ANON;
10430b57cec5SDimitry Andric         AbbrevToUse = StructAnonAbbrev;
10440b57cec5SDimitry Andric       } else {
10450b57cec5SDimitry Andric         if (ST->isOpaque()) {
10460b57cec5SDimitry Andric           Code = bitc::TYPE_CODE_OPAQUE;
10470b57cec5SDimitry Andric         } else {
10480b57cec5SDimitry Andric           Code = bitc::TYPE_CODE_STRUCT_NAMED;
10490b57cec5SDimitry Andric           AbbrevToUse = StructNamedAbbrev;
10500b57cec5SDimitry Andric         }
10510b57cec5SDimitry Andric 
10520b57cec5SDimitry Andric         // Emit the name if it is present.
10530b57cec5SDimitry Andric         if (!ST->getName().empty())
10540b57cec5SDimitry Andric           writeStringRecord(Stream, bitc::TYPE_CODE_STRUCT_NAME, ST->getName(),
10550b57cec5SDimitry Andric                             StructNameAbbrev);
10560b57cec5SDimitry Andric       }
10570b57cec5SDimitry Andric       break;
10580b57cec5SDimitry Andric     }
10590b57cec5SDimitry Andric     case Type::ArrayTyID: {
10600b57cec5SDimitry Andric       ArrayType *AT = cast<ArrayType>(T);
10610b57cec5SDimitry Andric       // ARRAY: [numelts, eltty]
10620b57cec5SDimitry Andric       Code = bitc::TYPE_CODE_ARRAY;
10630b57cec5SDimitry Andric       TypeVals.push_back(AT->getNumElements());
10640b57cec5SDimitry Andric       TypeVals.push_back(VE.getTypeID(AT->getElementType()));
10650b57cec5SDimitry Andric       AbbrevToUse = ArrayAbbrev;
10660b57cec5SDimitry Andric       break;
10670b57cec5SDimitry Andric     }
10685ffd83dbSDimitry Andric     case Type::FixedVectorTyID:
10695ffd83dbSDimitry Andric     case Type::ScalableVectorTyID: {
10700b57cec5SDimitry Andric       VectorType *VT = cast<VectorType>(T);
10710b57cec5SDimitry Andric       // VECTOR [numelts, eltty] or
10720b57cec5SDimitry Andric       //        [numelts, eltty, scalable]
10730b57cec5SDimitry Andric       Code = bitc::TYPE_CODE_VECTOR;
1074e8d8bef9SDimitry Andric       TypeVals.push_back(VT->getElementCount().getKnownMinValue());
10750b57cec5SDimitry Andric       TypeVals.push_back(VE.getTypeID(VT->getElementType()));
10765ffd83dbSDimitry Andric       if (isa<ScalableVectorType>(VT))
10775ffd83dbSDimitry Andric         TypeVals.push_back(true);
10780b57cec5SDimitry Andric       break;
10790b57cec5SDimitry Andric     }
1080bdd1243dSDimitry Andric     case Type::TargetExtTyID: {
1081bdd1243dSDimitry Andric       TargetExtType *TET = cast<TargetExtType>(T);
1082bdd1243dSDimitry Andric       Code = bitc::TYPE_CODE_TARGET_TYPE;
1083bdd1243dSDimitry Andric       writeStringRecord(Stream, bitc::TYPE_CODE_STRUCT_NAME, TET->getName(),
1084bdd1243dSDimitry Andric                         StructNameAbbrev);
1085bdd1243dSDimitry Andric       TypeVals.push_back(TET->getNumTypeParameters());
1086bdd1243dSDimitry Andric       for (Type *InnerTy : TET->type_params())
1087bdd1243dSDimitry Andric         TypeVals.push_back(VE.getTypeID(InnerTy));
1088bdd1243dSDimitry Andric       for (unsigned IntParam : TET->int_params())
1089bdd1243dSDimitry Andric         TypeVals.push_back(IntParam);
1090bdd1243dSDimitry Andric       break;
1091bdd1243dSDimitry Andric     }
1092bdd1243dSDimitry Andric     case Type::TypedPointerTyID:
1093bdd1243dSDimitry Andric       llvm_unreachable("Typed pointers cannot be added to IR modules");
10940b57cec5SDimitry Andric     }
10950b57cec5SDimitry Andric 
10960b57cec5SDimitry Andric     // Emit the finished record.
10970b57cec5SDimitry Andric     Stream.EmitRecord(Code, TypeVals, AbbrevToUse);
10980b57cec5SDimitry Andric     TypeVals.clear();
10990b57cec5SDimitry Andric   }
11000b57cec5SDimitry Andric 
11010b57cec5SDimitry Andric   Stream.ExitBlock();
11020b57cec5SDimitry Andric }
11030b57cec5SDimitry Andric 
getEncodedLinkage(const GlobalValue::LinkageTypes Linkage)11040b57cec5SDimitry Andric static unsigned getEncodedLinkage(const GlobalValue::LinkageTypes Linkage) {
11050b57cec5SDimitry Andric   switch (Linkage) {
11060b57cec5SDimitry Andric   case GlobalValue::ExternalLinkage:
11070b57cec5SDimitry Andric     return 0;
11080b57cec5SDimitry Andric   case GlobalValue::WeakAnyLinkage:
11090b57cec5SDimitry Andric     return 16;
11100b57cec5SDimitry Andric   case GlobalValue::AppendingLinkage:
11110b57cec5SDimitry Andric     return 2;
11120b57cec5SDimitry Andric   case GlobalValue::InternalLinkage:
11130b57cec5SDimitry Andric     return 3;
11140b57cec5SDimitry Andric   case GlobalValue::LinkOnceAnyLinkage:
11150b57cec5SDimitry Andric     return 18;
11160b57cec5SDimitry Andric   case GlobalValue::ExternalWeakLinkage:
11170b57cec5SDimitry Andric     return 7;
11180b57cec5SDimitry Andric   case GlobalValue::CommonLinkage:
11190b57cec5SDimitry Andric     return 8;
11200b57cec5SDimitry Andric   case GlobalValue::PrivateLinkage:
11210b57cec5SDimitry Andric     return 9;
11220b57cec5SDimitry Andric   case GlobalValue::WeakODRLinkage:
11230b57cec5SDimitry Andric     return 17;
11240b57cec5SDimitry Andric   case GlobalValue::LinkOnceODRLinkage:
11250b57cec5SDimitry Andric     return 19;
11260b57cec5SDimitry Andric   case GlobalValue::AvailableExternallyLinkage:
11270b57cec5SDimitry Andric     return 12;
11280b57cec5SDimitry Andric   }
11290b57cec5SDimitry Andric   llvm_unreachable("Invalid linkage");
11300b57cec5SDimitry Andric }
11310b57cec5SDimitry Andric 
getEncodedLinkage(const GlobalValue & GV)11320b57cec5SDimitry Andric static unsigned getEncodedLinkage(const GlobalValue &GV) {
11330b57cec5SDimitry Andric   return getEncodedLinkage(GV.getLinkage());
11340b57cec5SDimitry Andric }
11350b57cec5SDimitry Andric 
getEncodedFFlags(FunctionSummary::FFlags Flags)11360b57cec5SDimitry Andric static uint64_t getEncodedFFlags(FunctionSummary::FFlags Flags) {
11370b57cec5SDimitry Andric   uint64_t RawFlags = 0;
11380b57cec5SDimitry Andric   RawFlags |= Flags.ReadNone;
11390b57cec5SDimitry Andric   RawFlags |= (Flags.ReadOnly << 1);
11400b57cec5SDimitry Andric   RawFlags |= (Flags.NoRecurse << 2);
11410b57cec5SDimitry Andric   RawFlags |= (Flags.ReturnDoesNotAlias << 3);
11420b57cec5SDimitry Andric   RawFlags |= (Flags.NoInline << 4);
1143480093f4SDimitry Andric   RawFlags |= (Flags.AlwaysInline << 5);
1144349cc55cSDimitry Andric   RawFlags |= (Flags.NoUnwind << 6);
1145349cc55cSDimitry Andric   RawFlags |= (Flags.MayThrow << 7);
1146349cc55cSDimitry Andric   RawFlags |= (Flags.HasUnknownCall << 8);
11470eae32dcSDimitry Andric   RawFlags |= (Flags.MustBeUnreachable << 9);
11480b57cec5SDimitry Andric   return RawFlags;
11490b57cec5SDimitry Andric }
11500b57cec5SDimitry Andric 
1151fe6060f1SDimitry Andric // Decode the flags for GlobalValue in the summary. See getDecodedGVSummaryFlags
1152fe6060f1SDimitry Andric // in BitcodeReader.cpp.
getEncodedGVSummaryFlags(GlobalValueSummary::GVFlags Flags)11530b57cec5SDimitry Andric static uint64_t getEncodedGVSummaryFlags(GlobalValueSummary::GVFlags Flags) {
11540b57cec5SDimitry Andric   uint64_t RawFlags = 0;
11550b57cec5SDimitry Andric 
11560b57cec5SDimitry Andric   RawFlags |= Flags.NotEligibleToImport; // bool
11570b57cec5SDimitry Andric   RawFlags |= (Flags.Live << 1);
11580b57cec5SDimitry Andric   RawFlags |= (Flags.DSOLocal << 2);
11590b57cec5SDimitry Andric   RawFlags |= (Flags.CanAutoHide << 3);
11600b57cec5SDimitry Andric 
11610b57cec5SDimitry Andric   // Linkage don't need to be remapped at that time for the summary. Any future
11620b57cec5SDimitry Andric   // change to the getEncodedLinkage() function will need to be taken into
11630b57cec5SDimitry Andric   // account here as well.
11640b57cec5SDimitry Andric   RawFlags = (RawFlags << 4) | Flags.Linkage; // 4 bits
11650b57cec5SDimitry Andric 
1166fe6060f1SDimitry Andric   RawFlags |= (Flags.Visibility << 8); // 2 bits
1167fe6060f1SDimitry Andric 
11680b57cec5SDimitry Andric   return RawFlags;
11690b57cec5SDimitry Andric }
11700b57cec5SDimitry Andric 
getEncodedGVarFlags(GlobalVarSummary::GVarFlags Flags)11710b57cec5SDimitry Andric static uint64_t getEncodedGVarFlags(GlobalVarSummary::GVarFlags Flags) {
11725ffd83dbSDimitry Andric   uint64_t RawFlags = Flags.MaybeReadOnly | (Flags.MaybeWriteOnly << 1) |
11735ffd83dbSDimitry Andric                       (Flags.Constant << 2) | Flags.VCallVisibility << 3;
11740b57cec5SDimitry Andric   return RawFlags;
11750b57cec5SDimitry Andric }
11760b57cec5SDimitry Andric 
getEncodedHotnessCallEdgeInfo(const CalleeInfo & CI)1177c9157d92SDimitry Andric static uint64_t getEncodedHotnessCallEdgeInfo(const CalleeInfo &CI) {
1178c9157d92SDimitry Andric   uint64_t RawFlags = 0;
1179c9157d92SDimitry Andric 
1180c9157d92SDimitry Andric   RawFlags |= CI.Hotness;            // 3 bits
1181c9157d92SDimitry Andric   RawFlags |= (CI.HasTailCall << 3); // 1 bit
1182c9157d92SDimitry Andric 
1183c9157d92SDimitry Andric   return RawFlags;
1184c9157d92SDimitry Andric }
1185c9157d92SDimitry Andric 
getEncodedRelBFCallEdgeInfo(const CalleeInfo & CI)1186c9157d92SDimitry Andric static uint64_t getEncodedRelBFCallEdgeInfo(const CalleeInfo &CI) {
1187c9157d92SDimitry Andric   uint64_t RawFlags = 0;
1188c9157d92SDimitry Andric 
1189c9157d92SDimitry Andric   RawFlags |= CI.RelBlockFreq; // CalleeInfo::RelBlockFreqBits bits
1190c9157d92SDimitry Andric   RawFlags |= (CI.HasTailCall << CalleeInfo::RelBlockFreqBits); // 1 bit
1191c9157d92SDimitry Andric 
1192c9157d92SDimitry Andric   return RawFlags;
1193c9157d92SDimitry Andric }
1194c9157d92SDimitry Andric 
getEncodedVisibility(const GlobalValue & GV)11950b57cec5SDimitry Andric static unsigned getEncodedVisibility(const GlobalValue &GV) {
11960b57cec5SDimitry Andric   switch (GV.getVisibility()) {
11970b57cec5SDimitry Andric   case GlobalValue::DefaultVisibility:   return 0;
11980b57cec5SDimitry Andric   case GlobalValue::HiddenVisibility:    return 1;
11990b57cec5SDimitry Andric   case GlobalValue::ProtectedVisibility: return 2;
12000b57cec5SDimitry Andric   }
12010b57cec5SDimitry Andric   llvm_unreachable("Invalid visibility");
12020b57cec5SDimitry Andric }
12030b57cec5SDimitry Andric 
getEncodedDLLStorageClass(const GlobalValue & GV)12040b57cec5SDimitry Andric static unsigned getEncodedDLLStorageClass(const GlobalValue &GV) {
12050b57cec5SDimitry Andric   switch (GV.getDLLStorageClass()) {
12060b57cec5SDimitry Andric   case GlobalValue::DefaultStorageClass:   return 0;
12070b57cec5SDimitry Andric   case GlobalValue::DLLImportStorageClass: return 1;
12080b57cec5SDimitry Andric   case GlobalValue::DLLExportStorageClass: return 2;
12090b57cec5SDimitry Andric   }
12100b57cec5SDimitry Andric   llvm_unreachable("Invalid DLL storage class");
12110b57cec5SDimitry Andric }
12120b57cec5SDimitry Andric 
getEncodedThreadLocalMode(const GlobalValue & GV)12130b57cec5SDimitry Andric static unsigned getEncodedThreadLocalMode(const GlobalValue &GV) {
12140b57cec5SDimitry Andric   switch (GV.getThreadLocalMode()) {
12150b57cec5SDimitry Andric     case GlobalVariable::NotThreadLocal:         return 0;
12160b57cec5SDimitry Andric     case GlobalVariable::GeneralDynamicTLSModel: return 1;
12170b57cec5SDimitry Andric     case GlobalVariable::LocalDynamicTLSModel:   return 2;
12180b57cec5SDimitry Andric     case GlobalVariable::InitialExecTLSModel:    return 3;
12190b57cec5SDimitry Andric     case GlobalVariable::LocalExecTLSModel:      return 4;
12200b57cec5SDimitry Andric   }
12210b57cec5SDimitry Andric   llvm_unreachable("Invalid TLS model");
12220b57cec5SDimitry Andric }
12230b57cec5SDimitry Andric 
getEncodedComdatSelectionKind(const Comdat & C)12240b57cec5SDimitry Andric static unsigned getEncodedComdatSelectionKind(const Comdat &C) {
12250b57cec5SDimitry Andric   switch (C.getSelectionKind()) {
12260b57cec5SDimitry Andric   case Comdat::Any:
12270b57cec5SDimitry Andric     return bitc::COMDAT_SELECTION_KIND_ANY;
12280b57cec5SDimitry Andric   case Comdat::ExactMatch:
12290b57cec5SDimitry Andric     return bitc::COMDAT_SELECTION_KIND_EXACT_MATCH;
12300b57cec5SDimitry Andric   case Comdat::Largest:
12310b57cec5SDimitry Andric     return bitc::COMDAT_SELECTION_KIND_LARGEST;
1232fe6060f1SDimitry Andric   case Comdat::NoDeduplicate:
12330b57cec5SDimitry Andric     return bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES;
12340b57cec5SDimitry Andric   case Comdat::SameSize:
12350b57cec5SDimitry Andric     return bitc::COMDAT_SELECTION_KIND_SAME_SIZE;
12360b57cec5SDimitry Andric   }
12370b57cec5SDimitry Andric   llvm_unreachable("Invalid selection kind");
12380b57cec5SDimitry Andric }
12390b57cec5SDimitry Andric 
getEncodedUnnamedAddr(const GlobalValue & GV)12400b57cec5SDimitry Andric static unsigned getEncodedUnnamedAddr(const GlobalValue &GV) {
12410b57cec5SDimitry Andric   switch (GV.getUnnamedAddr()) {
12420b57cec5SDimitry Andric   case GlobalValue::UnnamedAddr::None:   return 0;
12430b57cec5SDimitry Andric   case GlobalValue::UnnamedAddr::Local:  return 2;
12440b57cec5SDimitry Andric   case GlobalValue::UnnamedAddr::Global: return 1;
12450b57cec5SDimitry Andric   }
12460b57cec5SDimitry Andric   llvm_unreachable("Invalid unnamed_addr");
12470b57cec5SDimitry Andric }
12480b57cec5SDimitry Andric 
addToStrtab(StringRef Str)12490b57cec5SDimitry Andric size_t ModuleBitcodeWriter::addToStrtab(StringRef Str) {
12500b57cec5SDimitry Andric   if (GenerateHash)
12510b57cec5SDimitry Andric     Hasher.update(Str);
12520b57cec5SDimitry Andric   return StrtabBuilder.add(Str);
12530b57cec5SDimitry Andric }
12540b57cec5SDimitry Andric 
writeComdats()12550b57cec5SDimitry Andric void ModuleBitcodeWriter::writeComdats() {
12560b57cec5SDimitry Andric   SmallVector<unsigned, 64> Vals;
12570b57cec5SDimitry Andric   for (const Comdat *C : VE.getComdats()) {
12580b57cec5SDimitry Andric     // COMDAT: [strtab offset, strtab size, selection_kind]
12590b57cec5SDimitry Andric     Vals.push_back(addToStrtab(C->getName()));
12600b57cec5SDimitry Andric     Vals.push_back(C->getName().size());
12610b57cec5SDimitry Andric     Vals.push_back(getEncodedComdatSelectionKind(*C));
12620b57cec5SDimitry Andric     Stream.EmitRecord(bitc::MODULE_CODE_COMDAT, Vals, /*AbbrevToUse=*/0);
12630b57cec5SDimitry Andric     Vals.clear();
12640b57cec5SDimitry Andric   }
12650b57cec5SDimitry Andric }
12660b57cec5SDimitry Andric 
12670b57cec5SDimitry Andric /// Write a record that will eventually hold the word offset of the
12680b57cec5SDimitry Andric /// module-level VST. For now the offset is 0, which will be backpatched
12690b57cec5SDimitry Andric /// after the real VST is written. Saves the bit offset to backpatch.
writeValueSymbolTableForwardDecl()12700b57cec5SDimitry Andric void ModuleBitcodeWriter::writeValueSymbolTableForwardDecl() {
12710b57cec5SDimitry Andric   // Write a placeholder value in for the offset of the real VST,
12720b57cec5SDimitry Andric   // which is written after the function blocks so that it can include
12730b57cec5SDimitry Andric   // the offset of each function. The placeholder offset will be
12740b57cec5SDimitry Andric   // updated when the real VST is written.
12750b57cec5SDimitry Andric   auto Abbv = std::make_shared<BitCodeAbbrev>();
12760b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_VSTOFFSET));
12770b57cec5SDimitry Andric   // Blocks are 32-bit aligned, so we can use a 32-bit word offset to
12780b57cec5SDimitry Andric   // hold the real VST offset. Must use fixed instead of VBR as we don't
12790b57cec5SDimitry Andric   // know how many VBR chunks to reserve ahead of time.
12800b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
12810b57cec5SDimitry Andric   unsigned VSTOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbv));
12820b57cec5SDimitry Andric 
12830b57cec5SDimitry Andric   // Emit the placeholder
12840b57cec5SDimitry Andric   uint64_t Vals[] = {bitc::MODULE_CODE_VSTOFFSET, 0};
12850b57cec5SDimitry Andric   Stream.EmitRecordWithAbbrev(VSTOffsetAbbrev, Vals);
12860b57cec5SDimitry Andric 
12870b57cec5SDimitry Andric   // Compute and save the bit offset to the placeholder, which will be
12880b57cec5SDimitry Andric   // patched when the real VST is written. We can simply subtract the 32-bit
12890b57cec5SDimitry Andric   // fixed size from the current bit number to get the location to backpatch.
12900b57cec5SDimitry Andric   VSTOffsetPlaceholder = Stream.GetCurrentBitNo() - 32;
12910b57cec5SDimitry Andric }
12920b57cec5SDimitry Andric 
12930b57cec5SDimitry Andric enum StringEncoding { SE_Char6, SE_Fixed7, SE_Fixed8 };
12940b57cec5SDimitry Andric 
12950b57cec5SDimitry Andric /// Determine the encoding to use for the given string name and length.
getStringEncoding(StringRef Str)12960b57cec5SDimitry Andric static StringEncoding getStringEncoding(StringRef Str) {
12970b57cec5SDimitry Andric   bool isChar6 = true;
12980b57cec5SDimitry Andric   for (char C : Str) {
12990b57cec5SDimitry Andric     if (isChar6)
13000b57cec5SDimitry Andric       isChar6 = BitCodeAbbrevOp::isChar6(C);
13010b57cec5SDimitry Andric     if ((unsigned char)C & 128)
13020b57cec5SDimitry Andric       // don't bother scanning the rest.
13030b57cec5SDimitry Andric       return SE_Fixed8;
13040b57cec5SDimitry Andric   }
13050b57cec5SDimitry Andric   if (isChar6)
13060b57cec5SDimitry Andric     return SE_Char6;
13070b57cec5SDimitry Andric   return SE_Fixed7;
13080b57cec5SDimitry Andric }
13090b57cec5SDimitry Andric 
131081ad6265SDimitry Andric static_assert(sizeof(GlobalValue::SanitizerMetadata) <= sizeof(unsigned),
131181ad6265SDimitry Andric               "Sanitizer Metadata is too large for naive serialization.");
131281ad6265SDimitry Andric static unsigned
serializeSanitizerMetadata(const GlobalValue::SanitizerMetadata & Meta)131381ad6265SDimitry Andric serializeSanitizerMetadata(const GlobalValue::SanitizerMetadata &Meta) {
131481ad6265SDimitry Andric   return Meta.NoAddress | (Meta.NoHWAddress << 1) |
1315753f127fSDimitry Andric          (Meta.Memtag << 2) | (Meta.IsDynInit << 3);
131681ad6265SDimitry Andric }
131781ad6265SDimitry Andric 
13180b57cec5SDimitry Andric /// Emit top-level description of module, including target triple, inline asm,
13190b57cec5SDimitry Andric /// descriptors for global variables, and function prototype info.
13200b57cec5SDimitry Andric /// Returns the bit offset to backpatch with the location of the real VST.
writeModuleInfo()13210b57cec5SDimitry Andric void ModuleBitcodeWriter::writeModuleInfo() {
13220b57cec5SDimitry Andric   // Emit various pieces of data attached to a module.
13230b57cec5SDimitry Andric   if (!M.getTargetTriple().empty())
13240b57cec5SDimitry Andric     writeStringRecord(Stream, bitc::MODULE_CODE_TRIPLE, M.getTargetTriple(),
13250b57cec5SDimitry Andric                       0 /*TODO*/);
13260b57cec5SDimitry Andric   const std::string &DL = M.getDataLayoutStr();
13270b57cec5SDimitry Andric   if (!DL.empty())
13280b57cec5SDimitry Andric     writeStringRecord(Stream, bitc::MODULE_CODE_DATALAYOUT, DL, 0 /*TODO*/);
13290b57cec5SDimitry Andric   if (!M.getModuleInlineAsm().empty())
13300b57cec5SDimitry Andric     writeStringRecord(Stream, bitc::MODULE_CODE_ASM, M.getModuleInlineAsm(),
13310b57cec5SDimitry Andric                       0 /*TODO*/);
13320b57cec5SDimitry Andric 
13330b57cec5SDimitry Andric   // Emit information about sections and GC, computing how many there are. Also
13340b57cec5SDimitry Andric   // compute the maximum alignment value.
13350b57cec5SDimitry Andric   std::map<std::string, unsigned> SectionMap;
13360b57cec5SDimitry Andric   std::map<std::string, unsigned> GCMap;
1337e8d8bef9SDimitry Andric   MaybeAlign MaxAlignment;
13380b57cec5SDimitry Andric   unsigned MaxGlobalType = 0;
1339e8d8bef9SDimitry Andric   const auto UpdateMaxAlignment = [&MaxAlignment](const MaybeAlign A) {
1340e8d8bef9SDimitry Andric     if (A)
1341e8d8bef9SDimitry Andric       MaxAlignment = !MaxAlignment ? *A : std::max(*MaxAlignment, *A);
1342e8d8bef9SDimitry Andric   };
13435ffd83dbSDimitry Andric   for (const GlobalVariable &GV : M.globals()) {
1344e8d8bef9SDimitry Andric     UpdateMaxAlignment(GV.getAlign());
13450b57cec5SDimitry Andric     MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV.getValueType()));
13460b57cec5SDimitry Andric     if (GV.hasSection()) {
13470b57cec5SDimitry Andric       // Give section names unique ID's.
13485ffd83dbSDimitry Andric       unsigned &Entry = SectionMap[std::string(GV.getSection())];
13490b57cec5SDimitry Andric       if (!Entry) {
13500b57cec5SDimitry Andric         writeStringRecord(Stream, bitc::MODULE_CODE_SECTIONNAME, GV.getSection(),
13510b57cec5SDimitry Andric                           0 /*TODO*/);
13520b57cec5SDimitry Andric         Entry = SectionMap.size();
13530b57cec5SDimitry Andric       }
13540b57cec5SDimitry Andric     }
13550b57cec5SDimitry Andric   }
13560b57cec5SDimitry Andric   for (const Function &F : M) {
1357e8d8bef9SDimitry Andric     UpdateMaxAlignment(F.getAlign());
13580b57cec5SDimitry Andric     if (F.hasSection()) {
13590b57cec5SDimitry Andric       // Give section names unique ID's.
13605ffd83dbSDimitry Andric       unsigned &Entry = SectionMap[std::string(F.getSection())];
13610b57cec5SDimitry Andric       if (!Entry) {
13620b57cec5SDimitry Andric         writeStringRecord(Stream, bitc::MODULE_CODE_SECTIONNAME, F.getSection(),
13630b57cec5SDimitry Andric                           0 /*TODO*/);
13640b57cec5SDimitry Andric         Entry = SectionMap.size();
13650b57cec5SDimitry Andric       }
13660b57cec5SDimitry Andric     }
13670b57cec5SDimitry Andric     if (F.hasGC()) {
13680b57cec5SDimitry Andric       // Same for GC names.
13690b57cec5SDimitry Andric       unsigned &Entry = GCMap[F.getGC()];
13700b57cec5SDimitry Andric       if (!Entry) {
13710b57cec5SDimitry Andric         writeStringRecord(Stream, bitc::MODULE_CODE_GCNAME, F.getGC(),
13720b57cec5SDimitry Andric                           0 /*TODO*/);
13730b57cec5SDimitry Andric         Entry = GCMap.size();
13740b57cec5SDimitry Andric       }
13750b57cec5SDimitry Andric     }
13760b57cec5SDimitry Andric   }
13770b57cec5SDimitry Andric 
13780b57cec5SDimitry Andric   // Emit abbrev for globals, now that we know # sections and max alignment.
13790b57cec5SDimitry Andric   unsigned SimpleGVarAbbrev = 0;
13800b57cec5SDimitry Andric   if (!M.global_empty()) {
13810b57cec5SDimitry Andric     // Add an abbrev for common globals with no visibility or thread localness.
13820b57cec5SDimitry Andric     auto Abbv = std::make_shared<BitCodeAbbrev>();
13830b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GLOBALVAR));
13840b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
13850b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
13860b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
13870b57cec5SDimitry Andric                               Log2_32_Ceil(MaxGlobalType+1)));
13880b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // AddrSpace << 2
13890b57cec5SDimitry Andric                                                            //| explicitType << 1
13900b57cec5SDimitry Andric                                                            //| constant
13910b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // Initializer.
13920b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5)); // Linkage.
1393e8d8bef9SDimitry Andric     if (!MaxAlignment)                                     // Alignment.
13940b57cec5SDimitry Andric       Abbv->Add(BitCodeAbbrevOp(0));
13950b57cec5SDimitry Andric     else {
1396e8d8bef9SDimitry Andric       unsigned MaxEncAlignment = getEncodedAlign(MaxAlignment);
13970b57cec5SDimitry Andric       Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
13980b57cec5SDimitry Andric                                Log2_32_Ceil(MaxEncAlignment+1)));
13990b57cec5SDimitry Andric     }
14000b57cec5SDimitry Andric     if (SectionMap.empty())                                    // Section.
14010b57cec5SDimitry Andric       Abbv->Add(BitCodeAbbrevOp(0));
14020b57cec5SDimitry Andric     else
14030b57cec5SDimitry Andric       Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
14040b57cec5SDimitry Andric                                Log2_32_Ceil(SectionMap.size()+1)));
14050b57cec5SDimitry Andric     // Don't bother emitting vis + thread local.
14060b57cec5SDimitry Andric     SimpleGVarAbbrev = Stream.EmitAbbrev(std::move(Abbv));
14070b57cec5SDimitry Andric   }
14080b57cec5SDimitry Andric 
14090b57cec5SDimitry Andric   SmallVector<unsigned, 64> Vals;
14100b57cec5SDimitry Andric   // Emit the module's source file name.
14110b57cec5SDimitry Andric   {
14120b57cec5SDimitry Andric     StringEncoding Bits = getStringEncoding(M.getSourceFileName());
14130b57cec5SDimitry Andric     BitCodeAbbrevOp AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8);
14140b57cec5SDimitry Andric     if (Bits == SE_Char6)
14150b57cec5SDimitry Andric       AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Char6);
14160b57cec5SDimitry Andric     else if (Bits == SE_Fixed7)
14170b57cec5SDimitry Andric       AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7);
14180b57cec5SDimitry Andric 
14190b57cec5SDimitry Andric     // MODULE_CODE_SOURCE_FILENAME: [namechar x N]
14200b57cec5SDimitry Andric     auto Abbv = std::make_shared<BitCodeAbbrev>();
14210b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_SOURCE_FILENAME));
14220b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
14230b57cec5SDimitry Andric     Abbv->Add(AbbrevOpToUse);
14240b57cec5SDimitry Andric     unsigned FilenameAbbrev = Stream.EmitAbbrev(std::move(Abbv));
14250b57cec5SDimitry Andric 
14260b57cec5SDimitry Andric     for (const auto P : M.getSourceFileName())
14270b57cec5SDimitry Andric       Vals.push_back((unsigned char)P);
14280b57cec5SDimitry Andric 
14290b57cec5SDimitry Andric     // Emit the finished record.
14300b57cec5SDimitry Andric     Stream.EmitRecord(bitc::MODULE_CODE_SOURCE_FILENAME, Vals, FilenameAbbrev);
14310b57cec5SDimitry Andric     Vals.clear();
14320b57cec5SDimitry Andric   }
14330b57cec5SDimitry Andric 
14340b57cec5SDimitry Andric   // Emit the global variable information.
14350b57cec5SDimitry Andric   for (const GlobalVariable &GV : M.globals()) {
14360b57cec5SDimitry Andric     unsigned AbbrevToUse = 0;
14370b57cec5SDimitry Andric 
14380b57cec5SDimitry Andric     // GLOBALVAR: [strtab offset, strtab size, type, isconst, initid,
14390b57cec5SDimitry Andric     //             linkage, alignment, section, visibility, threadlocal,
14400b57cec5SDimitry Andric     //             unnamed_addr, externally_initialized, dllstorageclass,
1441c9157d92SDimitry Andric     //             comdat, attributes, DSO_Local, GlobalSanitizer, code_model]
14420b57cec5SDimitry Andric     Vals.push_back(addToStrtab(GV.getName()));
14430b57cec5SDimitry Andric     Vals.push_back(GV.getName().size());
14440b57cec5SDimitry Andric     Vals.push_back(VE.getTypeID(GV.getValueType()));
14450b57cec5SDimitry Andric     Vals.push_back(GV.getType()->getAddressSpace() << 2 | 2 | GV.isConstant());
14460b57cec5SDimitry Andric     Vals.push_back(GV.isDeclaration() ? 0 :
14470b57cec5SDimitry Andric                    (VE.getValueID(GV.getInitializer()) + 1));
14480b57cec5SDimitry Andric     Vals.push_back(getEncodedLinkage(GV));
1449e8d8bef9SDimitry Andric     Vals.push_back(getEncodedAlign(GV.getAlign()));
14505ffd83dbSDimitry Andric     Vals.push_back(GV.hasSection() ? SectionMap[std::string(GV.getSection())]
14515ffd83dbSDimitry Andric                                    : 0);
14520b57cec5SDimitry Andric     if (GV.isThreadLocal() ||
14530b57cec5SDimitry Andric         GV.getVisibility() != GlobalValue::DefaultVisibility ||
14540b57cec5SDimitry Andric         GV.getUnnamedAddr() != GlobalValue::UnnamedAddr::None ||
14550b57cec5SDimitry Andric         GV.isExternallyInitialized() ||
14560b57cec5SDimitry Andric         GV.getDLLStorageClass() != GlobalValue::DefaultStorageClass ||
145781ad6265SDimitry Andric         GV.hasComdat() || GV.hasAttributes() || GV.isDSOLocal() ||
1458c9157d92SDimitry Andric         GV.hasPartition() || GV.hasSanitizerMetadata() || GV.getCodeModel()) {
14590b57cec5SDimitry Andric       Vals.push_back(getEncodedVisibility(GV));
14600b57cec5SDimitry Andric       Vals.push_back(getEncodedThreadLocalMode(GV));
14610b57cec5SDimitry Andric       Vals.push_back(getEncodedUnnamedAddr(GV));
14620b57cec5SDimitry Andric       Vals.push_back(GV.isExternallyInitialized());
14630b57cec5SDimitry Andric       Vals.push_back(getEncodedDLLStorageClass(GV));
14640b57cec5SDimitry Andric       Vals.push_back(GV.hasComdat() ? VE.getComdatID(GV.getComdat()) : 0);
14650b57cec5SDimitry Andric 
14660b57cec5SDimitry Andric       auto AL = GV.getAttributesAsList(AttributeList::FunctionIndex);
14670b57cec5SDimitry Andric       Vals.push_back(VE.getAttributeListID(AL));
14680b57cec5SDimitry Andric 
14690b57cec5SDimitry Andric       Vals.push_back(GV.isDSOLocal());
14700b57cec5SDimitry Andric       Vals.push_back(addToStrtab(GV.getPartition()));
14710b57cec5SDimitry Andric       Vals.push_back(GV.getPartition().size());
147281ad6265SDimitry Andric 
147381ad6265SDimitry Andric       Vals.push_back((GV.hasSanitizerMetadata() ? serializeSanitizerMetadata(
147481ad6265SDimitry Andric                                                       GV.getSanitizerMetadata())
147581ad6265SDimitry Andric                                                 : 0));
1476c9157d92SDimitry Andric       Vals.push_back(GV.getCodeModelRaw());
14770b57cec5SDimitry Andric     } else {
14780b57cec5SDimitry Andric       AbbrevToUse = SimpleGVarAbbrev;
14790b57cec5SDimitry Andric     }
14800b57cec5SDimitry Andric 
14810b57cec5SDimitry Andric     Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse);
14820b57cec5SDimitry Andric     Vals.clear();
14830b57cec5SDimitry Andric   }
14840b57cec5SDimitry Andric 
14850b57cec5SDimitry Andric   // Emit the function proto information.
14860b57cec5SDimitry Andric   for (const Function &F : M) {
14870b57cec5SDimitry Andric     // FUNCTION:  [strtab offset, strtab size, type, callingconv, isproto,
14880b57cec5SDimitry Andric     //             linkage, paramattrs, alignment, section, visibility, gc,
14890b57cec5SDimitry Andric     //             unnamed_addr, prologuedata, dllstorageclass, comdat,
14900b57cec5SDimitry Andric     //             prefixdata, personalityfn, DSO_Local, addrspace]
14910b57cec5SDimitry Andric     Vals.push_back(addToStrtab(F.getName()));
14920b57cec5SDimitry Andric     Vals.push_back(F.getName().size());
14930b57cec5SDimitry Andric     Vals.push_back(VE.getTypeID(F.getFunctionType()));
14940b57cec5SDimitry Andric     Vals.push_back(F.getCallingConv());
14950b57cec5SDimitry Andric     Vals.push_back(F.isDeclaration());
14960b57cec5SDimitry Andric     Vals.push_back(getEncodedLinkage(F));
14970b57cec5SDimitry Andric     Vals.push_back(VE.getAttributeListID(F.getAttributes()));
1498e8d8bef9SDimitry Andric     Vals.push_back(getEncodedAlign(F.getAlign()));
14995ffd83dbSDimitry Andric     Vals.push_back(F.hasSection() ? SectionMap[std::string(F.getSection())]
15005ffd83dbSDimitry Andric                                   : 0);
15010b57cec5SDimitry Andric     Vals.push_back(getEncodedVisibility(F));
15020b57cec5SDimitry Andric     Vals.push_back(F.hasGC() ? GCMap[F.getGC()] : 0);
15030b57cec5SDimitry Andric     Vals.push_back(getEncodedUnnamedAddr(F));
15040b57cec5SDimitry Andric     Vals.push_back(F.hasPrologueData() ? (VE.getValueID(F.getPrologueData()) + 1)
15050b57cec5SDimitry Andric                                        : 0);
15060b57cec5SDimitry Andric     Vals.push_back(getEncodedDLLStorageClass(F));
15070b57cec5SDimitry Andric     Vals.push_back(F.hasComdat() ? VE.getComdatID(F.getComdat()) : 0);
15080b57cec5SDimitry Andric     Vals.push_back(F.hasPrefixData() ? (VE.getValueID(F.getPrefixData()) + 1)
15090b57cec5SDimitry Andric                                      : 0);
15100b57cec5SDimitry Andric     Vals.push_back(
15110b57cec5SDimitry Andric         F.hasPersonalityFn() ? (VE.getValueID(F.getPersonalityFn()) + 1) : 0);
15120b57cec5SDimitry Andric 
15130b57cec5SDimitry Andric     Vals.push_back(F.isDSOLocal());
15140b57cec5SDimitry Andric     Vals.push_back(F.getAddressSpace());
15150b57cec5SDimitry Andric     Vals.push_back(addToStrtab(F.getPartition()));
15160b57cec5SDimitry Andric     Vals.push_back(F.getPartition().size());
15170b57cec5SDimitry Andric 
15180b57cec5SDimitry Andric     unsigned AbbrevToUse = 0;
15190b57cec5SDimitry Andric     Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse);
15200b57cec5SDimitry Andric     Vals.clear();
15210b57cec5SDimitry Andric   }
15220b57cec5SDimitry Andric 
15230b57cec5SDimitry Andric   // Emit the alias information.
15240b57cec5SDimitry Andric   for (const GlobalAlias &A : M.aliases()) {
15250b57cec5SDimitry Andric     // ALIAS: [strtab offset, strtab size, alias type, aliasee val#, linkage,
15260b57cec5SDimitry Andric     //         visibility, dllstorageclass, threadlocal, unnamed_addr,
15270b57cec5SDimitry Andric     //         DSO_Local]
15280b57cec5SDimitry Andric     Vals.push_back(addToStrtab(A.getName()));
15290b57cec5SDimitry Andric     Vals.push_back(A.getName().size());
15300b57cec5SDimitry Andric     Vals.push_back(VE.getTypeID(A.getValueType()));
15310b57cec5SDimitry Andric     Vals.push_back(A.getType()->getAddressSpace());
15320b57cec5SDimitry Andric     Vals.push_back(VE.getValueID(A.getAliasee()));
15330b57cec5SDimitry Andric     Vals.push_back(getEncodedLinkage(A));
15340b57cec5SDimitry Andric     Vals.push_back(getEncodedVisibility(A));
15350b57cec5SDimitry Andric     Vals.push_back(getEncodedDLLStorageClass(A));
15360b57cec5SDimitry Andric     Vals.push_back(getEncodedThreadLocalMode(A));
15370b57cec5SDimitry Andric     Vals.push_back(getEncodedUnnamedAddr(A));
15380b57cec5SDimitry Andric     Vals.push_back(A.isDSOLocal());
15390b57cec5SDimitry Andric     Vals.push_back(addToStrtab(A.getPartition()));
15400b57cec5SDimitry Andric     Vals.push_back(A.getPartition().size());
15410b57cec5SDimitry Andric 
15420b57cec5SDimitry Andric     unsigned AbbrevToUse = 0;
15430b57cec5SDimitry Andric     Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse);
15440b57cec5SDimitry Andric     Vals.clear();
15450b57cec5SDimitry Andric   }
15460b57cec5SDimitry Andric 
15470b57cec5SDimitry Andric   // Emit the ifunc information.
15480b57cec5SDimitry Andric   for (const GlobalIFunc &I : M.ifuncs()) {
15490b57cec5SDimitry Andric     // IFUNC: [strtab offset, strtab size, ifunc type, address space, resolver
15500b57cec5SDimitry Andric     //         val#, linkage, visibility, DSO_Local]
15510b57cec5SDimitry Andric     Vals.push_back(addToStrtab(I.getName()));
15520b57cec5SDimitry Andric     Vals.push_back(I.getName().size());
15530b57cec5SDimitry Andric     Vals.push_back(VE.getTypeID(I.getValueType()));
15540b57cec5SDimitry Andric     Vals.push_back(I.getType()->getAddressSpace());
15550b57cec5SDimitry Andric     Vals.push_back(VE.getValueID(I.getResolver()));
15560b57cec5SDimitry Andric     Vals.push_back(getEncodedLinkage(I));
15570b57cec5SDimitry Andric     Vals.push_back(getEncodedVisibility(I));
15580b57cec5SDimitry Andric     Vals.push_back(I.isDSOLocal());
15590b57cec5SDimitry Andric     Vals.push_back(addToStrtab(I.getPartition()));
15600b57cec5SDimitry Andric     Vals.push_back(I.getPartition().size());
15610b57cec5SDimitry Andric     Stream.EmitRecord(bitc::MODULE_CODE_IFUNC, Vals);
15620b57cec5SDimitry Andric     Vals.clear();
15630b57cec5SDimitry Andric   }
15640b57cec5SDimitry Andric 
15650b57cec5SDimitry Andric   writeValueSymbolTableForwardDecl();
15660b57cec5SDimitry Andric }
15670b57cec5SDimitry Andric 
getOptimizationFlags(const Value * V)15680b57cec5SDimitry Andric static uint64_t getOptimizationFlags(const Value *V) {
15690b57cec5SDimitry Andric   uint64_t Flags = 0;
15700b57cec5SDimitry Andric 
15710b57cec5SDimitry Andric   if (const auto *OBO = dyn_cast<OverflowingBinaryOperator>(V)) {
15720b57cec5SDimitry Andric     if (OBO->hasNoSignedWrap())
15730b57cec5SDimitry Andric       Flags |= 1 << bitc::OBO_NO_SIGNED_WRAP;
15740b57cec5SDimitry Andric     if (OBO->hasNoUnsignedWrap())
15750b57cec5SDimitry Andric       Flags |= 1 << bitc::OBO_NO_UNSIGNED_WRAP;
15760b57cec5SDimitry Andric   } else if (const auto *PEO = dyn_cast<PossiblyExactOperator>(V)) {
15770b57cec5SDimitry Andric     if (PEO->isExact())
15780b57cec5SDimitry Andric       Flags |= 1 << bitc::PEO_EXACT;
1579c9157d92SDimitry Andric   } else if (const auto *PDI = dyn_cast<PossiblyDisjointInst>(V)) {
1580c9157d92SDimitry Andric     if (PDI->isDisjoint())
1581c9157d92SDimitry Andric       Flags |= 1 << bitc::PDI_DISJOINT;
15820b57cec5SDimitry Andric   } else if (const auto *FPMO = dyn_cast<FPMathOperator>(V)) {
15830b57cec5SDimitry Andric     if (FPMO->hasAllowReassoc())
15840b57cec5SDimitry Andric       Flags |= bitc::AllowReassoc;
15850b57cec5SDimitry Andric     if (FPMO->hasNoNaNs())
15860b57cec5SDimitry Andric       Flags |= bitc::NoNaNs;
15870b57cec5SDimitry Andric     if (FPMO->hasNoInfs())
15880b57cec5SDimitry Andric       Flags |= bitc::NoInfs;
15890b57cec5SDimitry Andric     if (FPMO->hasNoSignedZeros())
15900b57cec5SDimitry Andric       Flags |= bitc::NoSignedZeros;
15910b57cec5SDimitry Andric     if (FPMO->hasAllowReciprocal())
15920b57cec5SDimitry Andric       Flags |= bitc::AllowReciprocal;
15930b57cec5SDimitry Andric     if (FPMO->hasAllowContract())
15940b57cec5SDimitry Andric       Flags |= bitc::AllowContract;
15950b57cec5SDimitry Andric     if (FPMO->hasApproxFunc())
15960b57cec5SDimitry Andric       Flags |= bitc::ApproxFunc;
1597c9157d92SDimitry Andric   } else if (const auto *NNI = dyn_cast<PossiblyNonNegInst>(V)) {
1598c9157d92SDimitry Andric     if (NNI->hasNonNeg())
1599c9157d92SDimitry Andric       Flags |= 1 << bitc::PNNI_NON_NEG;
16000b57cec5SDimitry Andric   }
16010b57cec5SDimitry Andric 
16020b57cec5SDimitry Andric   return Flags;
16030b57cec5SDimitry Andric }
16040b57cec5SDimitry Andric 
writeValueAsMetadata(const ValueAsMetadata * MD,SmallVectorImpl<uint64_t> & Record)16050b57cec5SDimitry Andric void ModuleBitcodeWriter::writeValueAsMetadata(
16060b57cec5SDimitry Andric     const ValueAsMetadata *MD, SmallVectorImpl<uint64_t> &Record) {
16070b57cec5SDimitry Andric   // Mimic an MDNode with a value as one operand.
16080b57cec5SDimitry Andric   Value *V = MD->getValue();
16090b57cec5SDimitry Andric   Record.push_back(VE.getTypeID(V->getType()));
16100b57cec5SDimitry Andric   Record.push_back(VE.getValueID(V));
16110b57cec5SDimitry Andric   Stream.EmitRecord(bitc::METADATA_VALUE, Record, 0);
16120b57cec5SDimitry Andric   Record.clear();
16130b57cec5SDimitry Andric }
16140b57cec5SDimitry Andric 
writeMDTuple(const MDTuple * N,SmallVectorImpl<uint64_t> & Record,unsigned Abbrev)16150b57cec5SDimitry Andric void ModuleBitcodeWriter::writeMDTuple(const MDTuple *N,
16160b57cec5SDimitry Andric                                        SmallVectorImpl<uint64_t> &Record,
16170b57cec5SDimitry Andric                                        unsigned Abbrev) {
16180b57cec5SDimitry Andric   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
16190b57cec5SDimitry Andric     Metadata *MD = N->getOperand(i);
16200b57cec5SDimitry Andric     assert(!(MD && isa<LocalAsMetadata>(MD)) &&
16210b57cec5SDimitry Andric            "Unexpected function-local metadata");
16220b57cec5SDimitry Andric     Record.push_back(VE.getMetadataOrNullID(MD));
16230b57cec5SDimitry Andric   }
16240b57cec5SDimitry Andric   Stream.EmitRecord(N->isDistinct() ? bitc::METADATA_DISTINCT_NODE
16250b57cec5SDimitry Andric                                     : bitc::METADATA_NODE,
16260b57cec5SDimitry Andric                     Record, Abbrev);
16270b57cec5SDimitry Andric   Record.clear();
16280b57cec5SDimitry Andric }
16290b57cec5SDimitry Andric 
createDILocationAbbrev()16300b57cec5SDimitry Andric unsigned ModuleBitcodeWriter::createDILocationAbbrev() {
16310b57cec5SDimitry Andric   // Assume the column is usually under 128, and always output the inlined-at
16320b57cec5SDimitry Andric   // location (it's never more expensive than building an array size 1).
16330b57cec5SDimitry Andric   auto Abbv = std::make_shared<BitCodeAbbrev>();
16340b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_LOCATION));
16350b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
16360b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
16370b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
16380b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
16390b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
16400b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
16410b57cec5SDimitry Andric   return Stream.EmitAbbrev(std::move(Abbv));
16420b57cec5SDimitry Andric }
16430b57cec5SDimitry Andric 
writeDILocation(const DILocation * N,SmallVectorImpl<uint64_t> & Record,unsigned & Abbrev)16440b57cec5SDimitry Andric void ModuleBitcodeWriter::writeDILocation(const DILocation *N,
16450b57cec5SDimitry Andric                                           SmallVectorImpl<uint64_t> &Record,
16460b57cec5SDimitry Andric                                           unsigned &Abbrev) {
16470b57cec5SDimitry Andric   if (!Abbrev)
16480b57cec5SDimitry Andric     Abbrev = createDILocationAbbrev();
16490b57cec5SDimitry Andric 
16500b57cec5SDimitry Andric   Record.push_back(N->isDistinct());
16510b57cec5SDimitry Andric   Record.push_back(N->getLine());
16520b57cec5SDimitry Andric   Record.push_back(N->getColumn());
16530b57cec5SDimitry Andric   Record.push_back(VE.getMetadataID(N->getScope()));
16540b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getInlinedAt()));
16550b57cec5SDimitry Andric   Record.push_back(N->isImplicitCode());
16560b57cec5SDimitry Andric 
16570b57cec5SDimitry Andric   Stream.EmitRecord(bitc::METADATA_LOCATION, Record, Abbrev);
16580b57cec5SDimitry Andric   Record.clear();
16590b57cec5SDimitry Andric }
16600b57cec5SDimitry Andric 
createGenericDINodeAbbrev()16610b57cec5SDimitry Andric unsigned ModuleBitcodeWriter::createGenericDINodeAbbrev() {
16620b57cec5SDimitry Andric   // Assume the column is usually under 128, and always output the inlined-at
16630b57cec5SDimitry Andric   // location (it's never more expensive than building an array size 1).
16640b57cec5SDimitry Andric   auto Abbv = std::make_shared<BitCodeAbbrev>();
16650b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_GENERIC_DEBUG));
16660b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
16670b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
16680b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
16690b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
16700b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
16710b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
16720b57cec5SDimitry Andric   return Stream.EmitAbbrev(std::move(Abbv));
16730b57cec5SDimitry Andric }
16740b57cec5SDimitry Andric 
writeGenericDINode(const GenericDINode * N,SmallVectorImpl<uint64_t> & Record,unsigned & Abbrev)16750b57cec5SDimitry Andric void ModuleBitcodeWriter::writeGenericDINode(const GenericDINode *N,
16760b57cec5SDimitry Andric                                              SmallVectorImpl<uint64_t> &Record,
16770b57cec5SDimitry Andric                                              unsigned &Abbrev) {
16780b57cec5SDimitry Andric   if (!Abbrev)
16790b57cec5SDimitry Andric     Abbrev = createGenericDINodeAbbrev();
16800b57cec5SDimitry Andric 
16810b57cec5SDimitry Andric   Record.push_back(N->isDistinct());
16820b57cec5SDimitry Andric   Record.push_back(N->getTag());
16830b57cec5SDimitry Andric   Record.push_back(0); // Per-tag version field; unused for now.
16840b57cec5SDimitry Andric 
16850b57cec5SDimitry Andric   for (auto &I : N->operands())
16860b57cec5SDimitry Andric     Record.push_back(VE.getMetadataOrNullID(I));
16870b57cec5SDimitry Andric 
16880b57cec5SDimitry Andric   Stream.EmitRecord(bitc::METADATA_GENERIC_DEBUG, Record, Abbrev);
16890b57cec5SDimitry Andric   Record.clear();
16900b57cec5SDimitry Andric }
16910b57cec5SDimitry Andric 
writeDISubrange(const DISubrange * N,SmallVectorImpl<uint64_t> & Record,unsigned Abbrev)16920b57cec5SDimitry Andric void ModuleBitcodeWriter::writeDISubrange(const DISubrange *N,
16930b57cec5SDimitry Andric                                           SmallVectorImpl<uint64_t> &Record,
16940b57cec5SDimitry Andric                                           unsigned Abbrev) {
16955ffd83dbSDimitry Andric   const uint64_t Version = 2 << 1;
16960b57cec5SDimitry Andric   Record.push_back((uint64_t)N->isDistinct() | Version);
16970b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawCountNode()));
16985ffd83dbSDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawLowerBound()));
16995ffd83dbSDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawUpperBound()));
17005ffd83dbSDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawStride()));
17010b57cec5SDimitry Andric 
17020b57cec5SDimitry Andric   Stream.EmitRecord(bitc::METADATA_SUBRANGE, Record, Abbrev);
17030b57cec5SDimitry Andric   Record.clear();
17040b57cec5SDimitry Andric }
17050b57cec5SDimitry Andric 
writeDIGenericSubrange(const DIGenericSubrange * N,SmallVectorImpl<uint64_t> & Record,unsigned Abbrev)1706e8d8bef9SDimitry Andric void ModuleBitcodeWriter::writeDIGenericSubrange(
1707e8d8bef9SDimitry Andric     const DIGenericSubrange *N, SmallVectorImpl<uint64_t> &Record,
1708e8d8bef9SDimitry Andric     unsigned Abbrev) {
1709e8d8bef9SDimitry Andric   Record.push_back((uint64_t)N->isDistinct());
1710e8d8bef9SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawCountNode()));
1711e8d8bef9SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawLowerBound()));
1712e8d8bef9SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawUpperBound()));
1713e8d8bef9SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawStride()));
1714e8d8bef9SDimitry Andric 
1715e8d8bef9SDimitry Andric   Stream.EmitRecord(bitc::METADATA_GENERIC_SUBRANGE, Record, Abbrev);
1716e8d8bef9SDimitry Andric   Record.clear();
1717e8d8bef9SDimitry Andric }
1718e8d8bef9SDimitry Andric 
emitSignedInt64(SmallVectorImpl<uint64_t> & Vals,uint64_t V)17195ffd83dbSDimitry Andric static void emitSignedInt64(SmallVectorImpl<uint64_t> &Vals, uint64_t V) {
17205ffd83dbSDimitry Andric   if ((int64_t)V >= 0)
17215ffd83dbSDimitry Andric     Vals.push_back(V << 1);
17225ffd83dbSDimitry Andric   else
17235ffd83dbSDimitry Andric     Vals.push_back((-V << 1) | 1);
17245ffd83dbSDimitry Andric }
17255ffd83dbSDimitry Andric 
emitWideAPInt(SmallVectorImpl<uint64_t> & Vals,const APInt & A)17265ffd83dbSDimitry Andric static void emitWideAPInt(SmallVectorImpl<uint64_t> &Vals, const APInt &A) {
17275ffd83dbSDimitry Andric   // We have an arbitrary precision integer value to write whose
17285ffd83dbSDimitry Andric   // bit width is > 64. However, in canonical unsigned integer
17295ffd83dbSDimitry Andric   // format it is likely that the high bits are going to be zero.
17305ffd83dbSDimitry Andric   // So, we only write the number of active words.
17315ffd83dbSDimitry Andric   unsigned NumWords = A.getActiveWords();
17325ffd83dbSDimitry Andric   const uint64_t *RawData = A.getRawData();
17335ffd83dbSDimitry Andric   for (unsigned i = 0; i < NumWords; i++)
17345ffd83dbSDimitry Andric     emitSignedInt64(Vals, RawData[i]);
17355ffd83dbSDimitry Andric }
17365ffd83dbSDimitry Andric 
writeDIEnumerator(const DIEnumerator * N,SmallVectorImpl<uint64_t> & Record,unsigned Abbrev)17370b57cec5SDimitry Andric void ModuleBitcodeWriter::writeDIEnumerator(const DIEnumerator *N,
17380b57cec5SDimitry Andric                                             SmallVectorImpl<uint64_t> &Record,
17390b57cec5SDimitry Andric                                             unsigned Abbrev) {
17405ffd83dbSDimitry Andric   const uint64_t IsBigInt = 1 << 2;
17415ffd83dbSDimitry Andric   Record.push_back(IsBigInt | (N->isUnsigned() << 1) | N->isDistinct());
17425ffd83dbSDimitry Andric   Record.push_back(N->getValue().getBitWidth());
17430b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
17445ffd83dbSDimitry Andric   emitWideAPInt(Record, N->getValue());
17450b57cec5SDimitry Andric 
17460b57cec5SDimitry Andric   Stream.EmitRecord(bitc::METADATA_ENUMERATOR, Record, Abbrev);
17470b57cec5SDimitry Andric   Record.clear();
17480b57cec5SDimitry Andric }
17490b57cec5SDimitry Andric 
writeDIBasicType(const DIBasicType * N,SmallVectorImpl<uint64_t> & Record,unsigned Abbrev)17500b57cec5SDimitry Andric void ModuleBitcodeWriter::writeDIBasicType(const DIBasicType *N,
17510b57cec5SDimitry Andric                                            SmallVectorImpl<uint64_t> &Record,
17520b57cec5SDimitry Andric                                            unsigned Abbrev) {
17530b57cec5SDimitry Andric   Record.push_back(N->isDistinct());
17540b57cec5SDimitry Andric   Record.push_back(N->getTag());
17550b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
17560b57cec5SDimitry Andric   Record.push_back(N->getSizeInBits());
17570b57cec5SDimitry Andric   Record.push_back(N->getAlignInBits());
17580b57cec5SDimitry Andric   Record.push_back(N->getEncoding());
17590b57cec5SDimitry Andric   Record.push_back(N->getFlags());
17600b57cec5SDimitry Andric 
17610b57cec5SDimitry Andric   Stream.EmitRecord(bitc::METADATA_BASIC_TYPE, Record, Abbrev);
17620b57cec5SDimitry Andric   Record.clear();
17630b57cec5SDimitry Andric }
17640b57cec5SDimitry Andric 
writeDIStringType(const DIStringType * N,SmallVectorImpl<uint64_t> & Record,unsigned Abbrev)1765e8d8bef9SDimitry Andric void ModuleBitcodeWriter::writeDIStringType(const DIStringType *N,
1766e8d8bef9SDimitry Andric                                             SmallVectorImpl<uint64_t> &Record,
1767e8d8bef9SDimitry Andric                                             unsigned Abbrev) {
1768e8d8bef9SDimitry Andric   Record.push_back(N->isDistinct());
1769e8d8bef9SDimitry Andric   Record.push_back(N->getTag());
1770e8d8bef9SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1771e8d8bef9SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getStringLength()));
1772e8d8bef9SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getStringLengthExp()));
177304eeddc0SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getStringLocationExp()));
1774e8d8bef9SDimitry Andric   Record.push_back(N->getSizeInBits());
1775e8d8bef9SDimitry Andric   Record.push_back(N->getAlignInBits());
1776e8d8bef9SDimitry Andric   Record.push_back(N->getEncoding());
1777e8d8bef9SDimitry Andric 
1778e8d8bef9SDimitry Andric   Stream.EmitRecord(bitc::METADATA_STRING_TYPE, Record, Abbrev);
1779e8d8bef9SDimitry Andric   Record.clear();
1780e8d8bef9SDimitry Andric }
1781e8d8bef9SDimitry Andric 
writeDIDerivedType(const DIDerivedType * N,SmallVectorImpl<uint64_t> & Record,unsigned Abbrev)17820b57cec5SDimitry Andric void ModuleBitcodeWriter::writeDIDerivedType(const DIDerivedType *N,
17830b57cec5SDimitry Andric                                              SmallVectorImpl<uint64_t> &Record,
17840b57cec5SDimitry Andric                                              unsigned Abbrev) {
17850b57cec5SDimitry Andric   Record.push_back(N->isDistinct());
17860b57cec5SDimitry Andric   Record.push_back(N->getTag());
17870b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
17880b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
17890b57cec5SDimitry Andric   Record.push_back(N->getLine());
17900b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
17910b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
17920b57cec5SDimitry Andric   Record.push_back(N->getSizeInBits());
17930b57cec5SDimitry Andric   Record.push_back(N->getAlignInBits());
17940b57cec5SDimitry Andric   Record.push_back(N->getOffsetInBits());
17950b57cec5SDimitry Andric   Record.push_back(N->getFlags());
17960b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getExtraData()));
17970b57cec5SDimitry Andric 
17980b57cec5SDimitry Andric   // DWARF address space is encoded as N->getDWARFAddressSpace() + 1. 0 means
17990b57cec5SDimitry Andric   // that there is no DWARF address space associated with DIDerivedType.
18000b57cec5SDimitry Andric   if (const auto &DWARFAddressSpace = N->getDWARFAddressSpace())
18010b57cec5SDimitry Andric     Record.push_back(*DWARFAddressSpace + 1);
18020b57cec5SDimitry Andric   else
18030b57cec5SDimitry Andric     Record.push_back(0);
18040b57cec5SDimitry Andric 
1805349cc55cSDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getAnnotations().get()));
1806349cc55cSDimitry Andric 
18070b57cec5SDimitry Andric   Stream.EmitRecord(bitc::METADATA_DERIVED_TYPE, Record, Abbrev);
18080b57cec5SDimitry Andric   Record.clear();
18090b57cec5SDimitry Andric }
18100b57cec5SDimitry Andric 
writeDICompositeType(const DICompositeType * N,SmallVectorImpl<uint64_t> & Record,unsigned Abbrev)18110b57cec5SDimitry Andric void ModuleBitcodeWriter::writeDICompositeType(
18120b57cec5SDimitry Andric     const DICompositeType *N, SmallVectorImpl<uint64_t> &Record,
18130b57cec5SDimitry Andric     unsigned Abbrev) {
18140b57cec5SDimitry Andric   const unsigned IsNotUsedInOldTypeRef = 0x2;
18150b57cec5SDimitry Andric   Record.push_back(IsNotUsedInOldTypeRef | (unsigned)N->isDistinct());
18160b57cec5SDimitry Andric   Record.push_back(N->getTag());
18170b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
18180b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
18190b57cec5SDimitry Andric   Record.push_back(N->getLine());
18200b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
18210b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
18220b57cec5SDimitry Andric   Record.push_back(N->getSizeInBits());
18230b57cec5SDimitry Andric   Record.push_back(N->getAlignInBits());
18240b57cec5SDimitry Andric   Record.push_back(N->getOffsetInBits());
18250b57cec5SDimitry Andric   Record.push_back(N->getFlags());
18260b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
18270b57cec5SDimitry Andric   Record.push_back(N->getRuntimeLang());
18280b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getVTableHolder()));
18290b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
18300b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawIdentifier()));
18310b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getDiscriminator()));
18325ffd83dbSDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawDataLocation()));
1833e8d8bef9SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawAssociated()));
1834e8d8bef9SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawAllocated()));
1835e8d8bef9SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawRank()));
1836349cc55cSDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getAnnotations().get()));
18370b57cec5SDimitry Andric 
18380b57cec5SDimitry Andric   Stream.EmitRecord(bitc::METADATA_COMPOSITE_TYPE, Record, Abbrev);
18390b57cec5SDimitry Andric   Record.clear();
18400b57cec5SDimitry Andric }
18410b57cec5SDimitry Andric 
writeDISubroutineType(const DISubroutineType * N,SmallVectorImpl<uint64_t> & Record,unsigned Abbrev)18420b57cec5SDimitry Andric void ModuleBitcodeWriter::writeDISubroutineType(
18430b57cec5SDimitry Andric     const DISubroutineType *N, SmallVectorImpl<uint64_t> &Record,
18440b57cec5SDimitry Andric     unsigned Abbrev) {
18450b57cec5SDimitry Andric   const unsigned HasNoOldTypeRefs = 0x2;
18460b57cec5SDimitry Andric   Record.push_back(HasNoOldTypeRefs | (unsigned)N->isDistinct());
18470b57cec5SDimitry Andric   Record.push_back(N->getFlags());
18480b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getTypeArray().get()));
18490b57cec5SDimitry Andric   Record.push_back(N->getCC());
18500b57cec5SDimitry Andric 
18510b57cec5SDimitry Andric   Stream.EmitRecord(bitc::METADATA_SUBROUTINE_TYPE, Record, Abbrev);
18520b57cec5SDimitry Andric   Record.clear();
18530b57cec5SDimitry Andric }
18540b57cec5SDimitry Andric 
writeDIFile(const DIFile * N,SmallVectorImpl<uint64_t> & Record,unsigned Abbrev)18550b57cec5SDimitry Andric void ModuleBitcodeWriter::writeDIFile(const DIFile *N,
18560b57cec5SDimitry Andric                                       SmallVectorImpl<uint64_t> &Record,
18570b57cec5SDimitry Andric                                       unsigned Abbrev) {
18580b57cec5SDimitry Andric   Record.push_back(N->isDistinct());
18590b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawFilename()));
18600b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawDirectory()));
18610b57cec5SDimitry Andric   if (N->getRawChecksum()) {
18620b57cec5SDimitry Andric     Record.push_back(N->getRawChecksum()->Kind);
18630b57cec5SDimitry Andric     Record.push_back(VE.getMetadataOrNullID(N->getRawChecksum()->Value));
18640b57cec5SDimitry Andric   } else {
18650b57cec5SDimitry Andric     // Maintain backwards compatibility with the old internal representation of
18660b57cec5SDimitry Andric     // CSK_None in ChecksumKind by writing nulls here when Checksum is None.
18670b57cec5SDimitry Andric     Record.push_back(0);
18680b57cec5SDimitry Andric     Record.push_back(VE.getMetadataOrNullID(nullptr));
18690b57cec5SDimitry Andric   }
18700b57cec5SDimitry Andric   auto Source = N->getRawSource();
18710b57cec5SDimitry Andric   if (Source)
1872bdd1243dSDimitry Andric     Record.push_back(VE.getMetadataOrNullID(Source));
18730b57cec5SDimitry Andric 
18740b57cec5SDimitry Andric   Stream.EmitRecord(bitc::METADATA_FILE, Record, Abbrev);
18750b57cec5SDimitry Andric   Record.clear();
18760b57cec5SDimitry Andric }
18770b57cec5SDimitry Andric 
writeDICompileUnit(const DICompileUnit * N,SmallVectorImpl<uint64_t> & Record,unsigned Abbrev)18780b57cec5SDimitry Andric void ModuleBitcodeWriter::writeDICompileUnit(const DICompileUnit *N,
18790b57cec5SDimitry Andric                                              SmallVectorImpl<uint64_t> &Record,
18800b57cec5SDimitry Andric                                              unsigned Abbrev) {
18810b57cec5SDimitry Andric   assert(N->isDistinct() && "Expected distinct compile units");
18820b57cec5SDimitry Andric   Record.push_back(/* IsDistinct */ true);
18830b57cec5SDimitry Andric   Record.push_back(N->getSourceLanguage());
18840b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
18850b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawProducer()));
18860b57cec5SDimitry Andric   Record.push_back(N->isOptimized());
18870b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawFlags()));
18880b57cec5SDimitry Andric   Record.push_back(N->getRuntimeVersion());
18890b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawSplitDebugFilename()));
18900b57cec5SDimitry Andric   Record.push_back(N->getEmissionKind());
18910b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getEnumTypes().get()));
18920b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRetainedTypes().get()));
18930b57cec5SDimitry Andric   Record.push_back(/* subprograms */ 0);
18940b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getGlobalVariables().get()));
18950b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getImportedEntities().get()));
18960b57cec5SDimitry Andric   Record.push_back(N->getDWOId());
18970b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getMacros().get()));
18980b57cec5SDimitry Andric   Record.push_back(N->getSplitDebugInlining());
18990b57cec5SDimitry Andric   Record.push_back(N->getDebugInfoForProfiling());
19000b57cec5SDimitry Andric   Record.push_back((unsigned)N->getNameTableKind());
19015ffd83dbSDimitry Andric   Record.push_back(N->getRangesBaseAddress());
19025ffd83dbSDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawSysRoot()));
19035ffd83dbSDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawSDK()));
19040b57cec5SDimitry Andric 
19050b57cec5SDimitry Andric   Stream.EmitRecord(bitc::METADATA_COMPILE_UNIT, Record, Abbrev);
19060b57cec5SDimitry Andric   Record.clear();
19070b57cec5SDimitry Andric }
19080b57cec5SDimitry Andric 
writeDISubprogram(const DISubprogram * N,SmallVectorImpl<uint64_t> & Record,unsigned Abbrev)19090b57cec5SDimitry Andric void ModuleBitcodeWriter::writeDISubprogram(const DISubprogram *N,
19100b57cec5SDimitry Andric                                             SmallVectorImpl<uint64_t> &Record,
19110b57cec5SDimitry Andric                                             unsigned Abbrev) {
19120b57cec5SDimitry Andric   const uint64_t HasUnitFlag = 1 << 1;
19130b57cec5SDimitry Andric   const uint64_t HasSPFlagsFlag = 1 << 2;
19140b57cec5SDimitry Andric   Record.push_back(uint64_t(N->isDistinct()) | HasUnitFlag | HasSPFlagsFlag);
19150b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
19160b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
19170b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
19180b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
19190b57cec5SDimitry Andric   Record.push_back(N->getLine());
19200b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getType()));
19210b57cec5SDimitry Andric   Record.push_back(N->getScopeLine());
19220b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getContainingType()));
19230b57cec5SDimitry Andric   Record.push_back(N->getSPFlags());
19240b57cec5SDimitry Andric   Record.push_back(N->getVirtualIndex());
19250b57cec5SDimitry Andric   Record.push_back(N->getFlags());
19260b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawUnit()));
19270b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
19280b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getDeclaration()));
19290b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRetainedNodes().get()));
19300b57cec5SDimitry Andric   Record.push_back(N->getThisAdjustment());
19310b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getThrownTypes().get()));
1932349cc55cSDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getAnnotations().get()));
193381ad6265SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawTargetFuncName()));
19340b57cec5SDimitry Andric 
19350b57cec5SDimitry Andric   Stream.EmitRecord(bitc::METADATA_SUBPROGRAM, Record, Abbrev);
19360b57cec5SDimitry Andric   Record.clear();
19370b57cec5SDimitry Andric }
19380b57cec5SDimitry Andric 
writeDILexicalBlock(const DILexicalBlock * N,SmallVectorImpl<uint64_t> & Record,unsigned Abbrev)19390b57cec5SDimitry Andric void ModuleBitcodeWriter::writeDILexicalBlock(const DILexicalBlock *N,
19400b57cec5SDimitry Andric                                               SmallVectorImpl<uint64_t> &Record,
19410b57cec5SDimitry Andric                                               unsigned Abbrev) {
19420b57cec5SDimitry Andric   Record.push_back(N->isDistinct());
19430b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
19440b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
19450b57cec5SDimitry Andric   Record.push_back(N->getLine());
19460b57cec5SDimitry Andric   Record.push_back(N->getColumn());
19470b57cec5SDimitry Andric 
19480b57cec5SDimitry Andric   Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK, Record, Abbrev);
19490b57cec5SDimitry Andric   Record.clear();
19500b57cec5SDimitry Andric }
19510b57cec5SDimitry Andric 
writeDILexicalBlockFile(const DILexicalBlockFile * N,SmallVectorImpl<uint64_t> & Record,unsigned Abbrev)19520b57cec5SDimitry Andric void ModuleBitcodeWriter::writeDILexicalBlockFile(
19530b57cec5SDimitry Andric     const DILexicalBlockFile *N, SmallVectorImpl<uint64_t> &Record,
19540b57cec5SDimitry Andric     unsigned Abbrev) {
19550b57cec5SDimitry Andric   Record.push_back(N->isDistinct());
19560b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
19570b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
19580b57cec5SDimitry Andric   Record.push_back(N->getDiscriminator());
19590b57cec5SDimitry Andric 
19600b57cec5SDimitry Andric   Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK_FILE, Record, Abbrev);
19610b57cec5SDimitry Andric   Record.clear();
19620b57cec5SDimitry Andric }
19630b57cec5SDimitry Andric 
writeDICommonBlock(const DICommonBlock * N,SmallVectorImpl<uint64_t> & Record,unsigned Abbrev)19640b57cec5SDimitry Andric void ModuleBitcodeWriter::writeDICommonBlock(const DICommonBlock *N,
19650b57cec5SDimitry Andric                                              SmallVectorImpl<uint64_t> &Record,
19660b57cec5SDimitry Andric                                              unsigned Abbrev) {
19670b57cec5SDimitry Andric   Record.push_back(N->isDistinct());
19680b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
19690b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getDecl()));
19700b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
19710b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
19720b57cec5SDimitry Andric   Record.push_back(N->getLineNo());
19730b57cec5SDimitry Andric 
19740b57cec5SDimitry Andric   Stream.EmitRecord(bitc::METADATA_COMMON_BLOCK, Record, Abbrev);
19750b57cec5SDimitry Andric   Record.clear();
19760b57cec5SDimitry Andric }
19770b57cec5SDimitry Andric 
writeDINamespace(const DINamespace * N,SmallVectorImpl<uint64_t> & Record,unsigned Abbrev)19780b57cec5SDimitry Andric void ModuleBitcodeWriter::writeDINamespace(const DINamespace *N,
19790b57cec5SDimitry Andric                                            SmallVectorImpl<uint64_t> &Record,
19800b57cec5SDimitry Andric                                            unsigned Abbrev) {
19810b57cec5SDimitry Andric   Record.push_back(N->isDistinct() | N->getExportSymbols() << 1);
19820b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
19830b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
19840b57cec5SDimitry Andric 
19850b57cec5SDimitry Andric   Stream.EmitRecord(bitc::METADATA_NAMESPACE, Record, Abbrev);
19860b57cec5SDimitry Andric   Record.clear();
19870b57cec5SDimitry Andric }
19880b57cec5SDimitry Andric 
writeDIMacro(const DIMacro * N,SmallVectorImpl<uint64_t> & Record,unsigned Abbrev)19890b57cec5SDimitry Andric void ModuleBitcodeWriter::writeDIMacro(const DIMacro *N,
19900b57cec5SDimitry Andric                                        SmallVectorImpl<uint64_t> &Record,
19910b57cec5SDimitry Andric                                        unsigned Abbrev) {
19920b57cec5SDimitry Andric   Record.push_back(N->isDistinct());
19930b57cec5SDimitry Andric   Record.push_back(N->getMacinfoType());
19940b57cec5SDimitry Andric   Record.push_back(N->getLine());
19950b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
19960b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawValue()));
19970b57cec5SDimitry Andric 
19980b57cec5SDimitry Andric   Stream.EmitRecord(bitc::METADATA_MACRO, Record, Abbrev);
19990b57cec5SDimitry Andric   Record.clear();
20000b57cec5SDimitry Andric }
20010b57cec5SDimitry Andric 
writeDIMacroFile(const DIMacroFile * N,SmallVectorImpl<uint64_t> & Record,unsigned Abbrev)20020b57cec5SDimitry Andric void ModuleBitcodeWriter::writeDIMacroFile(const DIMacroFile *N,
20030b57cec5SDimitry Andric                                            SmallVectorImpl<uint64_t> &Record,
20040b57cec5SDimitry Andric                                            unsigned Abbrev) {
20050b57cec5SDimitry Andric   Record.push_back(N->isDistinct());
20060b57cec5SDimitry Andric   Record.push_back(N->getMacinfoType());
20070b57cec5SDimitry Andric   Record.push_back(N->getLine());
20080b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
20090b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
20100b57cec5SDimitry Andric 
20110b57cec5SDimitry Andric   Stream.EmitRecord(bitc::METADATA_MACRO_FILE, Record, Abbrev);
20120b57cec5SDimitry Andric   Record.clear();
20130b57cec5SDimitry Andric }
20140b57cec5SDimitry Andric 
writeDIArgList(const DIArgList * N,SmallVectorImpl<uint64_t> & Record)2015fe6060f1SDimitry Andric void ModuleBitcodeWriter::writeDIArgList(const DIArgList *N,
2016c9157d92SDimitry Andric                                          SmallVectorImpl<uint64_t> &Record) {
2017fe6060f1SDimitry Andric   Record.reserve(N->getArgs().size());
2018fe6060f1SDimitry Andric   for (ValueAsMetadata *MD : N->getArgs())
2019fe6060f1SDimitry Andric     Record.push_back(VE.getMetadataID(MD));
2020fe6060f1SDimitry Andric 
2021c9157d92SDimitry Andric   Stream.EmitRecord(bitc::METADATA_ARG_LIST, Record);
2022fe6060f1SDimitry Andric   Record.clear();
2023fe6060f1SDimitry Andric }
2024fe6060f1SDimitry Andric 
writeDIModule(const DIModule * N,SmallVectorImpl<uint64_t> & Record,unsigned Abbrev)20250b57cec5SDimitry Andric void ModuleBitcodeWriter::writeDIModule(const DIModule *N,
20260b57cec5SDimitry Andric                                         SmallVectorImpl<uint64_t> &Record,
20270b57cec5SDimitry Andric                                         unsigned Abbrev) {
20280b57cec5SDimitry Andric   Record.push_back(N->isDistinct());
20290b57cec5SDimitry Andric   for (auto &I : N->operands())
20300b57cec5SDimitry Andric     Record.push_back(VE.getMetadataOrNullID(I));
20315ffd83dbSDimitry Andric   Record.push_back(N->getLineNo());
2032e8d8bef9SDimitry Andric   Record.push_back(N->getIsDecl());
20330b57cec5SDimitry Andric 
20340b57cec5SDimitry Andric   Stream.EmitRecord(bitc::METADATA_MODULE, Record, Abbrev);
20350b57cec5SDimitry Andric   Record.clear();
20360b57cec5SDimitry Andric }
20370b57cec5SDimitry Andric 
writeDIAssignID(const DIAssignID * N,SmallVectorImpl<uint64_t> & Record,unsigned Abbrev)2038bdd1243dSDimitry Andric void ModuleBitcodeWriter::writeDIAssignID(const DIAssignID *N,
2039bdd1243dSDimitry Andric                                           SmallVectorImpl<uint64_t> &Record,
2040bdd1243dSDimitry Andric                                           unsigned Abbrev) {
2041bdd1243dSDimitry Andric   // There are no arguments for this metadata type.
2042bdd1243dSDimitry Andric   Record.push_back(N->isDistinct());
2043bdd1243dSDimitry Andric   Stream.EmitRecord(bitc::METADATA_ASSIGN_ID, Record, Abbrev);
2044bdd1243dSDimitry Andric   Record.clear();
2045bdd1243dSDimitry Andric }
2046bdd1243dSDimitry Andric 
writeDITemplateTypeParameter(const DITemplateTypeParameter * N,SmallVectorImpl<uint64_t> & Record,unsigned Abbrev)20470b57cec5SDimitry Andric void ModuleBitcodeWriter::writeDITemplateTypeParameter(
20480b57cec5SDimitry Andric     const DITemplateTypeParameter *N, SmallVectorImpl<uint64_t> &Record,
20490b57cec5SDimitry Andric     unsigned Abbrev) {
20500b57cec5SDimitry Andric   Record.push_back(N->isDistinct());
20510b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
20520b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getType()));
20535ffd83dbSDimitry Andric   Record.push_back(N->isDefault());
20540b57cec5SDimitry Andric 
20550b57cec5SDimitry Andric   Stream.EmitRecord(bitc::METADATA_TEMPLATE_TYPE, Record, Abbrev);
20560b57cec5SDimitry Andric   Record.clear();
20570b57cec5SDimitry Andric }
20580b57cec5SDimitry Andric 
writeDITemplateValueParameter(const DITemplateValueParameter * N,SmallVectorImpl<uint64_t> & Record,unsigned Abbrev)20590b57cec5SDimitry Andric void ModuleBitcodeWriter::writeDITemplateValueParameter(
20600b57cec5SDimitry Andric     const DITemplateValueParameter *N, SmallVectorImpl<uint64_t> &Record,
20610b57cec5SDimitry Andric     unsigned Abbrev) {
20620b57cec5SDimitry Andric   Record.push_back(N->isDistinct());
20630b57cec5SDimitry Andric   Record.push_back(N->getTag());
20640b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
20650b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getType()));
20665ffd83dbSDimitry Andric   Record.push_back(N->isDefault());
20670b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getValue()));
20680b57cec5SDimitry Andric 
20690b57cec5SDimitry Andric   Stream.EmitRecord(bitc::METADATA_TEMPLATE_VALUE, Record, Abbrev);
20700b57cec5SDimitry Andric   Record.clear();
20710b57cec5SDimitry Andric }
20720b57cec5SDimitry Andric 
writeDIGlobalVariable(const DIGlobalVariable * N,SmallVectorImpl<uint64_t> & Record,unsigned Abbrev)20730b57cec5SDimitry Andric void ModuleBitcodeWriter::writeDIGlobalVariable(
20740b57cec5SDimitry Andric     const DIGlobalVariable *N, SmallVectorImpl<uint64_t> &Record,
20750b57cec5SDimitry Andric     unsigned Abbrev) {
20760b57cec5SDimitry Andric   const uint64_t Version = 2 << 1;
20770b57cec5SDimitry Andric   Record.push_back((uint64_t)N->isDistinct() | Version);
20780b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
20790b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
20800b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
20810b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
20820b57cec5SDimitry Andric   Record.push_back(N->getLine());
20830b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getType()));
20840b57cec5SDimitry Andric   Record.push_back(N->isLocalToUnit());
20850b57cec5SDimitry Andric   Record.push_back(N->isDefinition());
20860b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getStaticDataMemberDeclaration()));
20870b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams()));
20880b57cec5SDimitry Andric   Record.push_back(N->getAlignInBits());
2089349cc55cSDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getAnnotations().get()));
20900b57cec5SDimitry Andric 
20910b57cec5SDimitry Andric   Stream.EmitRecord(bitc::METADATA_GLOBAL_VAR, Record, Abbrev);
20920b57cec5SDimitry Andric   Record.clear();
20930b57cec5SDimitry Andric }
20940b57cec5SDimitry Andric 
writeDILocalVariable(const DILocalVariable * N,SmallVectorImpl<uint64_t> & Record,unsigned Abbrev)20950b57cec5SDimitry Andric void ModuleBitcodeWriter::writeDILocalVariable(
20960b57cec5SDimitry Andric     const DILocalVariable *N, SmallVectorImpl<uint64_t> &Record,
20970b57cec5SDimitry Andric     unsigned Abbrev) {
20980b57cec5SDimitry Andric   // In order to support all possible bitcode formats in BitcodeReader we need
20990b57cec5SDimitry Andric   // to distinguish the following cases:
21000b57cec5SDimitry Andric   // 1) Record has no artificial tag (Record[1]),
21010b57cec5SDimitry Andric   //   has no obsolete inlinedAt field (Record[9]).
21020b57cec5SDimitry Andric   //   In this case Record size will be 8, HasAlignment flag is false.
21030b57cec5SDimitry Andric   // 2) Record has artificial tag (Record[1]),
21040b57cec5SDimitry Andric   //   has no obsolete inlignedAt field (Record[9]).
21050b57cec5SDimitry Andric   //   In this case Record size will be 9, HasAlignment flag is false.
21060b57cec5SDimitry Andric   // 3) Record has both artificial tag (Record[1]) and
21070b57cec5SDimitry Andric   //   obsolete inlignedAt field (Record[9]).
21080b57cec5SDimitry Andric   //   In this case Record size will be 10, HasAlignment flag is false.
21090b57cec5SDimitry Andric   // 4) Record has neither artificial tag, nor inlignedAt field, but
21100b57cec5SDimitry Andric   //   HasAlignment flag is true and Record[8] contains alignment value.
21110b57cec5SDimitry Andric   const uint64_t HasAlignmentFlag = 1 << 1;
21120b57cec5SDimitry Andric   Record.push_back((uint64_t)N->isDistinct() | HasAlignmentFlag);
21130b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
21140b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
21150b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
21160b57cec5SDimitry Andric   Record.push_back(N->getLine());
21170b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getType()));
21180b57cec5SDimitry Andric   Record.push_back(N->getArg());
21190b57cec5SDimitry Andric   Record.push_back(N->getFlags());
21200b57cec5SDimitry Andric   Record.push_back(N->getAlignInBits());
2121349cc55cSDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getAnnotations().get()));
21220b57cec5SDimitry Andric 
21230b57cec5SDimitry Andric   Stream.EmitRecord(bitc::METADATA_LOCAL_VAR, Record, Abbrev);
21240b57cec5SDimitry Andric   Record.clear();
21250b57cec5SDimitry Andric }
21260b57cec5SDimitry Andric 
writeDILabel(const DILabel * N,SmallVectorImpl<uint64_t> & Record,unsigned Abbrev)21270b57cec5SDimitry Andric void ModuleBitcodeWriter::writeDILabel(
21280b57cec5SDimitry Andric     const DILabel *N, SmallVectorImpl<uint64_t> &Record,
21290b57cec5SDimitry Andric     unsigned Abbrev) {
21300b57cec5SDimitry Andric   Record.push_back((uint64_t)N->isDistinct());
21310b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
21320b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
21330b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
21340b57cec5SDimitry Andric   Record.push_back(N->getLine());
21350b57cec5SDimitry Andric 
21360b57cec5SDimitry Andric   Stream.EmitRecord(bitc::METADATA_LABEL, Record, Abbrev);
21370b57cec5SDimitry Andric   Record.clear();
21380b57cec5SDimitry Andric }
21390b57cec5SDimitry Andric 
writeDIExpression(const DIExpression * N,SmallVectorImpl<uint64_t> & Record,unsigned Abbrev)21400b57cec5SDimitry Andric void ModuleBitcodeWriter::writeDIExpression(const DIExpression *N,
21410b57cec5SDimitry Andric                                             SmallVectorImpl<uint64_t> &Record,
21420b57cec5SDimitry Andric                                             unsigned Abbrev) {
21430b57cec5SDimitry Andric   Record.reserve(N->getElements().size() + 1);
21440b57cec5SDimitry Andric   const uint64_t Version = 3 << 1;
21450b57cec5SDimitry Andric   Record.push_back((uint64_t)N->isDistinct() | Version);
21460b57cec5SDimitry Andric   Record.append(N->elements_begin(), N->elements_end());
21470b57cec5SDimitry Andric 
21480b57cec5SDimitry Andric   Stream.EmitRecord(bitc::METADATA_EXPRESSION, Record, Abbrev);
21490b57cec5SDimitry Andric   Record.clear();
21500b57cec5SDimitry Andric }
21510b57cec5SDimitry Andric 
writeDIGlobalVariableExpression(const DIGlobalVariableExpression * N,SmallVectorImpl<uint64_t> & Record,unsigned Abbrev)21520b57cec5SDimitry Andric void ModuleBitcodeWriter::writeDIGlobalVariableExpression(
21530b57cec5SDimitry Andric     const DIGlobalVariableExpression *N, SmallVectorImpl<uint64_t> &Record,
21540b57cec5SDimitry Andric     unsigned Abbrev) {
21550b57cec5SDimitry Andric   Record.push_back(N->isDistinct());
21560b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getVariable()));
21570b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getExpression()));
21580b57cec5SDimitry Andric 
21590b57cec5SDimitry Andric   Stream.EmitRecord(bitc::METADATA_GLOBAL_VAR_EXPR, Record, Abbrev);
21600b57cec5SDimitry Andric   Record.clear();
21610b57cec5SDimitry Andric }
21620b57cec5SDimitry Andric 
writeDIObjCProperty(const DIObjCProperty * N,SmallVectorImpl<uint64_t> & Record,unsigned Abbrev)21630b57cec5SDimitry Andric void ModuleBitcodeWriter::writeDIObjCProperty(const DIObjCProperty *N,
21640b57cec5SDimitry Andric                                               SmallVectorImpl<uint64_t> &Record,
21650b57cec5SDimitry Andric                                               unsigned Abbrev) {
21660b57cec5SDimitry Andric   Record.push_back(N->isDistinct());
21670b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
21680b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
21690b57cec5SDimitry Andric   Record.push_back(N->getLine());
21700b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawSetterName()));
21710b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawGetterName()));
21720b57cec5SDimitry Andric   Record.push_back(N->getAttributes());
21730b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getType()));
21740b57cec5SDimitry Andric 
21750b57cec5SDimitry Andric   Stream.EmitRecord(bitc::METADATA_OBJC_PROPERTY, Record, Abbrev);
21760b57cec5SDimitry Andric   Record.clear();
21770b57cec5SDimitry Andric }
21780b57cec5SDimitry Andric 
writeDIImportedEntity(const DIImportedEntity * N,SmallVectorImpl<uint64_t> & Record,unsigned Abbrev)21790b57cec5SDimitry Andric void ModuleBitcodeWriter::writeDIImportedEntity(
21800b57cec5SDimitry Andric     const DIImportedEntity *N, SmallVectorImpl<uint64_t> &Record,
21810b57cec5SDimitry Andric     unsigned Abbrev) {
21820b57cec5SDimitry Andric   Record.push_back(N->isDistinct());
21830b57cec5SDimitry Andric   Record.push_back(N->getTag());
21840b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
21850b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getEntity()));
21860b57cec5SDimitry Andric   Record.push_back(N->getLine());
21870b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
21880b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawFile()));
2189349cc55cSDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
21900b57cec5SDimitry Andric 
21910b57cec5SDimitry Andric   Stream.EmitRecord(bitc::METADATA_IMPORTED_ENTITY, Record, Abbrev);
21920b57cec5SDimitry Andric   Record.clear();
21930b57cec5SDimitry Andric }
21940b57cec5SDimitry Andric 
createNamedMetadataAbbrev()21950b57cec5SDimitry Andric unsigned ModuleBitcodeWriter::createNamedMetadataAbbrev() {
21960b57cec5SDimitry Andric   auto Abbv = std::make_shared<BitCodeAbbrev>();
21970b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_NAME));
21980b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
21990b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
22000b57cec5SDimitry Andric   return Stream.EmitAbbrev(std::move(Abbv));
22010b57cec5SDimitry Andric }
22020b57cec5SDimitry Andric 
writeNamedMetadata(SmallVectorImpl<uint64_t> & Record)22030b57cec5SDimitry Andric void ModuleBitcodeWriter::writeNamedMetadata(
22040b57cec5SDimitry Andric     SmallVectorImpl<uint64_t> &Record) {
22050b57cec5SDimitry Andric   if (M.named_metadata_empty())
22060b57cec5SDimitry Andric     return;
22070b57cec5SDimitry Andric 
22080b57cec5SDimitry Andric   unsigned Abbrev = createNamedMetadataAbbrev();
22090b57cec5SDimitry Andric   for (const NamedMDNode &NMD : M.named_metadata()) {
22100b57cec5SDimitry Andric     // Write name.
22110b57cec5SDimitry Andric     StringRef Str = NMD.getName();
22120b57cec5SDimitry Andric     Record.append(Str.bytes_begin(), Str.bytes_end());
22130b57cec5SDimitry Andric     Stream.EmitRecord(bitc::METADATA_NAME, Record, Abbrev);
22140b57cec5SDimitry Andric     Record.clear();
22150b57cec5SDimitry Andric 
22160b57cec5SDimitry Andric     // Write named metadata operands.
22170b57cec5SDimitry Andric     for (const MDNode *N : NMD.operands())
22180b57cec5SDimitry Andric       Record.push_back(VE.getMetadataID(N));
22190b57cec5SDimitry Andric     Stream.EmitRecord(bitc::METADATA_NAMED_NODE, Record, 0);
22200b57cec5SDimitry Andric     Record.clear();
22210b57cec5SDimitry Andric   }
22220b57cec5SDimitry Andric }
22230b57cec5SDimitry Andric 
createMetadataStringsAbbrev()22240b57cec5SDimitry Andric unsigned ModuleBitcodeWriter::createMetadataStringsAbbrev() {
22250b57cec5SDimitry Andric   auto Abbv = std::make_shared<BitCodeAbbrev>();
22260b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_STRINGS));
22270b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of strings
22280b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // offset to chars
22290b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
22300b57cec5SDimitry Andric   return Stream.EmitAbbrev(std::move(Abbv));
22310b57cec5SDimitry Andric }
22320b57cec5SDimitry Andric 
22330b57cec5SDimitry Andric /// Write out a record for MDString.
22340b57cec5SDimitry Andric ///
22350b57cec5SDimitry Andric /// All the metadata strings in a metadata block are emitted in a single
22360b57cec5SDimitry Andric /// record.  The sizes and strings themselves are shoved into a blob.
writeMetadataStrings(ArrayRef<const Metadata * > Strings,SmallVectorImpl<uint64_t> & Record)22370b57cec5SDimitry Andric void ModuleBitcodeWriter::writeMetadataStrings(
22380b57cec5SDimitry Andric     ArrayRef<const Metadata *> Strings, SmallVectorImpl<uint64_t> &Record) {
22390b57cec5SDimitry Andric   if (Strings.empty())
22400b57cec5SDimitry Andric     return;
22410b57cec5SDimitry Andric 
22420b57cec5SDimitry Andric   // Start the record with the number of strings.
22430b57cec5SDimitry Andric   Record.push_back(bitc::METADATA_STRINGS);
22440b57cec5SDimitry Andric   Record.push_back(Strings.size());
22450b57cec5SDimitry Andric 
22460b57cec5SDimitry Andric   // Emit the sizes of the strings in the blob.
22470b57cec5SDimitry Andric   SmallString<256> Blob;
22480b57cec5SDimitry Andric   {
22490b57cec5SDimitry Andric     BitstreamWriter W(Blob);
22500b57cec5SDimitry Andric     for (const Metadata *MD : Strings)
22510b57cec5SDimitry Andric       W.EmitVBR(cast<MDString>(MD)->getLength(), 6);
22520b57cec5SDimitry Andric     W.FlushToWord();
22530b57cec5SDimitry Andric   }
22540b57cec5SDimitry Andric 
22550b57cec5SDimitry Andric   // Add the offset to the strings to the record.
22560b57cec5SDimitry Andric   Record.push_back(Blob.size());
22570b57cec5SDimitry Andric 
22580b57cec5SDimitry Andric   // Add the strings to the blob.
22590b57cec5SDimitry Andric   for (const Metadata *MD : Strings)
22600b57cec5SDimitry Andric     Blob.append(cast<MDString>(MD)->getString());
22610b57cec5SDimitry Andric 
22620b57cec5SDimitry Andric   // Emit the final record.
22630b57cec5SDimitry Andric   Stream.EmitRecordWithBlob(createMetadataStringsAbbrev(), Record, Blob);
22640b57cec5SDimitry Andric   Record.clear();
22650b57cec5SDimitry Andric }
22660b57cec5SDimitry Andric 
22670b57cec5SDimitry Andric // Generates an enum to use as an index in the Abbrev array of Metadata record.
22680b57cec5SDimitry Andric enum MetadataAbbrev : unsigned {
22690b57cec5SDimitry Andric #define HANDLE_MDNODE_LEAF(CLASS) CLASS##AbbrevID,
22700b57cec5SDimitry Andric #include "llvm/IR/Metadata.def"
22710b57cec5SDimitry Andric   LastPlusOne
22720b57cec5SDimitry Andric };
22730b57cec5SDimitry Andric 
writeMetadataRecords(ArrayRef<const Metadata * > MDs,SmallVectorImpl<uint64_t> & Record,std::vector<unsigned> * MDAbbrevs,std::vector<uint64_t> * IndexPos)22740b57cec5SDimitry Andric void ModuleBitcodeWriter::writeMetadataRecords(
22750b57cec5SDimitry Andric     ArrayRef<const Metadata *> MDs, SmallVectorImpl<uint64_t> &Record,
22760b57cec5SDimitry Andric     std::vector<unsigned> *MDAbbrevs, std::vector<uint64_t> *IndexPos) {
22770b57cec5SDimitry Andric   if (MDs.empty())
22780b57cec5SDimitry Andric     return;
22790b57cec5SDimitry Andric 
22800b57cec5SDimitry Andric   // Initialize MDNode abbreviations.
22810b57cec5SDimitry Andric #define HANDLE_MDNODE_LEAF(CLASS) unsigned CLASS##Abbrev = 0;
22820b57cec5SDimitry Andric #include "llvm/IR/Metadata.def"
22830b57cec5SDimitry Andric 
22840b57cec5SDimitry Andric   for (const Metadata *MD : MDs) {
22850b57cec5SDimitry Andric     if (IndexPos)
22860b57cec5SDimitry Andric       IndexPos->push_back(Stream.GetCurrentBitNo());
22870b57cec5SDimitry Andric     if (const MDNode *N = dyn_cast<MDNode>(MD)) {
22880b57cec5SDimitry Andric       assert(N->isResolved() && "Expected forward references to be resolved");
22890b57cec5SDimitry Andric 
22900b57cec5SDimitry Andric       switch (N->getMetadataID()) {
22910b57cec5SDimitry Andric       default:
22920b57cec5SDimitry Andric         llvm_unreachable("Invalid MDNode subclass");
22930b57cec5SDimitry Andric #define HANDLE_MDNODE_LEAF(CLASS)                                              \
22940b57cec5SDimitry Andric   case Metadata::CLASS##Kind:                                                  \
22950b57cec5SDimitry Andric     if (MDAbbrevs)                                                             \
22960b57cec5SDimitry Andric       write##CLASS(cast<CLASS>(N), Record,                                     \
22970b57cec5SDimitry Andric                    (*MDAbbrevs)[MetadataAbbrev::CLASS##AbbrevID]);             \
22980b57cec5SDimitry Andric     else                                                                       \
22990b57cec5SDimitry Andric       write##CLASS(cast<CLASS>(N), Record, CLASS##Abbrev);                     \
23000b57cec5SDimitry Andric     continue;
23010b57cec5SDimitry Andric #include "llvm/IR/Metadata.def"
23020b57cec5SDimitry Andric       }
23030b57cec5SDimitry Andric     }
2304c9157d92SDimitry Andric     if (auto *AL = dyn_cast<DIArgList>(MD)) {
2305c9157d92SDimitry Andric       writeDIArgList(AL, Record);
2306c9157d92SDimitry Andric       continue;
2307c9157d92SDimitry Andric     }
23080b57cec5SDimitry Andric     writeValueAsMetadata(cast<ValueAsMetadata>(MD), Record);
23090b57cec5SDimitry Andric   }
23100b57cec5SDimitry Andric }
23110b57cec5SDimitry Andric 
writeModuleMetadata()23120b57cec5SDimitry Andric void ModuleBitcodeWriter::writeModuleMetadata() {
23130b57cec5SDimitry Andric   if (!VE.hasMDs() && M.named_metadata_empty())
23140b57cec5SDimitry Andric     return;
23150b57cec5SDimitry Andric 
23160b57cec5SDimitry Andric   Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 4);
23170b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
23180b57cec5SDimitry Andric 
23190b57cec5SDimitry Andric   // Emit all abbrevs upfront, so that the reader can jump in the middle of the
23200b57cec5SDimitry Andric   // block and load any metadata.
23210b57cec5SDimitry Andric   std::vector<unsigned> MDAbbrevs;
23220b57cec5SDimitry Andric 
23230b57cec5SDimitry Andric   MDAbbrevs.resize(MetadataAbbrev::LastPlusOne);
23240b57cec5SDimitry Andric   MDAbbrevs[MetadataAbbrev::DILocationAbbrevID] = createDILocationAbbrev();
23250b57cec5SDimitry Andric   MDAbbrevs[MetadataAbbrev::GenericDINodeAbbrevID] =
23260b57cec5SDimitry Andric       createGenericDINodeAbbrev();
23270b57cec5SDimitry Andric 
23280b57cec5SDimitry Andric   auto Abbv = std::make_shared<BitCodeAbbrev>();
23290b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_INDEX_OFFSET));
23300b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
23310b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
23320b57cec5SDimitry Andric   unsigned OffsetAbbrev = Stream.EmitAbbrev(std::move(Abbv));
23330b57cec5SDimitry Andric 
23340b57cec5SDimitry Andric   Abbv = std::make_shared<BitCodeAbbrev>();
23350b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_INDEX));
23360b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
23370b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
23380b57cec5SDimitry Andric   unsigned IndexAbbrev = Stream.EmitAbbrev(std::move(Abbv));
23390b57cec5SDimitry Andric 
23400b57cec5SDimitry Andric   // Emit MDStrings together upfront.
23410b57cec5SDimitry Andric   writeMetadataStrings(VE.getMDStrings(), Record);
23420b57cec5SDimitry Andric 
23430b57cec5SDimitry Andric   // We only emit an index for the metadata record if we have more than a given
23440b57cec5SDimitry Andric   // (naive) threshold of metadatas, otherwise it is not worth it.
23450b57cec5SDimitry Andric   if (VE.getNonMDStrings().size() > IndexThreshold) {
23460b57cec5SDimitry Andric     // Write a placeholder value in for the offset of the metadata index,
23470b57cec5SDimitry Andric     // which is written after the records, so that it can include
23480b57cec5SDimitry Andric     // the offset of each entry. The placeholder offset will be
23490b57cec5SDimitry Andric     // updated after all records are emitted.
23500b57cec5SDimitry Andric     uint64_t Vals[] = {0, 0};
23510b57cec5SDimitry Andric     Stream.EmitRecord(bitc::METADATA_INDEX_OFFSET, Vals, OffsetAbbrev);
23520b57cec5SDimitry Andric   }
23530b57cec5SDimitry Andric 
23540b57cec5SDimitry Andric   // Compute and save the bit offset to the current position, which will be
23550b57cec5SDimitry Andric   // patched when we emit the index later. We can simply subtract the 64-bit
23560b57cec5SDimitry Andric   // fixed size from the current bit number to get the location to backpatch.
23570b57cec5SDimitry Andric   uint64_t IndexOffsetRecordBitPos = Stream.GetCurrentBitNo();
23580b57cec5SDimitry Andric 
23590b57cec5SDimitry Andric   // This index will contain the bitpos for each individual record.
23600b57cec5SDimitry Andric   std::vector<uint64_t> IndexPos;
23610b57cec5SDimitry Andric   IndexPos.reserve(VE.getNonMDStrings().size());
23620b57cec5SDimitry Andric 
23630b57cec5SDimitry Andric   // Write all the records
23640b57cec5SDimitry Andric   writeMetadataRecords(VE.getNonMDStrings(), Record, &MDAbbrevs, &IndexPos);
23650b57cec5SDimitry Andric 
23660b57cec5SDimitry Andric   if (VE.getNonMDStrings().size() > IndexThreshold) {
23670b57cec5SDimitry Andric     // Now that we have emitted all the records we will emit the index. But
23680b57cec5SDimitry Andric     // first
23690b57cec5SDimitry Andric     // backpatch the forward reference so that the reader can skip the records
23700b57cec5SDimitry Andric     // efficiently.
23710b57cec5SDimitry Andric     Stream.BackpatchWord64(IndexOffsetRecordBitPos - 64,
23720b57cec5SDimitry Andric                            Stream.GetCurrentBitNo() - IndexOffsetRecordBitPos);
23730b57cec5SDimitry Andric 
23740b57cec5SDimitry Andric     // Delta encode the index.
23750b57cec5SDimitry Andric     uint64_t PreviousValue = IndexOffsetRecordBitPos;
23760b57cec5SDimitry Andric     for (auto &Elt : IndexPos) {
23770b57cec5SDimitry Andric       auto EltDelta = Elt - PreviousValue;
23780b57cec5SDimitry Andric       PreviousValue = Elt;
23790b57cec5SDimitry Andric       Elt = EltDelta;
23800b57cec5SDimitry Andric     }
23810b57cec5SDimitry Andric     // Emit the index record.
23820b57cec5SDimitry Andric     Stream.EmitRecord(bitc::METADATA_INDEX, IndexPos, IndexAbbrev);
23830b57cec5SDimitry Andric     IndexPos.clear();
23840b57cec5SDimitry Andric   }
23850b57cec5SDimitry Andric 
23860b57cec5SDimitry Andric   // Write the named metadata now.
23870b57cec5SDimitry Andric   writeNamedMetadata(Record);
23880b57cec5SDimitry Andric 
23890b57cec5SDimitry Andric   auto AddDeclAttachedMetadata = [&](const GlobalObject &GO) {
23900b57cec5SDimitry Andric     SmallVector<uint64_t, 4> Record;
23910b57cec5SDimitry Andric     Record.push_back(VE.getValueID(&GO));
23920b57cec5SDimitry Andric     pushGlobalMetadataAttachment(Record, GO);
23930b57cec5SDimitry Andric     Stream.EmitRecord(bitc::METADATA_GLOBAL_DECL_ATTACHMENT, Record);
23940b57cec5SDimitry Andric   };
23950b57cec5SDimitry Andric   for (const Function &F : M)
23960b57cec5SDimitry Andric     if (F.isDeclaration() && F.hasMetadata())
23970b57cec5SDimitry Andric       AddDeclAttachedMetadata(F);
23980b57cec5SDimitry Andric   // FIXME: Only store metadata for declarations here, and move data for global
23990b57cec5SDimitry Andric   // variable definitions to a separate block (PR28134).
24000b57cec5SDimitry Andric   for (const GlobalVariable &GV : M.globals())
24010b57cec5SDimitry Andric     if (GV.hasMetadata())
24020b57cec5SDimitry Andric       AddDeclAttachedMetadata(GV);
24030b57cec5SDimitry Andric 
24040b57cec5SDimitry Andric   Stream.ExitBlock();
24050b57cec5SDimitry Andric }
24060b57cec5SDimitry Andric 
writeFunctionMetadata(const Function & F)24070b57cec5SDimitry Andric void ModuleBitcodeWriter::writeFunctionMetadata(const Function &F) {
24080b57cec5SDimitry Andric   if (!VE.hasMDs())
24090b57cec5SDimitry Andric     return;
24100b57cec5SDimitry Andric 
24110b57cec5SDimitry Andric   Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
24120b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
24130b57cec5SDimitry Andric   writeMetadataStrings(VE.getMDStrings(), Record);
24140b57cec5SDimitry Andric   writeMetadataRecords(VE.getNonMDStrings(), Record);
24150b57cec5SDimitry Andric   Stream.ExitBlock();
24160b57cec5SDimitry Andric }
24170b57cec5SDimitry Andric 
pushGlobalMetadataAttachment(SmallVectorImpl<uint64_t> & Record,const GlobalObject & GO)24180b57cec5SDimitry Andric void ModuleBitcodeWriter::pushGlobalMetadataAttachment(
24190b57cec5SDimitry Andric     SmallVectorImpl<uint64_t> &Record, const GlobalObject &GO) {
24200b57cec5SDimitry Andric   // [n x [id, mdnode]]
24210b57cec5SDimitry Andric   SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
24220b57cec5SDimitry Andric   GO.getAllMetadata(MDs);
24230b57cec5SDimitry Andric   for (const auto &I : MDs) {
24240b57cec5SDimitry Andric     Record.push_back(I.first);
24250b57cec5SDimitry Andric     Record.push_back(VE.getMetadataID(I.second));
24260b57cec5SDimitry Andric   }
24270b57cec5SDimitry Andric }
24280b57cec5SDimitry Andric 
writeFunctionMetadataAttachment(const Function & F)24290b57cec5SDimitry Andric void ModuleBitcodeWriter::writeFunctionMetadataAttachment(const Function &F) {
24300b57cec5SDimitry Andric   Stream.EnterSubblock(bitc::METADATA_ATTACHMENT_ID, 3);
24310b57cec5SDimitry Andric 
24320b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
24330b57cec5SDimitry Andric 
24340b57cec5SDimitry Andric   if (F.hasMetadata()) {
24350b57cec5SDimitry Andric     pushGlobalMetadataAttachment(Record, F);
24360b57cec5SDimitry Andric     Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
24370b57cec5SDimitry Andric     Record.clear();
24380b57cec5SDimitry Andric   }
24390b57cec5SDimitry Andric 
24400b57cec5SDimitry Andric   // Write metadata attachments
24410b57cec5SDimitry Andric   // METADATA_ATTACHMENT - [m x [value, [n x [id, mdnode]]]
24420b57cec5SDimitry Andric   SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
24430b57cec5SDimitry Andric   for (const BasicBlock &BB : F)
24440b57cec5SDimitry Andric     for (const Instruction &I : BB) {
24450b57cec5SDimitry Andric       MDs.clear();
24460b57cec5SDimitry Andric       I.getAllMetadataOtherThanDebugLoc(MDs);
24470b57cec5SDimitry Andric 
24480b57cec5SDimitry Andric       // If no metadata, ignore instruction.
24490b57cec5SDimitry Andric       if (MDs.empty()) continue;
24500b57cec5SDimitry Andric 
24510b57cec5SDimitry Andric       Record.push_back(VE.getInstructionID(&I));
24520b57cec5SDimitry Andric 
24530b57cec5SDimitry Andric       for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
24540b57cec5SDimitry Andric         Record.push_back(MDs[i].first);
24550b57cec5SDimitry Andric         Record.push_back(VE.getMetadataID(MDs[i].second));
24560b57cec5SDimitry Andric       }
24570b57cec5SDimitry Andric       Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
24580b57cec5SDimitry Andric       Record.clear();
24590b57cec5SDimitry Andric     }
24600b57cec5SDimitry Andric 
24610b57cec5SDimitry Andric   Stream.ExitBlock();
24620b57cec5SDimitry Andric }
24630b57cec5SDimitry Andric 
writeModuleMetadataKinds()24640b57cec5SDimitry Andric void ModuleBitcodeWriter::writeModuleMetadataKinds() {
24650b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
24660b57cec5SDimitry Andric 
24670b57cec5SDimitry Andric   // Write metadata kinds
24680b57cec5SDimitry Andric   // METADATA_KIND - [n x [id, name]]
24690b57cec5SDimitry Andric   SmallVector<StringRef, 8> Names;
24700b57cec5SDimitry Andric   M.getMDKindNames(Names);
24710b57cec5SDimitry Andric 
24720b57cec5SDimitry Andric   if (Names.empty()) return;
24730b57cec5SDimitry Andric 
24740b57cec5SDimitry Andric   Stream.EnterSubblock(bitc::METADATA_KIND_BLOCK_ID, 3);
24750b57cec5SDimitry Andric 
24760b57cec5SDimitry Andric   for (unsigned MDKindID = 0, e = Names.size(); MDKindID != e; ++MDKindID) {
24770b57cec5SDimitry Andric     Record.push_back(MDKindID);
24780b57cec5SDimitry Andric     StringRef KName = Names[MDKindID];
24790b57cec5SDimitry Andric     Record.append(KName.begin(), KName.end());
24800b57cec5SDimitry Andric 
24810b57cec5SDimitry Andric     Stream.EmitRecord(bitc::METADATA_KIND, Record, 0);
24820b57cec5SDimitry Andric     Record.clear();
24830b57cec5SDimitry Andric   }
24840b57cec5SDimitry Andric 
24850b57cec5SDimitry Andric   Stream.ExitBlock();
24860b57cec5SDimitry Andric }
24870b57cec5SDimitry Andric 
writeOperandBundleTags()24880b57cec5SDimitry Andric void ModuleBitcodeWriter::writeOperandBundleTags() {
24890b57cec5SDimitry Andric   // Write metadata kinds
24900b57cec5SDimitry Andric   //
24910b57cec5SDimitry Andric   // OPERAND_BUNDLE_TAGS_BLOCK_ID : N x OPERAND_BUNDLE_TAG
24920b57cec5SDimitry Andric   //
24930b57cec5SDimitry Andric   // OPERAND_BUNDLE_TAG - [strchr x N]
24940b57cec5SDimitry Andric 
24950b57cec5SDimitry Andric   SmallVector<StringRef, 8> Tags;
24960b57cec5SDimitry Andric   M.getOperandBundleTags(Tags);
24970b57cec5SDimitry Andric 
24980b57cec5SDimitry Andric   if (Tags.empty())
24990b57cec5SDimitry Andric     return;
25000b57cec5SDimitry Andric 
25010b57cec5SDimitry Andric   Stream.EnterSubblock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID, 3);
25020b57cec5SDimitry Andric 
25030b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
25040b57cec5SDimitry Andric 
25050b57cec5SDimitry Andric   for (auto Tag : Tags) {
25060b57cec5SDimitry Andric     Record.append(Tag.begin(), Tag.end());
25070b57cec5SDimitry Andric 
25080b57cec5SDimitry Andric     Stream.EmitRecord(bitc::OPERAND_BUNDLE_TAG, Record, 0);
25090b57cec5SDimitry Andric     Record.clear();
25100b57cec5SDimitry Andric   }
25110b57cec5SDimitry Andric 
25120b57cec5SDimitry Andric   Stream.ExitBlock();
25130b57cec5SDimitry Andric }
25140b57cec5SDimitry Andric 
writeSyncScopeNames()25150b57cec5SDimitry Andric void ModuleBitcodeWriter::writeSyncScopeNames() {
25160b57cec5SDimitry Andric   SmallVector<StringRef, 8> SSNs;
25170b57cec5SDimitry Andric   M.getContext().getSyncScopeNames(SSNs);
25180b57cec5SDimitry Andric   if (SSNs.empty())
25190b57cec5SDimitry Andric     return;
25200b57cec5SDimitry Andric 
25210b57cec5SDimitry Andric   Stream.EnterSubblock(bitc::SYNC_SCOPE_NAMES_BLOCK_ID, 2);
25220b57cec5SDimitry Andric 
25230b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
25240b57cec5SDimitry Andric   for (auto SSN : SSNs) {
25250b57cec5SDimitry Andric     Record.append(SSN.begin(), SSN.end());
25260b57cec5SDimitry Andric     Stream.EmitRecord(bitc::SYNC_SCOPE_NAME, Record, 0);
25270b57cec5SDimitry Andric     Record.clear();
25280b57cec5SDimitry Andric   }
25290b57cec5SDimitry Andric 
25300b57cec5SDimitry Andric   Stream.ExitBlock();
25310b57cec5SDimitry Andric }
25320b57cec5SDimitry Andric 
writeConstants(unsigned FirstVal,unsigned LastVal,bool isGlobal)25330b57cec5SDimitry Andric void ModuleBitcodeWriter::writeConstants(unsigned FirstVal, unsigned LastVal,
25340b57cec5SDimitry Andric                                          bool isGlobal) {
25350b57cec5SDimitry Andric   if (FirstVal == LastVal) return;
25360b57cec5SDimitry Andric 
25370b57cec5SDimitry Andric   Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 4);
25380b57cec5SDimitry Andric 
25390b57cec5SDimitry Andric   unsigned AggregateAbbrev = 0;
25400b57cec5SDimitry Andric   unsigned String8Abbrev = 0;
25410b57cec5SDimitry Andric   unsigned CString7Abbrev = 0;
25420b57cec5SDimitry Andric   unsigned CString6Abbrev = 0;
25430b57cec5SDimitry Andric   // If this is a constant pool for the module, emit module-specific abbrevs.
25440b57cec5SDimitry Andric   if (isGlobal) {
25450b57cec5SDimitry Andric     // Abbrev for CST_CODE_AGGREGATE.
25460b57cec5SDimitry Andric     auto Abbv = std::make_shared<BitCodeAbbrev>();
25470b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_AGGREGATE));
25480b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
25490b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal+1)));
25500b57cec5SDimitry Andric     AggregateAbbrev = Stream.EmitAbbrev(std::move(Abbv));
25510b57cec5SDimitry Andric 
25520b57cec5SDimitry Andric     // Abbrev for CST_CODE_STRING.
25530b57cec5SDimitry Andric     Abbv = std::make_shared<BitCodeAbbrev>();
25540b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_STRING));
25550b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
25560b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
25570b57cec5SDimitry Andric     String8Abbrev = Stream.EmitAbbrev(std::move(Abbv));
25580b57cec5SDimitry Andric     // Abbrev for CST_CODE_CSTRING.
25590b57cec5SDimitry Andric     Abbv = std::make_shared<BitCodeAbbrev>();
25600b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
25610b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
25620b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
25630b57cec5SDimitry Andric     CString7Abbrev = Stream.EmitAbbrev(std::move(Abbv));
25640b57cec5SDimitry Andric     // Abbrev for CST_CODE_CSTRING.
25650b57cec5SDimitry Andric     Abbv = std::make_shared<BitCodeAbbrev>();
25660b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
25670b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
25680b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
25690b57cec5SDimitry Andric     CString6Abbrev = Stream.EmitAbbrev(std::move(Abbv));
25700b57cec5SDimitry Andric   }
25710b57cec5SDimitry Andric 
25720b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
25730b57cec5SDimitry Andric 
25740b57cec5SDimitry Andric   const ValueEnumerator::ValueList &Vals = VE.getValues();
25750b57cec5SDimitry Andric   Type *LastTy = nullptr;
25760b57cec5SDimitry Andric   for (unsigned i = FirstVal; i != LastVal; ++i) {
25770b57cec5SDimitry Andric     const Value *V = Vals[i].first;
25780b57cec5SDimitry Andric     // If we need to switch types, do so now.
25790b57cec5SDimitry Andric     if (V->getType() != LastTy) {
25800b57cec5SDimitry Andric       LastTy = V->getType();
25810b57cec5SDimitry Andric       Record.push_back(VE.getTypeID(LastTy));
25820b57cec5SDimitry Andric       Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record,
25830b57cec5SDimitry Andric                         CONSTANTS_SETTYPE_ABBREV);
25840b57cec5SDimitry Andric       Record.clear();
25850b57cec5SDimitry Andric     }
25860b57cec5SDimitry Andric 
25870b57cec5SDimitry Andric     if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
258804eeddc0SDimitry Andric       Record.push_back(VE.getTypeID(IA->getFunctionType()));
2589fe6060f1SDimitry Andric       Record.push_back(
2590fe6060f1SDimitry Andric           unsigned(IA->hasSideEffects()) | unsigned(IA->isAlignStack()) << 1 |
2591fe6060f1SDimitry Andric           unsigned(IA->getDialect() & 1) << 2 | unsigned(IA->canThrow()) << 3);
25920b57cec5SDimitry Andric 
25930b57cec5SDimitry Andric       // Add the asm string.
25940b57cec5SDimitry Andric       const std::string &AsmStr = IA->getAsmString();
25950b57cec5SDimitry Andric       Record.push_back(AsmStr.size());
25960b57cec5SDimitry Andric       Record.append(AsmStr.begin(), AsmStr.end());
25970b57cec5SDimitry Andric 
25980b57cec5SDimitry Andric       // Add the constraint string.
25990b57cec5SDimitry Andric       const std::string &ConstraintStr = IA->getConstraintString();
26000b57cec5SDimitry Andric       Record.push_back(ConstraintStr.size());
26010b57cec5SDimitry Andric       Record.append(ConstraintStr.begin(), ConstraintStr.end());
26020b57cec5SDimitry Andric       Stream.EmitRecord(bitc::CST_CODE_INLINEASM, Record);
26030b57cec5SDimitry Andric       Record.clear();
26040b57cec5SDimitry Andric       continue;
26050b57cec5SDimitry Andric     }
26060b57cec5SDimitry Andric     const Constant *C = cast<Constant>(V);
26070b57cec5SDimitry Andric     unsigned Code = -1U;
26080b57cec5SDimitry Andric     unsigned AbbrevToUse = 0;
26090b57cec5SDimitry Andric     if (C->isNullValue()) {
26100b57cec5SDimitry Andric       Code = bitc::CST_CODE_NULL;
2611e8d8bef9SDimitry Andric     } else if (isa<PoisonValue>(C)) {
2612e8d8bef9SDimitry Andric       Code = bitc::CST_CODE_POISON;
26130b57cec5SDimitry Andric     } else if (isa<UndefValue>(C)) {
26140b57cec5SDimitry Andric       Code = bitc::CST_CODE_UNDEF;
26150b57cec5SDimitry Andric     } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {
26160b57cec5SDimitry Andric       if (IV->getBitWidth() <= 64) {
26170b57cec5SDimitry Andric         uint64_t V = IV->getSExtValue();
26180b57cec5SDimitry Andric         emitSignedInt64(Record, V);
26190b57cec5SDimitry Andric         Code = bitc::CST_CODE_INTEGER;
26200b57cec5SDimitry Andric         AbbrevToUse = CONSTANTS_INTEGER_ABBREV;
26210b57cec5SDimitry Andric       } else {                             // Wide integers, > 64 bits in size.
26225ffd83dbSDimitry Andric         emitWideAPInt(Record, IV->getValue());
26230b57cec5SDimitry Andric         Code = bitc::CST_CODE_WIDE_INTEGER;
26240b57cec5SDimitry Andric       }
26250b57cec5SDimitry Andric     } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
26260b57cec5SDimitry Andric       Code = bitc::CST_CODE_FLOAT;
26270b57cec5SDimitry Andric       Type *Ty = CFP->getType();
26285ffd83dbSDimitry Andric       if (Ty->isHalfTy() || Ty->isBFloatTy() || Ty->isFloatTy() ||
26295ffd83dbSDimitry Andric           Ty->isDoubleTy()) {
26300b57cec5SDimitry Andric         Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
26310b57cec5SDimitry Andric       } else if (Ty->isX86_FP80Ty()) {
26320b57cec5SDimitry Andric         // api needed to prevent premature destruction
26330b57cec5SDimitry Andric         // bits are not in the same order as a normal i80 APInt, compensate.
26340b57cec5SDimitry Andric         APInt api = CFP->getValueAPF().bitcastToAPInt();
26350b57cec5SDimitry Andric         const uint64_t *p = api.getRawData();
26360b57cec5SDimitry Andric         Record.push_back((p[1] << 48) | (p[0] >> 16));
26370b57cec5SDimitry Andric         Record.push_back(p[0] & 0xffffLL);
26380b57cec5SDimitry Andric       } else if (Ty->isFP128Ty() || Ty->isPPC_FP128Ty()) {
26390b57cec5SDimitry Andric         APInt api = CFP->getValueAPF().bitcastToAPInt();
26400b57cec5SDimitry Andric         const uint64_t *p = api.getRawData();
26410b57cec5SDimitry Andric         Record.push_back(p[0]);
26420b57cec5SDimitry Andric         Record.push_back(p[1]);
26430b57cec5SDimitry Andric       } else {
26440b57cec5SDimitry Andric         assert(0 && "Unknown FP type!");
26450b57cec5SDimitry Andric       }
26460b57cec5SDimitry Andric     } else if (isa<ConstantDataSequential>(C) &&
26470b57cec5SDimitry Andric                cast<ConstantDataSequential>(C)->isString()) {
26480b57cec5SDimitry Andric       const ConstantDataSequential *Str = cast<ConstantDataSequential>(C);
26490b57cec5SDimitry Andric       // Emit constant strings specially.
26500b57cec5SDimitry Andric       unsigned NumElts = Str->getNumElements();
26510b57cec5SDimitry Andric       // If this is a null-terminated string, use the denser CSTRING encoding.
26520b57cec5SDimitry Andric       if (Str->isCString()) {
26530b57cec5SDimitry Andric         Code = bitc::CST_CODE_CSTRING;
26540b57cec5SDimitry Andric         --NumElts;  // Don't encode the null, which isn't allowed by char6.
26550b57cec5SDimitry Andric       } else {
26560b57cec5SDimitry Andric         Code = bitc::CST_CODE_STRING;
26570b57cec5SDimitry Andric         AbbrevToUse = String8Abbrev;
26580b57cec5SDimitry Andric       }
26590b57cec5SDimitry Andric       bool isCStr7 = Code == bitc::CST_CODE_CSTRING;
26600b57cec5SDimitry Andric       bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING;
26610b57cec5SDimitry Andric       for (unsigned i = 0; i != NumElts; ++i) {
26620b57cec5SDimitry Andric         unsigned char V = Str->getElementAsInteger(i);
26630b57cec5SDimitry Andric         Record.push_back(V);
26640b57cec5SDimitry Andric         isCStr7 &= (V & 128) == 0;
26650b57cec5SDimitry Andric         if (isCStrChar6)
26660b57cec5SDimitry Andric           isCStrChar6 = BitCodeAbbrevOp::isChar6(V);
26670b57cec5SDimitry Andric       }
26680b57cec5SDimitry Andric 
26690b57cec5SDimitry Andric       if (isCStrChar6)
26700b57cec5SDimitry Andric         AbbrevToUse = CString6Abbrev;
26710b57cec5SDimitry Andric       else if (isCStr7)
26720b57cec5SDimitry Andric         AbbrevToUse = CString7Abbrev;
26730b57cec5SDimitry Andric     } else if (const ConstantDataSequential *CDS =
26740b57cec5SDimitry Andric                   dyn_cast<ConstantDataSequential>(C)) {
26750b57cec5SDimitry Andric       Code = bitc::CST_CODE_DATA;
26765ffd83dbSDimitry Andric       Type *EltTy = CDS->getElementType();
26770b57cec5SDimitry Andric       if (isa<IntegerType>(EltTy)) {
26780b57cec5SDimitry Andric         for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
26790b57cec5SDimitry Andric           Record.push_back(CDS->getElementAsInteger(i));
26800b57cec5SDimitry Andric       } else {
26810b57cec5SDimitry Andric         for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
26820b57cec5SDimitry Andric           Record.push_back(
26830b57cec5SDimitry Andric               CDS->getElementAsAPFloat(i).bitcastToAPInt().getLimitedValue());
26840b57cec5SDimitry Andric       }
26850b57cec5SDimitry Andric     } else if (isa<ConstantAggregate>(C)) {
26860b57cec5SDimitry Andric       Code = bitc::CST_CODE_AGGREGATE;
26870b57cec5SDimitry Andric       for (const Value *Op : C->operands())
26880b57cec5SDimitry Andric         Record.push_back(VE.getValueID(Op));
26890b57cec5SDimitry Andric       AbbrevToUse = AggregateAbbrev;
26900b57cec5SDimitry Andric     } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
26910b57cec5SDimitry Andric       switch (CE->getOpcode()) {
26920b57cec5SDimitry Andric       default:
26930b57cec5SDimitry Andric         if (Instruction::isCast(CE->getOpcode())) {
26940b57cec5SDimitry Andric           Code = bitc::CST_CODE_CE_CAST;
26950b57cec5SDimitry Andric           Record.push_back(getEncodedCastOpcode(CE->getOpcode()));
26960b57cec5SDimitry Andric           Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
26970b57cec5SDimitry Andric           Record.push_back(VE.getValueID(C->getOperand(0)));
26980b57cec5SDimitry Andric           AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;
26990b57cec5SDimitry Andric         } else {
27000b57cec5SDimitry Andric           assert(CE->getNumOperands() == 2 && "Unknown constant expr!");
27010b57cec5SDimitry Andric           Code = bitc::CST_CODE_CE_BINOP;
27020b57cec5SDimitry Andric           Record.push_back(getEncodedBinaryOpcode(CE->getOpcode()));
27030b57cec5SDimitry Andric           Record.push_back(VE.getValueID(C->getOperand(0)));
27040b57cec5SDimitry Andric           Record.push_back(VE.getValueID(C->getOperand(1)));
27050b57cec5SDimitry Andric           uint64_t Flags = getOptimizationFlags(CE);
27060b57cec5SDimitry Andric           if (Flags != 0)
27070b57cec5SDimitry Andric             Record.push_back(Flags);
27080b57cec5SDimitry Andric         }
27090b57cec5SDimitry Andric         break;
27100b57cec5SDimitry Andric       case Instruction::FNeg: {
27110b57cec5SDimitry Andric         assert(CE->getNumOperands() == 1 && "Unknown constant expr!");
27120b57cec5SDimitry Andric         Code = bitc::CST_CODE_CE_UNOP;
27130b57cec5SDimitry Andric         Record.push_back(getEncodedUnaryOpcode(CE->getOpcode()));
27140b57cec5SDimitry Andric         Record.push_back(VE.getValueID(C->getOperand(0)));
27150b57cec5SDimitry Andric         uint64_t Flags = getOptimizationFlags(CE);
27160b57cec5SDimitry Andric         if (Flags != 0)
27170b57cec5SDimitry Andric           Record.push_back(Flags);
27180b57cec5SDimitry Andric         break;
27190b57cec5SDimitry Andric       }
27200b57cec5SDimitry Andric       case Instruction::GetElementPtr: {
27210b57cec5SDimitry Andric         Code = bitc::CST_CODE_CE_GEP;
27220b57cec5SDimitry Andric         const auto *GO = cast<GEPOperator>(C);
27230b57cec5SDimitry Andric         Record.push_back(VE.getTypeID(GO->getSourceElementType()));
2724bdd1243dSDimitry Andric         if (std::optional<unsigned> Idx = GO->getInRangeIndex()) {
27250b57cec5SDimitry Andric           Code = bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX;
27260b57cec5SDimitry Andric           Record.push_back((*Idx << 1) | GO->isInBounds());
27270b57cec5SDimitry Andric         } else if (GO->isInBounds())
27280b57cec5SDimitry Andric           Code = bitc::CST_CODE_CE_INBOUNDS_GEP;
27290b57cec5SDimitry Andric         for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
27300b57cec5SDimitry Andric           Record.push_back(VE.getTypeID(C->getOperand(i)->getType()));
27310b57cec5SDimitry Andric           Record.push_back(VE.getValueID(C->getOperand(i)));
27320b57cec5SDimitry Andric         }
27330b57cec5SDimitry Andric         break;
27340b57cec5SDimitry Andric       }
27350b57cec5SDimitry Andric       case Instruction::ExtractElement:
27360b57cec5SDimitry Andric         Code = bitc::CST_CODE_CE_EXTRACTELT;
27370b57cec5SDimitry Andric         Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
27380b57cec5SDimitry Andric         Record.push_back(VE.getValueID(C->getOperand(0)));
27390b57cec5SDimitry Andric         Record.push_back(VE.getTypeID(C->getOperand(1)->getType()));
27400b57cec5SDimitry Andric         Record.push_back(VE.getValueID(C->getOperand(1)));
27410b57cec5SDimitry Andric         break;
27420b57cec5SDimitry Andric       case Instruction::InsertElement:
27430b57cec5SDimitry Andric         Code = bitc::CST_CODE_CE_INSERTELT;
27440b57cec5SDimitry Andric         Record.push_back(VE.getValueID(C->getOperand(0)));
27450b57cec5SDimitry Andric         Record.push_back(VE.getValueID(C->getOperand(1)));
27460b57cec5SDimitry Andric         Record.push_back(VE.getTypeID(C->getOperand(2)->getType()));
27470b57cec5SDimitry Andric         Record.push_back(VE.getValueID(C->getOperand(2)));
27480b57cec5SDimitry Andric         break;
27490b57cec5SDimitry Andric       case Instruction::ShuffleVector:
27500b57cec5SDimitry Andric         // If the return type and argument types are the same, this is a
27510b57cec5SDimitry Andric         // standard shufflevector instruction.  If the types are different,
27520b57cec5SDimitry Andric         // then the shuffle is widening or truncating the input vectors, and
27530b57cec5SDimitry Andric         // the argument type must also be encoded.
27540b57cec5SDimitry Andric         if (C->getType() == C->getOperand(0)->getType()) {
27550b57cec5SDimitry Andric           Code = bitc::CST_CODE_CE_SHUFFLEVEC;
27560b57cec5SDimitry Andric         } else {
27570b57cec5SDimitry Andric           Code = bitc::CST_CODE_CE_SHUFVEC_EX;
27580b57cec5SDimitry Andric           Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
27590b57cec5SDimitry Andric         }
27600b57cec5SDimitry Andric         Record.push_back(VE.getValueID(C->getOperand(0)));
27610b57cec5SDimitry Andric         Record.push_back(VE.getValueID(C->getOperand(1)));
27625ffd83dbSDimitry Andric         Record.push_back(VE.getValueID(CE->getShuffleMaskForBitcode()));
27630b57cec5SDimitry Andric         break;
27640b57cec5SDimitry Andric       case Instruction::ICmp:
27650b57cec5SDimitry Andric       case Instruction::FCmp:
27660b57cec5SDimitry Andric         Code = bitc::CST_CODE_CE_CMP;
27670b57cec5SDimitry Andric         Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
27680b57cec5SDimitry Andric         Record.push_back(VE.getValueID(C->getOperand(0)));
27690b57cec5SDimitry Andric         Record.push_back(VE.getValueID(C->getOperand(1)));
27700b57cec5SDimitry Andric         Record.push_back(CE->getPredicate());
27710b57cec5SDimitry Andric         break;
27720b57cec5SDimitry Andric       }
27730b57cec5SDimitry Andric     } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) {
27740b57cec5SDimitry Andric       Code = bitc::CST_CODE_BLOCKADDRESS;
27750b57cec5SDimitry Andric       Record.push_back(VE.getTypeID(BA->getFunction()->getType()));
27760b57cec5SDimitry Andric       Record.push_back(VE.getValueID(BA->getFunction()));
27770b57cec5SDimitry Andric       Record.push_back(VE.getGlobalBasicBlockID(BA->getBasicBlock()));
2778fe6060f1SDimitry Andric     } else if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C)) {
2779fe6060f1SDimitry Andric       Code = bitc::CST_CODE_DSO_LOCAL_EQUIVALENT;
2780fe6060f1SDimitry Andric       Record.push_back(VE.getTypeID(Equiv->getGlobalValue()->getType()));
2781fe6060f1SDimitry Andric       Record.push_back(VE.getValueID(Equiv->getGlobalValue()));
27820eae32dcSDimitry Andric     } else if (const auto *NC = dyn_cast<NoCFIValue>(C)) {
27830eae32dcSDimitry Andric       Code = bitc::CST_CODE_NO_CFI_VALUE;
27840eae32dcSDimitry Andric       Record.push_back(VE.getTypeID(NC->getGlobalValue()->getType()));
27850eae32dcSDimitry Andric       Record.push_back(VE.getValueID(NC->getGlobalValue()));
27860b57cec5SDimitry Andric     } else {
27870b57cec5SDimitry Andric #ifndef NDEBUG
27880b57cec5SDimitry Andric       C->dump();
27890b57cec5SDimitry Andric #endif
27900b57cec5SDimitry Andric       llvm_unreachable("Unknown constant!");
27910b57cec5SDimitry Andric     }
27920b57cec5SDimitry Andric     Stream.EmitRecord(Code, Record, AbbrevToUse);
27930b57cec5SDimitry Andric     Record.clear();
27940b57cec5SDimitry Andric   }
27950b57cec5SDimitry Andric 
27960b57cec5SDimitry Andric   Stream.ExitBlock();
27970b57cec5SDimitry Andric }
27980b57cec5SDimitry Andric 
writeModuleConstants()27990b57cec5SDimitry Andric void ModuleBitcodeWriter::writeModuleConstants() {
28000b57cec5SDimitry Andric   const ValueEnumerator::ValueList &Vals = VE.getValues();
28010b57cec5SDimitry Andric 
28020b57cec5SDimitry Andric   // Find the first constant to emit, which is the first non-globalvalue value.
28030b57cec5SDimitry Andric   // We know globalvalues have been emitted by WriteModuleInfo.
28040b57cec5SDimitry Andric   for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
28050b57cec5SDimitry Andric     if (!isa<GlobalValue>(Vals[i].first)) {
28060b57cec5SDimitry Andric       writeConstants(i, Vals.size(), true);
28070b57cec5SDimitry Andric       return;
28080b57cec5SDimitry Andric     }
28090b57cec5SDimitry Andric   }
28100b57cec5SDimitry Andric }
28110b57cec5SDimitry Andric 
28120b57cec5SDimitry Andric /// pushValueAndType - The file has to encode both the value and type id for
28130b57cec5SDimitry Andric /// many values, because we need to know what type to create for forward
28140b57cec5SDimitry Andric /// references.  However, most operands are not forward references, so this type
28150b57cec5SDimitry Andric /// field is not needed.
28160b57cec5SDimitry Andric ///
28170b57cec5SDimitry Andric /// This function adds V's value ID to Vals.  If the value ID is higher than the
28180b57cec5SDimitry Andric /// instruction ID, then it is a forward reference, and it also includes the
28190b57cec5SDimitry Andric /// type ID.  The value ID that is written is encoded relative to the InstID.
pushValueAndType(const Value * V,unsigned InstID,SmallVectorImpl<unsigned> & Vals)28200b57cec5SDimitry Andric bool ModuleBitcodeWriter::pushValueAndType(const Value *V, unsigned InstID,
28210b57cec5SDimitry Andric                                            SmallVectorImpl<unsigned> &Vals) {
28220b57cec5SDimitry Andric   unsigned ValID = VE.getValueID(V);
28230b57cec5SDimitry Andric   // Make encoding relative to the InstID.
28240b57cec5SDimitry Andric   Vals.push_back(InstID - ValID);
28250b57cec5SDimitry Andric   if (ValID >= InstID) {
28260b57cec5SDimitry Andric     Vals.push_back(VE.getTypeID(V->getType()));
28270b57cec5SDimitry Andric     return true;
28280b57cec5SDimitry Andric   }
28290b57cec5SDimitry Andric   return false;
28300b57cec5SDimitry Andric }
28310b57cec5SDimitry Andric 
writeOperandBundles(const CallBase & CS,unsigned InstID)28325ffd83dbSDimitry Andric void ModuleBitcodeWriter::writeOperandBundles(const CallBase &CS,
28330b57cec5SDimitry Andric                                               unsigned InstID) {
28340b57cec5SDimitry Andric   SmallVector<unsigned, 64> Record;
28355ffd83dbSDimitry Andric   LLVMContext &C = CS.getContext();
28360b57cec5SDimitry Andric 
28370b57cec5SDimitry Andric   for (unsigned i = 0, e = CS.getNumOperandBundles(); i != e; ++i) {
28380b57cec5SDimitry Andric     const auto &Bundle = CS.getOperandBundleAt(i);
28390b57cec5SDimitry Andric     Record.push_back(C.getOperandBundleTagID(Bundle.getTagName()));
28400b57cec5SDimitry Andric 
28410b57cec5SDimitry Andric     for (auto &Input : Bundle.Inputs)
28420b57cec5SDimitry Andric       pushValueAndType(Input, InstID, Record);
28430b57cec5SDimitry Andric 
28440b57cec5SDimitry Andric     Stream.EmitRecord(bitc::FUNC_CODE_OPERAND_BUNDLE, Record);
28450b57cec5SDimitry Andric     Record.clear();
28460b57cec5SDimitry Andric   }
28470b57cec5SDimitry Andric }
28480b57cec5SDimitry Andric 
28490b57cec5SDimitry Andric /// pushValue - Like pushValueAndType, but where the type of the value is
28500b57cec5SDimitry Andric /// omitted (perhaps it was already encoded in an earlier operand).
pushValue(const Value * V,unsigned InstID,SmallVectorImpl<unsigned> & Vals)28510b57cec5SDimitry Andric void ModuleBitcodeWriter::pushValue(const Value *V, unsigned InstID,
28520b57cec5SDimitry Andric                                     SmallVectorImpl<unsigned> &Vals) {
28530b57cec5SDimitry Andric   unsigned ValID = VE.getValueID(V);
28540b57cec5SDimitry Andric   Vals.push_back(InstID - ValID);
28550b57cec5SDimitry Andric }
28560b57cec5SDimitry Andric 
pushValueSigned(const Value * V,unsigned InstID,SmallVectorImpl<uint64_t> & Vals)28570b57cec5SDimitry Andric void ModuleBitcodeWriter::pushValueSigned(const Value *V, unsigned InstID,
28580b57cec5SDimitry Andric                                           SmallVectorImpl<uint64_t> &Vals) {
28590b57cec5SDimitry Andric   unsigned ValID = VE.getValueID(V);
28600b57cec5SDimitry Andric   int64_t diff = ((int32_t)InstID - (int32_t)ValID);
28610b57cec5SDimitry Andric   emitSignedInt64(Vals, diff);
28620b57cec5SDimitry Andric }
28630b57cec5SDimitry Andric 
28640b57cec5SDimitry Andric /// WriteInstruction - Emit an instruction to the specified stream.
writeInstruction(const Instruction & I,unsigned InstID,SmallVectorImpl<unsigned> & Vals)28650b57cec5SDimitry Andric void ModuleBitcodeWriter::writeInstruction(const Instruction &I,
28660b57cec5SDimitry Andric                                            unsigned InstID,
28670b57cec5SDimitry Andric                                            SmallVectorImpl<unsigned> &Vals) {
28680b57cec5SDimitry Andric   unsigned Code = 0;
28690b57cec5SDimitry Andric   unsigned AbbrevToUse = 0;
28700b57cec5SDimitry Andric   VE.setInstructionID(&I);
28710b57cec5SDimitry Andric   switch (I.getOpcode()) {
28720b57cec5SDimitry Andric   default:
28730b57cec5SDimitry Andric     if (Instruction::isCast(I.getOpcode())) {
28740b57cec5SDimitry Andric       Code = bitc::FUNC_CODE_INST_CAST;
28750b57cec5SDimitry Andric       if (!pushValueAndType(I.getOperand(0), InstID, Vals))
28760b57cec5SDimitry Andric         AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
28770b57cec5SDimitry Andric       Vals.push_back(VE.getTypeID(I.getType()));
28780b57cec5SDimitry Andric       Vals.push_back(getEncodedCastOpcode(I.getOpcode()));
2879c9157d92SDimitry Andric       uint64_t Flags = getOptimizationFlags(&I);
2880c9157d92SDimitry Andric       if (Flags != 0) {
2881c9157d92SDimitry Andric         if (AbbrevToUse == FUNCTION_INST_CAST_ABBREV)
2882c9157d92SDimitry Andric           AbbrevToUse = FUNCTION_INST_CAST_FLAGS_ABBREV;
2883c9157d92SDimitry Andric         Vals.push_back(Flags);
2884c9157d92SDimitry Andric       }
28850b57cec5SDimitry Andric     } else {
28860b57cec5SDimitry Andric       assert(isa<BinaryOperator>(I) && "Unknown instruction!");
28870b57cec5SDimitry Andric       Code = bitc::FUNC_CODE_INST_BINOP;
28880b57cec5SDimitry Andric       if (!pushValueAndType(I.getOperand(0), InstID, Vals))
28890b57cec5SDimitry Andric         AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
28900b57cec5SDimitry Andric       pushValue(I.getOperand(1), InstID, Vals);
28910b57cec5SDimitry Andric       Vals.push_back(getEncodedBinaryOpcode(I.getOpcode()));
28920b57cec5SDimitry Andric       uint64_t Flags = getOptimizationFlags(&I);
28930b57cec5SDimitry Andric       if (Flags != 0) {
28940b57cec5SDimitry Andric         if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV)
28950b57cec5SDimitry Andric           AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV;
28960b57cec5SDimitry Andric         Vals.push_back(Flags);
28970b57cec5SDimitry Andric       }
28980b57cec5SDimitry Andric     }
28990b57cec5SDimitry Andric     break;
29000b57cec5SDimitry Andric   case Instruction::FNeg: {
29010b57cec5SDimitry Andric     Code = bitc::FUNC_CODE_INST_UNOP;
29020b57cec5SDimitry Andric     if (!pushValueAndType(I.getOperand(0), InstID, Vals))
29030b57cec5SDimitry Andric       AbbrevToUse = FUNCTION_INST_UNOP_ABBREV;
29040b57cec5SDimitry Andric     Vals.push_back(getEncodedUnaryOpcode(I.getOpcode()));
29050b57cec5SDimitry Andric     uint64_t Flags = getOptimizationFlags(&I);
29060b57cec5SDimitry Andric     if (Flags != 0) {
29070b57cec5SDimitry Andric       if (AbbrevToUse == FUNCTION_INST_UNOP_ABBREV)
29080b57cec5SDimitry Andric         AbbrevToUse = FUNCTION_INST_UNOP_FLAGS_ABBREV;
29090b57cec5SDimitry Andric       Vals.push_back(Flags);
29100b57cec5SDimitry Andric     }
29110b57cec5SDimitry Andric     break;
29120b57cec5SDimitry Andric   }
29130b57cec5SDimitry Andric   case Instruction::GetElementPtr: {
29140b57cec5SDimitry Andric     Code = bitc::FUNC_CODE_INST_GEP;
29150b57cec5SDimitry Andric     AbbrevToUse = FUNCTION_INST_GEP_ABBREV;
29160b57cec5SDimitry Andric     auto &GEPInst = cast<GetElementPtrInst>(I);
29170b57cec5SDimitry Andric     Vals.push_back(GEPInst.isInBounds());
29180b57cec5SDimitry Andric     Vals.push_back(VE.getTypeID(GEPInst.getSourceElementType()));
29190b57cec5SDimitry Andric     for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
29200b57cec5SDimitry Andric       pushValueAndType(I.getOperand(i), InstID, Vals);
29210b57cec5SDimitry Andric     break;
29220b57cec5SDimitry Andric   }
29230b57cec5SDimitry Andric   case Instruction::ExtractValue: {
29240b57cec5SDimitry Andric     Code = bitc::FUNC_CODE_INST_EXTRACTVAL;
29250b57cec5SDimitry Andric     pushValueAndType(I.getOperand(0), InstID, Vals);
29260b57cec5SDimitry Andric     const ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
29270b57cec5SDimitry Andric     Vals.append(EVI->idx_begin(), EVI->idx_end());
29280b57cec5SDimitry Andric     break;
29290b57cec5SDimitry Andric   }
29300b57cec5SDimitry Andric   case Instruction::InsertValue: {
29310b57cec5SDimitry Andric     Code = bitc::FUNC_CODE_INST_INSERTVAL;
29320b57cec5SDimitry Andric     pushValueAndType(I.getOperand(0), InstID, Vals);
29330b57cec5SDimitry Andric     pushValueAndType(I.getOperand(1), InstID, Vals);
29340b57cec5SDimitry Andric     const InsertValueInst *IVI = cast<InsertValueInst>(&I);
29350b57cec5SDimitry Andric     Vals.append(IVI->idx_begin(), IVI->idx_end());
29360b57cec5SDimitry Andric     break;
29370b57cec5SDimitry Andric   }
29380b57cec5SDimitry Andric   case Instruction::Select: {
29390b57cec5SDimitry Andric     Code = bitc::FUNC_CODE_INST_VSELECT;
29400b57cec5SDimitry Andric     pushValueAndType(I.getOperand(1), InstID, Vals);
29410b57cec5SDimitry Andric     pushValue(I.getOperand(2), InstID, Vals);
29420b57cec5SDimitry Andric     pushValueAndType(I.getOperand(0), InstID, Vals);
29430b57cec5SDimitry Andric     uint64_t Flags = getOptimizationFlags(&I);
29440b57cec5SDimitry Andric     if (Flags != 0)
29450b57cec5SDimitry Andric       Vals.push_back(Flags);
29460b57cec5SDimitry Andric     break;
29470b57cec5SDimitry Andric   }
29480b57cec5SDimitry Andric   case Instruction::ExtractElement:
29490b57cec5SDimitry Andric     Code = bitc::FUNC_CODE_INST_EXTRACTELT;
29500b57cec5SDimitry Andric     pushValueAndType(I.getOperand(0), InstID, Vals);
29510b57cec5SDimitry Andric     pushValueAndType(I.getOperand(1), InstID, Vals);
29520b57cec5SDimitry Andric     break;
29530b57cec5SDimitry Andric   case Instruction::InsertElement:
29540b57cec5SDimitry Andric     Code = bitc::FUNC_CODE_INST_INSERTELT;
29550b57cec5SDimitry Andric     pushValueAndType(I.getOperand(0), InstID, Vals);
29560b57cec5SDimitry Andric     pushValue(I.getOperand(1), InstID, Vals);
29570b57cec5SDimitry Andric     pushValueAndType(I.getOperand(2), InstID, Vals);
29580b57cec5SDimitry Andric     break;
29590b57cec5SDimitry Andric   case Instruction::ShuffleVector:
29600b57cec5SDimitry Andric     Code = bitc::FUNC_CODE_INST_SHUFFLEVEC;
29610b57cec5SDimitry Andric     pushValueAndType(I.getOperand(0), InstID, Vals);
29620b57cec5SDimitry Andric     pushValue(I.getOperand(1), InstID, Vals);
29635ffd83dbSDimitry Andric     pushValue(cast<ShuffleVectorInst>(I).getShuffleMaskForBitcode(), InstID,
29645ffd83dbSDimitry Andric               Vals);
29650b57cec5SDimitry Andric     break;
29660b57cec5SDimitry Andric   case Instruction::ICmp:
29670b57cec5SDimitry Andric   case Instruction::FCmp: {
29680b57cec5SDimitry Andric     // compare returning Int1Ty or vector of Int1Ty
29690b57cec5SDimitry Andric     Code = bitc::FUNC_CODE_INST_CMP2;
29700b57cec5SDimitry Andric     pushValueAndType(I.getOperand(0), InstID, Vals);
29710b57cec5SDimitry Andric     pushValue(I.getOperand(1), InstID, Vals);
29720b57cec5SDimitry Andric     Vals.push_back(cast<CmpInst>(I).getPredicate());
29730b57cec5SDimitry Andric     uint64_t Flags = getOptimizationFlags(&I);
29740b57cec5SDimitry Andric     if (Flags != 0)
29750b57cec5SDimitry Andric       Vals.push_back(Flags);
29760b57cec5SDimitry Andric     break;
29770b57cec5SDimitry Andric   }
29780b57cec5SDimitry Andric 
29790b57cec5SDimitry Andric   case Instruction::Ret:
29800b57cec5SDimitry Andric     {
29810b57cec5SDimitry Andric       Code = bitc::FUNC_CODE_INST_RET;
29820b57cec5SDimitry Andric       unsigned NumOperands = I.getNumOperands();
29830b57cec5SDimitry Andric       if (NumOperands == 0)
29840b57cec5SDimitry Andric         AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
29850b57cec5SDimitry Andric       else if (NumOperands == 1) {
29860b57cec5SDimitry Andric         if (!pushValueAndType(I.getOperand(0), InstID, Vals))
29870b57cec5SDimitry Andric           AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
29880b57cec5SDimitry Andric       } else {
29890b57cec5SDimitry Andric         for (unsigned i = 0, e = NumOperands; i != e; ++i)
29900b57cec5SDimitry Andric           pushValueAndType(I.getOperand(i), InstID, Vals);
29910b57cec5SDimitry Andric       }
29920b57cec5SDimitry Andric     }
29930b57cec5SDimitry Andric     break;
29940b57cec5SDimitry Andric   case Instruction::Br:
29950b57cec5SDimitry Andric     {
29960b57cec5SDimitry Andric       Code = bitc::FUNC_CODE_INST_BR;
29970b57cec5SDimitry Andric       const BranchInst &II = cast<BranchInst>(I);
29980b57cec5SDimitry Andric       Vals.push_back(VE.getValueID(II.getSuccessor(0)));
29990b57cec5SDimitry Andric       if (II.isConditional()) {
30000b57cec5SDimitry Andric         Vals.push_back(VE.getValueID(II.getSuccessor(1)));
30010b57cec5SDimitry Andric         pushValue(II.getCondition(), InstID, Vals);
30020b57cec5SDimitry Andric       }
30030b57cec5SDimitry Andric     }
30040b57cec5SDimitry Andric     break;
30050b57cec5SDimitry Andric   case Instruction::Switch:
30060b57cec5SDimitry Andric     {
30070b57cec5SDimitry Andric       Code = bitc::FUNC_CODE_INST_SWITCH;
30080b57cec5SDimitry Andric       const SwitchInst &SI = cast<SwitchInst>(I);
30090b57cec5SDimitry Andric       Vals.push_back(VE.getTypeID(SI.getCondition()->getType()));
30100b57cec5SDimitry Andric       pushValue(SI.getCondition(), InstID, Vals);
30110b57cec5SDimitry Andric       Vals.push_back(VE.getValueID(SI.getDefaultDest()));
30120b57cec5SDimitry Andric       for (auto Case : SI.cases()) {
30130b57cec5SDimitry Andric         Vals.push_back(VE.getValueID(Case.getCaseValue()));
30140b57cec5SDimitry Andric         Vals.push_back(VE.getValueID(Case.getCaseSuccessor()));
30150b57cec5SDimitry Andric       }
30160b57cec5SDimitry Andric     }
30170b57cec5SDimitry Andric     break;
30180b57cec5SDimitry Andric   case Instruction::IndirectBr:
30190b57cec5SDimitry Andric     Code = bitc::FUNC_CODE_INST_INDIRECTBR;
30200b57cec5SDimitry Andric     Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
30210b57cec5SDimitry Andric     // Encode the address operand as relative, but not the basic blocks.
30220b57cec5SDimitry Andric     pushValue(I.getOperand(0), InstID, Vals);
30230b57cec5SDimitry Andric     for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i)
30240b57cec5SDimitry Andric       Vals.push_back(VE.getValueID(I.getOperand(i)));
30250b57cec5SDimitry Andric     break;
30260b57cec5SDimitry Andric 
30270b57cec5SDimitry Andric   case Instruction::Invoke: {
30280b57cec5SDimitry Andric     const InvokeInst *II = cast<InvokeInst>(&I);
30295ffd83dbSDimitry Andric     const Value *Callee = II->getCalledOperand();
30300b57cec5SDimitry Andric     FunctionType *FTy = II->getFunctionType();
30310b57cec5SDimitry Andric 
30320b57cec5SDimitry Andric     if (II->hasOperandBundles())
30335ffd83dbSDimitry Andric       writeOperandBundles(*II, InstID);
30340b57cec5SDimitry Andric 
30350b57cec5SDimitry Andric     Code = bitc::FUNC_CODE_INST_INVOKE;
30360b57cec5SDimitry Andric 
30370b57cec5SDimitry Andric     Vals.push_back(VE.getAttributeListID(II->getAttributes()));
30380b57cec5SDimitry Andric     Vals.push_back(II->getCallingConv() | 1 << 13);
30390b57cec5SDimitry Andric     Vals.push_back(VE.getValueID(II->getNormalDest()));
30400b57cec5SDimitry Andric     Vals.push_back(VE.getValueID(II->getUnwindDest()));
30410b57cec5SDimitry Andric     Vals.push_back(VE.getTypeID(FTy));
30420b57cec5SDimitry Andric     pushValueAndType(Callee, InstID, Vals);
30430b57cec5SDimitry Andric 
30440b57cec5SDimitry Andric     // Emit value #'s for the fixed parameters.
30450b57cec5SDimitry Andric     for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
30460b57cec5SDimitry Andric       pushValue(I.getOperand(i), InstID, Vals); // fixed param.
30470b57cec5SDimitry Andric 
30480b57cec5SDimitry Andric     // Emit type/value pairs for varargs params.
30490b57cec5SDimitry Andric     if (FTy->isVarArg()) {
3050349cc55cSDimitry Andric       for (unsigned i = FTy->getNumParams(), e = II->arg_size(); i != e; ++i)
30510b57cec5SDimitry Andric         pushValueAndType(I.getOperand(i), InstID, Vals); // vararg
30520b57cec5SDimitry Andric     }
30530b57cec5SDimitry Andric     break;
30540b57cec5SDimitry Andric   }
30550b57cec5SDimitry Andric   case Instruction::Resume:
30560b57cec5SDimitry Andric     Code = bitc::FUNC_CODE_INST_RESUME;
30570b57cec5SDimitry Andric     pushValueAndType(I.getOperand(0), InstID, Vals);
30580b57cec5SDimitry Andric     break;
30590b57cec5SDimitry Andric   case Instruction::CleanupRet: {
30600b57cec5SDimitry Andric     Code = bitc::FUNC_CODE_INST_CLEANUPRET;
30610b57cec5SDimitry Andric     const auto &CRI = cast<CleanupReturnInst>(I);
30620b57cec5SDimitry Andric     pushValue(CRI.getCleanupPad(), InstID, Vals);
30630b57cec5SDimitry Andric     if (CRI.hasUnwindDest())
30640b57cec5SDimitry Andric       Vals.push_back(VE.getValueID(CRI.getUnwindDest()));
30650b57cec5SDimitry Andric     break;
30660b57cec5SDimitry Andric   }
30670b57cec5SDimitry Andric   case Instruction::CatchRet: {
30680b57cec5SDimitry Andric     Code = bitc::FUNC_CODE_INST_CATCHRET;
30690b57cec5SDimitry Andric     const auto &CRI = cast<CatchReturnInst>(I);
30700b57cec5SDimitry Andric     pushValue(CRI.getCatchPad(), InstID, Vals);
30710b57cec5SDimitry Andric     Vals.push_back(VE.getValueID(CRI.getSuccessor()));
30720b57cec5SDimitry Andric     break;
30730b57cec5SDimitry Andric   }
30740b57cec5SDimitry Andric   case Instruction::CleanupPad:
30750b57cec5SDimitry Andric   case Instruction::CatchPad: {
30760b57cec5SDimitry Andric     const auto &FuncletPad = cast<FuncletPadInst>(I);
30770b57cec5SDimitry Andric     Code = isa<CatchPadInst>(FuncletPad) ? bitc::FUNC_CODE_INST_CATCHPAD
30780b57cec5SDimitry Andric                                          : bitc::FUNC_CODE_INST_CLEANUPPAD;
30790b57cec5SDimitry Andric     pushValue(FuncletPad.getParentPad(), InstID, Vals);
30800b57cec5SDimitry Andric 
3081bdd1243dSDimitry Andric     unsigned NumArgOperands = FuncletPad.arg_size();
30820b57cec5SDimitry Andric     Vals.push_back(NumArgOperands);
30830b57cec5SDimitry Andric     for (unsigned Op = 0; Op != NumArgOperands; ++Op)
30840b57cec5SDimitry Andric       pushValueAndType(FuncletPad.getArgOperand(Op), InstID, Vals);
30850b57cec5SDimitry Andric     break;
30860b57cec5SDimitry Andric   }
30870b57cec5SDimitry Andric   case Instruction::CatchSwitch: {
30880b57cec5SDimitry Andric     Code = bitc::FUNC_CODE_INST_CATCHSWITCH;
30890b57cec5SDimitry Andric     const auto &CatchSwitch = cast<CatchSwitchInst>(I);
30900b57cec5SDimitry Andric 
30910b57cec5SDimitry Andric     pushValue(CatchSwitch.getParentPad(), InstID, Vals);
30920b57cec5SDimitry Andric 
30930b57cec5SDimitry Andric     unsigned NumHandlers = CatchSwitch.getNumHandlers();
30940b57cec5SDimitry Andric     Vals.push_back(NumHandlers);
30950b57cec5SDimitry Andric     for (const BasicBlock *CatchPadBB : CatchSwitch.handlers())
30960b57cec5SDimitry Andric       Vals.push_back(VE.getValueID(CatchPadBB));
30970b57cec5SDimitry Andric 
30980b57cec5SDimitry Andric     if (CatchSwitch.hasUnwindDest())
30990b57cec5SDimitry Andric       Vals.push_back(VE.getValueID(CatchSwitch.getUnwindDest()));
31000b57cec5SDimitry Andric     break;
31010b57cec5SDimitry Andric   }
31020b57cec5SDimitry Andric   case Instruction::CallBr: {
31030b57cec5SDimitry Andric     const CallBrInst *CBI = cast<CallBrInst>(&I);
31045ffd83dbSDimitry Andric     const Value *Callee = CBI->getCalledOperand();
31050b57cec5SDimitry Andric     FunctionType *FTy = CBI->getFunctionType();
31060b57cec5SDimitry Andric 
31070b57cec5SDimitry Andric     if (CBI->hasOperandBundles())
31085ffd83dbSDimitry Andric       writeOperandBundles(*CBI, InstID);
31090b57cec5SDimitry Andric 
31100b57cec5SDimitry Andric     Code = bitc::FUNC_CODE_INST_CALLBR;
31110b57cec5SDimitry Andric 
31120b57cec5SDimitry Andric     Vals.push_back(VE.getAttributeListID(CBI->getAttributes()));
31130b57cec5SDimitry Andric 
31140b57cec5SDimitry Andric     Vals.push_back(CBI->getCallingConv() << bitc::CALL_CCONV |
31150b57cec5SDimitry Andric                    1 << bitc::CALL_EXPLICIT_TYPE);
31160b57cec5SDimitry Andric 
31170b57cec5SDimitry Andric     Vals.push_back(VE.getValueID(CBI->getDefaultDest()));
31180b57cec5SDimitry Andric     Vals.push_back(CBI->getNumIndirectDests());
31190b57cec5SDimitry Andric     for (unsigned i = 0, e = CBI->getNumIndirectDests(); i != e; ++i)
31200b57cec5SDimitry Andric       Vals.push_back(VE.getValueID(CBI->getIndirectDest(i)));
31210b57cec5SDimitry Andric 
31220b57cec5SDimitry Andric     Vals.push_back(VE.getTypeID(FTy));
31230b57cec5SDimitry Andric     pushValueAndType(Callee, InstID, Vals);
31240b57cec5SDimitry Andric 
31250b57cec5SDimitry Andric     // Emit value #'s for the fixed parameters.
31260b57cec5SDimitry Andric     for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
31270b57cec5SDimitry Andric       pushValue(I.getOperand(i), InstID, Vals); // fixed param.
31280b57cec5SDimitry Andric 
31290b57cec5SDimitry Andric     // Emit type/value pairs for varargs params.
31300b57cec5SDimitry Andric     if (FTy->isVarArg()) {
3131349cc55cSDimitry Andric       for (unsigned i = FTy->getNumParams(), e = CBI->arg_size(); i != e; ++i)
31320b57cec5SDimitry Andric         pushValueAndType(I.getOperand(i), InstID, Vals); // vararg
31330b57cec5SDimitry Andric     }
31340b57cec5SDimitry Andric     break;
31350b57cec5SDimitry Andric   }
31360b57cec5SDimitry Andric   case Instruction::Unreachable:
31370b57cec5SDimitry Andric     Code = bitc::FUNC_CODE_INST_UNREACHABLE;
31380b57cec5SDimitry Andric     AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
31390b57cec5SDimitry Andric     break;
31400b57cec5SDimitry Andric 
31410b57cec5SDimitry Andric   case Instruction::PHI: {
31420b57cec5SDimitry Andric     const PHINode &PN = cast<PHINode>(I);
31430b57cec5SDimitry Andric     Code = bitc::FUNC_CODE_INST_PHI;
31440b57cec5SDimitry Andric     // With the newer instruction encoding, forward references could give
31450b57cec5SDimitry Andric     // negative valued IDs.  This is most common for PHIs, so we use
31460b57cec5SDimitry Andric     // signed VBRs.
31470b57cec5SDimitry Andric     SmallVector<uint64_t, 128> Vals64;
31480b57cec5SDimitry Andric     Vals64.push_back(VE.getTypeID(PN.getType()));
31490b57cec5SDimitry Andric     for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
31500b57cec5SDimitry Andric       pushValueSigned(PN.getIncomingValue(i), InstID, Vals64);
31510b57cec5SDimitry Andric       Vals64.push_back(VE.getValueID(PN.getIncomingBlock(i)));
31520b57cec5SDimitry Andric     }
31538bcb0991SDimitry Andric 
31548bcb0991SDimitry Andric     uint64_t Flags = getOptimizationFlags(&I);
31558bcb0991SDimitry Andric     if (Flags != 0)
31568bcb0991SDimitry Andric       Vals64.push_back(Flags);
31578bcb0991SDimitry Andric 
31580b57cec5SDimitry Andric     // Emit a Vals64 vector and exit.
31590b57cec5SDimitry Andric     Stream.EmitRecord(Code, Vals64, AbbrevToUse);
31600b57cec5SDimitry Andric     Vals64.clear();
31610b57cec5SDimitry Andric     return;
31620b57cec5SDimitry Andric   }
31630b57cec5SDimitry Andric 
31640b57cec5SDimitry Andric   case Instruction::LandingPad: {
31650b57cec5SDimitry Andric     const LandingPadInst &LP = cast<LandingPadInst>(I);
31660b57cec5SDimitry Andric     Code = bitc::FUNC_CODE_INST_LANDINGPAD;
31670b57cec5SDimitry Andric     Vals.push_back(VE.getTypeID(LP.getType()));
31680b57cec5SDimitry Andric     Vals.push_back(LP.isCleanup());
31690b57cec5SDimitry Andric     Vals.push_back(LP.getNumClauses());
31700b57cec5SDimitry Andric     for (unsigned I = 0, E = LP.getNumClauses(); I != E; ++I) {
31710b57cec5SDimitry Andric       if (LP.isCatch(I))
31720b57cec5SDimitry Andric         Vals.push_back(LandingPadInst::Catch);
31730b57cec5SDimitry Andric       else
31740b57cec5SDimitry Andric         Vals.push_back(LandingPadInst::Filter);
31750b57cec5SDimitry Andric       pushValueAndType(LP.getClause(I), InstID, Vals);
31760b57cec5SDimitry Andric     }
31770b57cec5SDimitry Andric     break;
31780b57cec5SDimitry Andric   }
31790b57cec5SDimitry Andric 
31800b57cec5SDimitry Andric   case Instruction::Alloca: {
31810b57cec5SDimitry Andric     Code = bitc::FUNC_CODE_INST_ALLOCA;
31820b57cec5SDimitry Andric     const AllocaInst &AI = cast<AllocaInst>(I);
31830b57cec5SDimitry Andric     Vals.push_back(VE.getTypeID(AI.getAllocatedType()));
31840b57cec5SDimitry Andric     Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
31850b57cec5SDimitry Andric     Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
3186e8d8bef9SDimitry Andric     using APV = AllocaPackedValues;
3187e8d8bef9SDimitry Andric     unsigned Record = 0;
3188349cc55cSDimitry Andric     unsigned EncodedAlign = getEncodedAlign(AI.getAlign());
3189349cc55cSDimitry Andric     Bitfield::set<APV::AlignLower>(
3190349cc55cSDimitry Andric         Record, EncodedAlign & ((1 << APV::AlignLower::Bits) - 1));
3191349cc55cSDimitry Andric     Bitfield::set<APV::AlignUpper>(Record,
3192349cc55cSDimitry Andric                                    EncodedAlign >> APV::AlignLower::Bits);
3193e8d8bef9SDimitry Andric     Bitfield::set<APV::UsedWithInAlloca>(Record, AI.isUsedWithInAlloca());
3194e8d8bef9SDimitry Andric     Bitfield::set<APV::ExplicitType>(Record, true);
3195e8d8bef9SDimitry Andric     Bitfield::set<APV::SwiftError>(Record, AI.isSwiftError());
3196e8d8bef9SDimitry Andric     Vals.push_back(Record);
319781ad6265SDimitry Andric 
319881ad6265SDimitry Andric     unsigned AS = AI.getAddressSpace();
319981ad6265SDimitry Andric     if (AS != M.getDataLayout().getAllocaAddrSpace())
320081ad6265SDimitry Andric       Vals.push_back(AS);
32010b57cec5SDimitry Andric     break;
32020b57cec5SDimitry Andric   }
32030b57cec5SDimitry Andric 
32040b57cec5SDimitry Andric   case Instruction::Load:
32050b57cec5SDimitry Andric     if (cast<LoadInst>(I).isAtomic()) {
32060b57cec5SDimitry Andric       Code = bitc::FUNC_CODE_INST_LOADATOMIC;
32070b57cec5SDimitry Andric       pushValueAndType(I.getOperand(0), InstID, Vals);
32080b57cec5SDimitry Andric     } else {
32090b57cec5SDimitry Andric       Code = bitc::FUNC_CODE_INST_LOAD;
32100b57cec5SDimitry Andric       if (!pushValueAndType(I.getOperand(0), InstID, Vals)) // ptr
32110b57cec5SDimitry Andric         AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
32120b57cec5SDimitry Andric     }
32130b57cec5SDimitry Andric     Vals.push_back(VE.getTypeID(I.getType()));
3214e8d8bef9SDimitry Andric     Vals.push_back(getEncodedAlign(cast<LoadInst>(I).getAlign()));
32150b57cec5SDimitry Andric     Vals.push_back(cast<LoadInst>(I).isVolatile());
32160b57cec5SDimitry Andric     if (cast<LoadInst>(I).isAtomic()) {
32170b57cec5SDimitry Andric       Vals.push_back(getEncodedOrdering(cast<LoadInst>(I).getOrdering()));
32180b57cec5SDimitry Andric       Vals.push_back(getEncodedSyncScopeID(cast<LoadInst>(I).getSyncScopeID()));
32190b57cec5SDimitry Andric     }
32200b57cec5SDimitry Andric     break;
32210b57cec5SDimitry Andric   case Instruction::Store:
32220b57cec5SDimitry Andric     if (cast<StoreInst>(I).isAtomic())
32230b57cec5SDimitry Andric       Code = bitc::FUNC_CODE_INST_STOREATOMIC;
32240b57cec5SDimitry Andric     else
32250b57cec5SDimitry Andric       Code = bitc::FUNC_CODE_INST_STORE;
32260b57cec5SDimitry Andric     pushValueAndType(I.getOperand(1), InstID, Vals); // ptrty + ptr
32270b57cec5SDimitry Andric     pushValueAndType(I.getOperand(0), InstID, Vals); // valty + val
3228e8d8bef9SDimitry Andric     Vals.push_back(getEncodedAlign(cast<StoreInst>(I).getAlign()));
32290b57cec5SDimitry Andric     Vals.push_back(cast<StoreInst>(I).isVolatile());
32300b57cec5SDimitry Andric     if (cast<StoreInst>(I).isAtomic()) {
32310b57cec5SDimitry Andric       Vals.push_back(getEncodedOrdering(cast<StoreInst>(I).getOrdering()));
32320b57cec5SDimitry Andric       Vals.push_back(
32330b57cec5SDimitry Andric           getEncodedSyncScopeID(cast<StoreInst>(I).getSyncScopeID()));
32340b57cec5SDimitry Andric     }
32350b57cec5SDimitry Andric     break;
32360b57cec5SDimitry Andric   case Instruction::AtomicCmpXchg:
32370b57cec5SDimitry Andric     Code = bitc::FUNC_CODE_INST_CMPXCHG;
32380b57cec5SDimitry Andric     pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr
32390b57cec5SDimitry Andric     pushValueAndType(I.getOperand(1), InstID, Vals); // cmp.
32400b57cec5SDimitry Andric     pushValue(I.getOperand(2), InstID, Vals);        // newval.
32410b57cec5SDimitry Andric     Vals.push_back(cast<AtomicCmpXchgInst>(I).isVolatile());
32420b57cec5SDimitry Andric     Vals.push_back(
32430b57cec5SDimitry Andric         getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getSuccessOrdering()));
32440b57cec5SDimitry Andric     Vals.push_back(
32450b57cec5SDimitry Andric         getEncodedSyncScopeID(cast<AtomicCmpXchgInst>(I).getSyncScopeID()));
32460b57cec5SDimitry Andric     Vals.push_back(
32470b57cec5SDimitry Andric         getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getFailureOrdering()));
32480b57cec5SDimitry Andric     Vals.push_back(cast<AtomicCmpXchgInst>(I).isWeak());
3249fe6060f1SDimitry Andric     Vals.push_back(getEncodedAlign(cast<AtomicCmpXchgInst>(I).getAlign()));
32500b57cec5SDimitry Andric     break;
32510b57cec5SDimitry Andric   case Instruction::AtomicRMW:
32520b57cec5SDimitry Andric     Code = bitc::FUNC_CODE_INST_ATOMICRMW;
32530b57cec5SDimitry Andric     pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr
3254fe6060f1SDimitry Andric     pushValueAndType(I.getOperand(1), InstID, Vals); // valty + val
32550b57cec5SDimitry Andric     Vals.push_back(
32560b57cec5SDimitry Andric         getEncodedRMWOperation(cast<AtomicRMWInst>(I).getOperation()));
32570b57cec5SDimitry Andric     Vals.push_back(cast<AtomicRMWInst>(I).isVolatile());
32580b57cec5SDimitry Andric     Vals.push_back(getEncodedOrdering(cast<AtomicRMWInst>(I).getOrdering()));
32590b57cec5SDimitry Andric     Vals.push_back(
32600b57cec5SDimitry Andric         getEncodedSyncScopeID(cast<AtomicRMWInst>(I).getSyncScopeID()));
3261fe6060f1SDimitry Andric     Vals.push_back(getEncodedAlign(cast<AtomicRMWInst>(I).getAlign()));
32620b57cec5SDimitry Andric     break;
32630b57cec5SDimitry Andric   case Instruction::Fence:
32640b57cec5SDimitry Andric     Code = bitc::FUNC_CODE_INST_FENCE;
32650b57cec5SDimitry Andric     Vals.push_back(getEncodedOrdering(cast<FenceInst>(I).getOrdering()));
32660b57cec5SDimitry Andric     Vals.push_back(getEncodedSyncScopeID(cast<FenceInst>(I).getSyncScopeID()));
32670b57cec5SDimitry Andric     break;
32680b57cec5SDimitry Andric   case Instruction::Call: {
32690b57cec5SDimitry Andric     const CallInst &CI = cast<CallInst>(I);
32700b57cec5SDimitry Andric     FunctionType *FTy = CI.getFunctionType();
32710b57cec5SDimitry Andric 
32720b57cec5SDimitry Andric     if (CI.hasOperandBundles())
32735ffd83dbSDimitry Andric       writeOperandBundles(CI, InstID);
32740b57cec5SDimitry Andric 
32750b57cec5SDimitry Andric     Code = bitc::FUNC_CODE_INST_CALL;
32760b57cec5SDimitry Andric 
32770b57cec5SDimitry Andric     Vals.push_back(VE.getAttributeListID(CI.getAttributes()));
32780b57cec5SDimitry Andric 
32790b57cec5SDimitry Andric     unsigned Flags = getOptimizationFlags(&I);
32800b57cec5SDimitry Andric     Vals.push_back(CI.getCallingConv() << bitc::CALL_CCONV |
32810b57cec5SDimitry Andric                    unsigned(CI.isTailCall()) << bitc::CALL_TAIL |
32820b57cec5SDimitry Andric                    unsigned(CI.isMustTailCall()) << bitc::CALL_MUSTTAIL |
32830b57cec5SDimitry Andric                    1 << bitc::CALL_EXPLICIT_TYPE |
32840b57cec5SDimitry Andric                    unsigned(CI.isNoTailCall()) << bitc::CALL_NOTAIL |
32850b57cec5SDimitry Andric                    unsigned(Flags != 0) << bitc::CALL_FMF);
32860b57cec5SDimitry Andric     if (Flags != 0)
32870b57cec5SDimitry Andric       Vals.push_back(Flags);
32880b57cec5SDimitry Andric 
32890b57cec5SDimitry Andric     Vals.push_back(VE.getTypeID(FTy));
32905ffd83dbSDimitry Andric     pushValueAndType(CI.getCalledOperand(), InstID, Vals); // Callee
32910b57cec5SDimitry Andric 
32920b57cec5SDimitry Andric     // Emit value #'s for the fixed parameters.
32930b57cec5SDimitry Andric     for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
32940b57cec5SDimitry Andric       // Check for labels (can happen with asm labels).
32950b57cec5SDimitry Andric       if (FTy->getParamType(i)->isLabelTy())
32960b57cec5SDimitry Andric         Vals.push_back(VE.getValueID(CI.getArgOperand(i)));
32970b57cec5SDimitry Andric       else
32980b57cec5SDimitry Andric         pushValue(CI.getArgOperand(i), InstID, Vals); // fixed param.
32990b57cec5SDimitry Andric     }
33000b57cec5SDimitry Andric 
33010b57cec5SDimitry Andric     // Emit type/value pairs for varargs params.
33020b57cec5SDimitry Andric     if (FTy->isVarArg()) {
3303349cc55cSDimitry Andric       for (unsigned i = FTy->getNumParams(), e = CI.arg_size(); i != e; ++i)
33040b57cec5SDimitry Andric         pushValueAndType(CI.getArgOperand(i), InstID, Vals); // varargs
33050b57cec5SDimitry Andric     }
33060b57cec5SDimitry Andric     break;
33070b57cec5SDimitry Andric   }
33080b57cec5SDimitry Andric   case Instruction::VAArg:
33090b57cec5SDimitry Andric     Code = bitc::FUNC_CODE_INST_VAARG;
33100b57cec5SDimitry Andric     Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));   // valistty
33110b57cec5SDimitry Andric     pushValue(I.getOperand(0), InstID, Vals);                   // valist.
33120b57cec5SDimitry Andric     Vals.push_back(VE.getTypeID(I.getType())); // restype.
33130b57cec5SDimitry Andric     break;
3314480093f4SDimitry Andric   case Instruction::Freeze:
3315480093f4SDimitry Andric     Code = bitc::FUNC_CODE_INST_FREEZE;
3316480093f4SDimitry Andric     pushValueAndType(I.getOperand(0), InstID, Vals);
3317480093f4SDimitry Andric     break;
33180b57cec5SDimitry Andric   }
33190b57cec5SDimitry Andric 
33200b57cec5SDimitry Andric   Stream.EmitRecord(Code, Vals, AbbrevToUse);
33210b57cec5SDimitry Andric   Vals.clear();
33220b57cec5SDimitry Andric }
33230b57cec5SDimitry Andric 
33240b57cec5SDimitry Andric /// Write a GlobalValue VST to the module. The purpose of this data structure is
33250b57cec5SDimitry Andric /// to allow clients to efficiently find the function body.
writeGlobalValueSymbolTable(DenseMap<const Function *,uint64_t> & FunctionToBitcodeIndex)33260b57cec5SDimitry Andric void ModuleBitcodeWriter::writeGlobalValueSymbolTable(
33270b57cec5SDimitry Andric   DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) {
33280b57cec5SDimitry Andric   // Get the offset of the VST we are writing, and backpatch it into
33290b57cec5SDimitry Andric   // the VST forward declaration record.
33300b57cec5SDimitry Andric   uint64_t VSTOffset = Stream.GetCurrentBitNo();
33310b57cec5SDimitry Andric   // The BitcodeStartBit was the stream offset of the identification block.
33320b57cec5SDimitry Andric   VSTOffset -= bitcodeStartBit();
33330b57cec5SDimitry Andric   assert((VSTOffset & 31) == 0 && "VST block not 32-bit aligned");
33340b57cec5SDimitry Andric   // Note that we add 1 here because the offset is relative to one word
33350b57cec5SDimitry Andric   // before the start of the identification block, which was historically
33360b57cec5SDimitry Andric   // always the start of the regular bitcode header.
33370b57cec5SDimitry Andric   Stream.BackpatchWord(VSTOffsetPlaceholder, VSTOffset / 32 + 1);
33380b57cec5SDimitry Andric 
33390b57cec5SDimitry Andric   Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
33400b57cec5SDimitry Andric 
33410b57cec5SDimitry Andric   auto Abbv = std::make_shared<BitCodeAbbrev>();
33420b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_FNENTRY));
33430b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
33440b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // funcoffset
33450b57cec5SDimitry Andric   unsigned FnEntryAbbrev = Stream.EmitAbbrev(std::move(Abbv));
33460b57cec5SDimitry Andric 
33470b57cec5SDimitry Andric   for (const Function &F : M) {
33480b57cec5SDimitry Andric     uint64_t Record[2];
33490b57cec5SDimitry Andric 
33500b57cec5SDimitry Andric     if (F.isDeclaration())
33510b57cec5SDimitry Andric       continue;
33520b57cec5SDimitry Andric 
33530b57cec5SDimitry Andric     Record[0] = VE.getValueID(&F);
33540b57cec5SDimitry Andric 
33550b57cec5SDimitry Andric     // Save the word offset of the function (from the start of the
33560b57cec5SDimitry Andric     // actual bitcode written to the stream).
33570b57cec5SDimitry Andric     uint64_t BitcodeIndex = FunctionToBitcodeIndex[&F] - bitcodeStartBit();
33580b57cec5SDimitry Andric     assert((BitcodeIndex & 31) == 0 && "function block not 32-bit aligned");
33590b57cec5SDimitry Andric     // Note that we add 1 here because the offset is relative to one word
33600b57cec5SDimitry Andric     // before the start of the identification block, which was historically
33610b57cec5SDimitry Andric     // always the start of the regular bitcode header.
33620b57cec5SDimitry Andric     Record[1] = BitcodeIndex / 32 + 1;
33630b57cec5SDimitry Andric 
33640b57cec5SDimitry Andric     Stream.EmitRecord(bitc::VST_CODE_FNENTRY, Record, FnEntryAbbrev);
33650b57cec5SDimitry Andric   }
33660b57cec5SDimitry Andric 
33670b57cec5SDimitry Andric   Stream.ExitBlock();
33680b57cec5SDimitry Andric }
33690b57cec5SDimitry Andric 
33700b57cec5SDimitry Andric /// Emit names for arguments, instructions and basic blocks in a function.
writeFunctionLevelValueSymbolTable(const ValueSymbolTable & VST)33710b57cec5SDimitry Andric void ModuleBitcodeWriter::writeFunctionLevelValueSymbolTable(
33720b57cec5SDimitry Andric     const ValueSymbolTable &VST) {
33730b57cec5SDimitry Andric   if (VST.empty())
33740b57cec5SDimitry Andric     return;
33750b57cec5SDimitry Andric 
33760b57cec5SDimitry Andric   Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
33770b57cec5SDimitry Andric 
33780b57cec5SDimitry Andric   // FIXME: Set up the abbrev, we know how many values there are!
33790b57cec5SDimitry Andric   // FIXME: We know if the type names can use 7-bit ascii.
33800b57cec5SDimitry Andric   SmallVector<uint64_t, 64> NameVals;
33810b57cec5SDimitry Andric 
33820b57cec5SDimitry Andric   for (const ValueName &Name : VST) {
33830b57cec5SDimitry Andric     // Figure out the encoding to use for the name.
33840b57cec5SDimitry Andric     StringEncoding Bits = getStringEncoding(Name.getKey());
33850b57cec5SDimitry Andric 
33860b57cec5SDimitry Andric     unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
33870b57cec5SDimitry Andric     NameVals.push_back(VE.getValueID(Name.getValue()));
33880b57cec5SDimitry Andric 
33890b57cec5SDimitry Andric     // VST_CODE_ENTRY:   [valueid, namechar x N]
33900b57cec5SDimitry Andric     // VST_CODE_BBENTRY: [bbid, namechar x N]
33910b57cec5SDimitry Andric     unsigned Code;
33920b57cec5SDimitry Andric     if (isa<BasicBlock>(Name.getValue())) {
33930b57cec5SDimitry Andric       Code = bitc::VST_CODE_BBENTRY;
33940b57cec5SDimitry Andric       if (Bits == SE_Char6)
33950b57cec5SDimitry Andric         AbbrevToUse = VST_BBENTRY_6_ABBREV;
33960b57cec5SDimitry Andric     } else {
33970b57cec5SDimitry Andric       Code = bitc::VST_CODE_ENTRY;
33980b57cec5SDimitry Andric       if (Bits == SE_Char6)
33990b57cec5SDimitry Andric         AbbrevToUse = VST_ENTRY_6_ABBREV;
34000b57cec5SDimitry Andric       else if (Bits == SE_Fixed7)
34010b57cec5SDimitry Andric         AbbrevToUse = VST_ENTRY_7_ABBREV;
34020b57cec5SDimitry Andric     }
34030b57cec5SDimitry Andric 
34040b57cec5SDimitry Andric     for (const auto P : Name.getKey())
34050b57cec5SDimitry Andric       NameVals.push_back((unsigned char)P);
34060b57cec5SDimitry Andric 
34070b57cec5SDimitry Andric     // Emit the finished record.
34080b57cec5SDimitry Andric     Stream.EmitRecord(Code, NameVals, AbbrevToUse);
34090b57cec5SDimitry Andric     NameVals.clear();
34100b57cec5SDimitry Andric   }
34110b57cec5SDimitry Andric 
34120b57cec5SDimitry Andric   Stream.ExitBlock();
34130b57cec5SDimitry Andric }
34140b57cec5SDimitry Andric 
writeUseList(UseListOrder && Order)34150b57cec5SDimitry Andric void ModuleBitcodeWriter::writeUseList(UseListOrder &&Order) {
34160b57cec5SDimitry Andric   assert(Order.Shuffle.size() >= 2 && "Shuffle too small");
34170b57cec5SDimitry Andric   unsigned Code;
34180b57cec5SDimitry Andric   if (isa<BasicBlock>(Order.V))
34190b57cec5SDimitry Andric     Code = bitc::USELIST_CODE_BB;
34200b57cec5SDimitry Andric   else
34210b57cec5SDimitry Andric     Code = bitc::USELIST_CODE_DEFAULT;
34220b57cec5SDimitry Andric 
34230b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record(Order.Shuffle.begin(), Order.Shuffle.end());
34240b57cec5SDimitry Andric   Record.push_back(VE.getValueID(Order.V));
34250b57cec5SDimitry Andric   Stream.EmitRecord(Code, Record);
34260b57cec5SDimitry Andric }
34270b57cec5SDimitry Andric 
writeUseListBlock(const Function * F)34280b57cec5SDimitry Andric void ModuleBitcodeWriter::writeUseListBlock(const Function *F) {
34290b57cec5SDimitry Andric   assert(VE.shouldPreserveUseListOrder() &&
34300b57cec5SDimitry Andric          "Expected to be preserving use-list order");
34310b57cec5SDimitry Andric 
34320b57cec5SDimitry Andric   auto hasMore = [&]() {
34330b57cec5SDimitry Andric     return !VE.UseListOrders.empty() && VE.UseListOrders.back().F == F;
34340b57cec5SDimitry Andric   };
34350b57cec5SDimitry Andric   if (!hasMore())
34360b57cec5SDimitry Andric     // Nothing to do.
34370b57cec5SDimitry Andric     return;
34380b57cec5SDimitry Andric 
34390b57cec5SDimitry Andric   Stream.EnterSubblock(bitc::USELIST_BLOCK_ID, 3);
34400b57cec5SDimitry Andric   while (hasMore()) {
34410b57cec5SDimitry Andric     writeUseList(std::move(VE.UseListOrders.back()));
34420b57cec5SDimitry Andric     VE.UseListOrders.pop_back();
34430b57cec5SDimitry Andric   }
34440b57cec5SDimitry Andric   Stream.ExitBlock();
34450b57cec5SDimitry Andric }
34460b57cec5SDimitry Andric 
34470b57cec5SDimitry Andric /// Emit a function body to the module stream.
writeFunction(const Function & F,DenseMap<const Function *,uint64_t> & FunctionToBitcodeIndex)34480b57cec5SDimitry Andric void ModuleBitcodeWriter::writeFunction(
34490b57cec5SDimitry Andric     const Function &F,
34500b57cec5SDimitry Andric     DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) {
34510b57cec5SDimitry Andric   // Save the bitcode index of the start of this function block for recording
34520b57cec5SDimitry Andric   // in the VST.
34530b57cec5SDimitry Andric   FunctionToBitcodeIndex[&F] = Stream.GetCurrentBitNo();
34540b57cec5SDimitry Andric 
34550b57cec5SDimitry Andric   Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 4);
34560b57cec5SDimitry Andric   VE.incorporateFunction(F);
34570b57cec5SDimitry Andric 
34580b57cec5SDimitry Andric   SmallVector<unsigned, 64> Vals;
34590b57cec5SDimitry Andric 
34600b57cec5SDimitry Andric   // Emit the number of basic blocks, so the reader can create them ahead of
34610b57cec5SDimitry Andric   // time.
34620b57cec5SDimitry Andric   Vals.push_back(VE.getBasicBlocks().size());
34630b57cec5SDimitry Andric   Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals);
34640b57cec5SDimitry Andric   Vals.clear();
34650b57cec5SDimitry Andric 
34660b57cec5SDimitry Andric   // If there are function-local constants, emit them now.
34670b57cec5SDimitry Andric   unsigned CstStart, CstEnd;
34680b57cec5SDimitry Andric   VE.getFunctionConstantRange(CstStart, CstEnd);
34690b57cec5SDimitry Andric   writeConstants(CstStart, CstEnd, false);
34700b57cec5SDimitry Andric 
34710b57cec5SDimitry Andric   // If there is function-local metadata, emit it now.
34720b57cec5SDimitry Andric   writeFunctionMetadata(F);
34730b57cec5SDimitry Andric 
34740b57cec5SDimitry Andric   // Keep a running idea of what the instruction ID is.
34750b57cec5SDimitry Andric   unsigned InstID = CstEnd;
34760b57cec5SDimitry Andric 
34770b57cec5SDimitry Andric   bool NeedsMetadataAttachment = F.hasMetadata();
34780b57cec5SDimitry Andric 
34790b57cec5SDimitry Andric   DILocation *LastDL = nullptr;
348081ad6265SDimitry Andric   SmallSetVector<Function *, 4> BlockAddressUsers;
348181ad6265SDimitry Andric 
34820b57cec5SDimitry Andric   // Finally, emit all the instructions, in order.
348381ad6265SDimitry Andric   for (const BasicBlock &BB : F) {
34844824e7fdSDimitry Andric     for (const Instruction &I : BB) {
34854824e7fdSDimitry Andric       writeInstruction(I, InstID, Vals);
34860b57cec5SDimitry Andric 
34874824e7fdSDimitry Andric       if (!I.getType()->isVoidTy())
34880b57cec5SDimitry Andric         ++InstID;
34890b57cec5SDimitry Andric 
34900b57cec5SDimitry Andric       // If the instruction has metadata, write a metadata attachment later.
34914824e7fdSDimitry Andric       NeedsMetadataAttachment |= I.hasMetadataOtherThanDebugLoc();
34920b57cec5SDimitry Andric 
34930b57cec5SDimitry Andric       // If the instruction has a debug location, emit it.
34944824e7fdSDimitry Andric       DILocation *DL = I.getDebugLoc();
34950b57cec5SDimitry Andric       if (!DL)
34960b57cec5SDimitry Andric         continue;
34970b57cec5SDimitry Andric 
34980b57cec5SDimitry Andric       if (DL == LastDL) {
34990b57cec5SDimitry Andric         // Just repeat the same debug loc as last time.
35000b57cec5SDimitry Andric         Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC_AGAIN, Vals);
35010b57cec5SDimitry Andric         continue;
35020b57cec5SDimitry Andric       }
35030b57cec5SDimitry Andric 
35040b57cec5SDimitry Andric       Vals.push_back(DL->getLine());
35050b57cec5SDimitry Andric       Vals.push_back(DL->getColumn());
35060b57cec5SDimitry Andric       Vals.push_back(VE.getMetadataOrNullID(DL->getScope()));
35070b57cec5SDimitry Andric       Vals.push_back(VE.getMetadataOrNullID(DL->getInlinedAt()));
35080b57cec5SDimitry Andric       Vals.push_back(DL->isImplicitCode());
35090b57cec5SDimitry Andric       Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC, Vals);
35100b57cec5SDimitry Andric       Vals.clear();
35110b57cec5SDimitry Andric 
35120b57cec5SDimitry Andric       LastDL = DL;
35130b57cec5SDimitry Andric     }
35140b57cec5SDimitry Andric 
351581ad6265SDimitry Andric     if (BlockAddress *BA = BlockAddress::lookup(&BB)) {
351681ad6265SDimitry Andric       SmallVector<Value *> Worklist{BA};
351781ad6265SDimitry Andric       SmallPtrSet<Value *, 8> Visited{BA};
351881ad6265SDimitry Andric       while (!Worklist.empty()) {
351981ad6265SDimitry Andric         Value *V = Worklist.pop_back_val();
352081ad6265SDimitry Andric         for (User *U : V->users()) {
352181ad6265SDimitry Andric           if (auto *I = dyn_cast<Instruction>(U)) {
352281ad6265SDimitry Andric             Function *P = I->getFunction();
352381ad6265SDimitry Andric             if (P != &F)
352481ad6265SDimitry Andric               BlockAddressUsers.insert(P);
352581ad6265SDimitry Andric           } else if (isa<Constant>(U) && !isa<GlobalValue>(U) &&
352681ad6265SDimitry Andric                      Visited.insert(U).second)
352781ad6265SDimitry Andric             Worklist.push_back(U);
352881ad6265SDimitry Andric         }
352981ad6265SDimitry Andric       }
353081ad6265SDimitry Andric     }
353181ad6265SDimitry Andric   }
353281ad6265SDimitry Andric 
353381ad6265SDimitry Andric   if (!BlockAddressUsers.empty()) {
353481ad6265SDimitry Andric     Vals.resize(BlockAddressUsers.size());
353581ad6265SDimitry Andric     for (auto I : llvm::enumerate(BlockAddressUsers))
353681ad6265SDimitry Andric       Vals[I.index()] = VE.getValueID(I.value());
353781ad6265SDimitry Andric     Stream.EmitRecord(bitc::FUNC_CODE_BLOCKADDR_USERS, Vals);
353881ad6265SDimitry Andric     Vals.clear();
353981ad6265SDimitry Andric   }
354081ad6265SDimitry Andric 
35410b57cec5SDimitry Andric   // Emit names for all the instructions etc.
35420b57cec5SDimitry Andric   if (auto *Symtab = F.getValueSymbolTable())
35430b57cec5SDimitry Andric     writeFunctionLevelValueSymbolTable(*Symtab);
35440b57cec5SDimitry Andric 
35450b57cec5SDimitry Andric   if (NeedsMetadataAttachment)
35460b57cec5SDimitry Andric     writeFunctionMetadataAttachment(F);
35470b57cec5SDimitry Andric   if (VE.shouldPreserveUseListOrder())
35480b57cec5SDimitry Andric     writeUseListBlock(&F);
35490b57cec5SDimitry Andric   VE.purgeFunction();
35500b57cec5SDimitry Andric   Stream.ExitBlock();
35510b57cec5SDimitry Andric }
35520b57cec5SDimitry Andric 
35530b57cec5SDimitry Andric // Emit blockinfo, which defines the standard abbreviations etc.
writeBlockInfo()35540b57cec5SDimitry Andric void ModuleBitcodeWriter::writeBlockInfo() {
35550b57cec5SDimitry Andric   // We only want to emit block info records for blocks that have multiple
35560b57cec5SDimitry Andric   // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK.
35570b57cec5SDimitry Andric   // Other blocks can define their abbrevs inline.
35580b57cec5SDimitry Andric   Stream.EnterBlockInfoBlock();
35590b57cec5SDimitry Andric 
35600b57cec5SDimitry Andric   { // 8-bit fixed-width VST_CODE_ENTRY/VST_CODE_BBENTRY strings.
35610b57cec5SDimitry Andric     auto Abbv = std::make_shared<BitCodeAbbrev>();
35620b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3));
35630b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
35640b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
35650b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
35660b57cec5SDimitry Andric     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
35670b57cec5SDimitry Andric         VST_ENTRY_8_ABBREV)
35680b57cec5SDimitry Andric       llvm_unreachable("Unexpected abbrev ordering!");
35690b57cec5SDimitry Andric   }
35700b57cec5SDimitry Andric 
35710b57cec5SDimitry Andric   { // 7-bit fixed width VST_CODE_ENTRY strings.
35720b57cec5SDimitry Andric     auto Abbv = std::make_shared<BitCodeAbbrev>();
35730b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
35740b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
35750b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
35760b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
35770b57cec5SDimitry Andric     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
35780b57cec5SDimitry Andric         VST_ENTRY_7_ABBREV)
35790b57cec5SDimitry Andric       llvm_unreachable("Unexpected abbrev ordering!");
35800b57cec5SDimitry Andric   }
35810b57cec5SDimitry Andric   { // 6-bit char6 VST_CODE_ENTRY strings.
35820b57cec5SDimitry Andric     auto Abbv = std::make_shared<BitCodeAbbrev>();
35830b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
35840b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
35850b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
35860b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
35870b57cec5SDimitry Andric     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
35880b57cec5SDimitry Andric         VST_ENTRY_6_ABBREV)
35890b57cec5SDimitry Andric       llvm_unreachable("Unexpected abbrev ordering!");
35900b57cec5SDimitry Andric   }
35910b57cec5SDimitry Andric   { // 6-bit char6 VST_CODE_BBENTRY strings.
35920b57cec5SDimitry Andric     auto Abbv = std::make_shared<BitCodeAbbrev>();
35930b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY));
35940b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
35950b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
35960b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
35970b57cec5SDimitry Andric     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
35980b57cec5SDimitry Andric         VST_BBENTRY_6_ABBREV)
35990b57cec5SDimitry Andric       llvm_unreachable("Unexpected abbrev ordering!");
36000b57cec5SDimitry Andric   }
36010b57cec5SDimitry Andric 
36020b57cec5SDimitry Andric   { // SETTYPE abbrev for CONSTANTS_BLOCK.
36030b57cec5SDimitry Andric     auto Abbv = std::make_shared<BitCodeAbbrev>();
36040b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_SETTYPE));
36050b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
36060b57cec5SDimitry Andric                               VE.computeBitsRequiredForTypeIndicies()));
36070b57cec5SDimitry Andric     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
36080b57cec5SDimitry Andric         CONSTANTS_SETTYPE_ABBREV)
36090b57cec5SDimitry Andric       llvm_unreachable("Unexpected abbrev ordering!");
36100b57cec5SDimitry Andric   }
36110b57cec5SDimitry Andric 
36120b57cec5SDimitry Andric   { // INTEGER abbrev for CONSTANTS_BLOCK.
36130b57cec5SDimitry Andric     auto Abbv = std::make_shared<BitCodeAbbrev>();
36140b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_INTEGER));
36150b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
36160b57cec5SDimitry Andric     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
36170b57cec5SDimitry Andric         CONSTANTS_INTEGER_ABBREV)
36180b57cec5SDimitry Andric       llvm_unreachable("Unexpected abbrev ordering!");
36190b57cec5SDimitry Andric   }
36200b57cec5SDimitry Andric 
36210b57cec5SDimitry Andric   { // CE_CAST abbrev for CONSTANTS_BLOCK.
36220b57cec5SDimitry Andric     auto Abbv = std::make_shared<BitCodeAbbrev>();
36230b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CE_CAST));
36240b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4));  // cast opc
36250b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,       // typeid
36260b57cec5SDimitry Andric                               VE.computeBitsRequiredForTypeIndicies()));
36270b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));    // value id
36280b57cec5SDimitry Andric 
36290b57cec5SDimitry Andric     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
36300b57cec5SDimitry Andric         CONSTANTS_CE_CAST_Abbrev)
36310b57cec5SDimitry Andric       llvm_unreachable("Unexpected abbrev ordering!");
36320b57cec5SDimitry Andric   }
36330b57cec5SDimitry Andric   { // NULL abbrev for CONSTANTS_BLOCK.
36340b57cec5SDimitry Andric     auto Abbv = std::make_shared<BitCodeAbbrev>();
36350b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_NULL));
36360b57cec5SDimitry Andric     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
36370b57cec5SDimitry Andric         CONSTANTS_NULL_Abbrev)
36380b57cec5SDimitry Andric       llvm_unreachable("Unexpected abbrev ordering!");
36390b57cec5SDimitry Andric   }
36400b57cec5SDimitry Andric 
36410b57cec5SDimitry Andric   // FIXME: This should only use space for first class types!
36420b57cec5SDimitry Andric 
36430b57cec5SDimitry Andric   { // INST_LOAD abbrev for FUNCTION_BLOCK.
36440b57cec5SDimitry Andric     auto Abbv = std::make_shared<BitCodeAbbrev>();
36450b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_LOAD));
36460b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Ptr
36470b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,    // dest ty
36480b57cec5SDimitry Andric                               VE.computeBitsRequiredForTypeIndicies()));
36490b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align
36500b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile
36510b57cec5SDimitry Andric     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
36520b57cec5SDimitry Andric         FUNCTION_INST_LOAD_ABBREV)
36530b57cec5SDimitry Andric       llvm_unreachable("Unexpected abbrev ordering!");
36540b57cec5SDimitry Andric   }
36550b57cec5SDimitry Andric   { // INST_UNOP abbrev for FUNCTION_BLOCK.
36560b57cec5SDimitry Andric     auto Abbv = std::make_shared<BitCodeAbbrev>();
36570b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNOP));
36580b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
36590b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
36600b57cec5SDimitry Andric     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
36610b57cec5SDimitry Andric         FUNCTION_INST_UNOP_ABBREV)
36620b57cec5SDimitry Andric       llvm_unreachable("Unexpected abbrev ordering!");
36630b57cec5SDimitry Andric   }
36640b57cec5SDimitry Andric   { // INST_UNOP_FLAGS abbrev for FUNCTION_BLOCK.
36650b57cec5SDimitry Andric     auto Abbv = std::make_shared<BitCodeAbbrev>();
36660b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNOP));
36670b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
36680b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
36690b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); // flags
36700b57cec5SDimitry Andric     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
36710b57cec5SDimitry Andric         FUNCTION_INST_UNOP_FLAGS_ABBREV)
36720b57cec5SDimitry Andric       llvm_unreachable("Unexpected abbrev ordering!");
36730b57cec5SDimitry Andric   }
36740b57cec5SDimitry Andric   { // INST_BINOP abbrev for FUNCTION_BLOCK.
36750b57cec5SDimitry Andric     auto Abbv = std::make_shared<BitCodeAbbrev>();
36760b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
36770b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
36780b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
36790b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
36800b57cec5SDimitry Andric     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
36810b57cec5SDimitry Andric         FUNCTION_INST_BINOP_ABBREV)
36820b57cec5SDimitry Andric       llvm_unreachable("Unexpected abbrev ordering!");
36830b57cec5SDimitry Andric   }
36840b57cec5SDimitry Andric   { // INST_BINOP_FLAGS abbrev for FUNCTION_BLOCK.
36850b57cec5SDimitry Andric     auto Abbv = std::make_shared<BitCodeAbbrev>();
36860b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
36870b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
36880b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
36890b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
36900b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); // flags
36910b57cec5SDimitry Andric     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
36920b57cec5SDimitry Andric         FUNCTION_INST_BINOP_FLAGS_ABBREV)
36930b57cec5SDimitry Andric       llvm_unreachable("Unexpected abbrev ordering!");
36940b57cec5SDimitry Andric   }
36950b57cec5SDimitry Andric   { // INST_CAST abbrev for FUNCTION_BLOCK.
36960b57cec5SDimitry Andric     auto Abbv = std::make_shared<BitCodeAbbrev>();
36970b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST));
36980b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));    // OpVal
36990b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,       // dest ty
37000b57cec5SDimitry Andric                               VE.computeBitsRequiredForTypeIndicies()));
37010b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4));  // opc
37020b57cec5SDimitry Andric     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
37030b57cec5SDimitry Andric         FUNCTION_INST_CAST_ABBREV)
37040b57cec5SDimitry Andric       llvm_unreachable("Unexpected abbrev ordering!");
37050b57cec5SDimitry Andric   }
3706c9157d92SDimitry Andric   { // INST_CAST_FLAGS abbrev for FUNCTION_BLOCK.
3707c9157d92SDimitry Andric     auto Abbv = std::make_shared<BitCodeAbbrev>();
3708c9157d92SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST));
3709c9157d92SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // OpVal
3710c9157d92SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,    // dest ty
3711c9157d92SDimitry Andric                               VE.computeBitsRequiredForTypeIndicies()));
3712c9157d92SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3713c9157d92SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); // flags
3714c9157d92SDimitry Andric     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3715c9157d92SDimitry Andric         FUNCTION_INST_CAST_FLAGS_ABBREV)
3716c9157d92SDimitry Andric       llvm_unreachable("Unexpected abbrev ordering!");
3717c9157d92SDimitry Andric   }
37180b57cec5SDimitry Andric 
37190b57cec5SDimitry Andric   { // INST_RET abbrev for FUNCTION_BLOCK.
37200b57cec5SDimitry Andric     auto Abbv = std::make_shared<BitCodeAbbrev>();
37210b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
37220b57cec5SDimitry Andric     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
37230b57cec5SDimitry Andric         FUNCTION_INST_RET_VOID_ABBREV)
37240b57cec5SDimitry Andric       llvm_unreachable("Unexpected abbrev ordering!");
37250b57cec5SDimitry Andric   }
37260b57cec5SDimitry Andric   { // INST_RET abbrev for FUNCTION_BLOCK.
37270b57cec5SDimitry Andric     auto Abbv = std::make_shared<BitCodeAbbrev>();
37280b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
37290b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ValID
37300b57cec5SDimitry Andric     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
37310b57cec5SDimitry Andric         FUNCTION_INST_RET_VAL_ABBREV)
37320b57cec5SDimitry Andric       llvm_unreachable("Unexpected abbrev ordering!");
37330b57cec5SDimitry Andric   }
37340b57cec5SDimitry Andric   { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK.
37350b57cec5SDimitry Andric     auto Abbv = std::make_shared<BitCodeAbbrev>();
37360b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNREACHABLE));
37370b57cec5SDimitry Andric     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
37380b57cec5SDimitry Andric         FUNCTION_INST_UNREACHABLE_ABBREV)
37390b57cec5SDimitry Andric       llvm_unreachable("Unexpected abbrev ordering!");
37400b57cec5SDimitry Andric   }
37410b57cec5SDimitry Andric   {
37420b57cec5SDimitry Andric     auto Abbv = std::make_shared<BitCodeAbbrev>();
37430b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_GEP));
37440b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
37450b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
37460b57cec5SDimitry Andric                               Log2_32_Ceil(VE.getTypes().size() + 1)));
37470b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
37480b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
37490b57cec5SDimitry Andric     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
37500b57cec5SDimitry Andric         FUNCTION_INST_GEP_ABBREV)
37510b57cec5SDimitry Andric       llvm_unreachable("Unexpected abbrev ordering!");
37520b57cec5SDimitry Andric   }
37530b57cec5SDimitry Andric 
37540b57cec5SDimitry Andric   Stream.ExitBlock();
37550b57cec5SDimitry Andric }
37560b57cec5SDimitry Andric 
37570b57cec5SDimitry Andric /// Write the module path strings, currently only used when generating
37580b57cec5SDimitry Andric /// a combined index file.
writeModStrings()37590b57cec5SDimitry Andric void IndexBitcodeWriter::writeModStrings() {
37600b57cec5SDimitry Andric   Stream.EnterSubblock(bitc::MODULE_STRTAB_BLOCK_ID, 3);
37610b57cec5SDimitry Andric 
37620b57cec5SDimitry Andric   // TODO: See which abbrev sizes we actually need to emit
37630b57cec5SDimitry Andric 
37640b57cec5SDimitry Andric   // 8-bit fixed-width MST_ENTRY strings.
37650b57cec5SDimitry Andric   auto Abbv = std::make_shared<BitCodeAbbrev>();
37660b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
37670b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
37680b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
37690b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
37700b57cec5SDimitry Andric   unsigned Abbrev8Bit = Stream.EmitAbbrev(std::move(Abbv));
37710b57cec5SDimitry Andric 
37720b57cec5SDimitry Andric   // 7-bit fixed width MST_ENTRY strings.
37730b57cec5SDimitry Andric   Abbv = std::make_shared<BitCodeAbbrev>();
37740b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
37750b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
37760b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
37770b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
37780b57cec5SDimitry Andric   unsigned Abbrev7Bit = Stream.EmitAbbrev(std::move(Abbv));
37790b57cec5SDimitry Andric 
37800b57cec5SDimitry Andric   // 6-bit char6 MST_ENTRY strings.
37810b57cec5SDimitry Andric   Abbv = std::make_shared<BitCodeAbbrev>();
37820b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
37830b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
37840b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
37850b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
37860b57cec5SDimitry Andric   unsigned Abbrev6Bit = Stream.EmitAbbrev(std::move(Abbv));
37870b57cec5SDimitry Andric 
37880b57cec5SDimitry Andric   // Module Hash, 160 bits SHA1. Optionally, emitted after each MST_CODE_ENTRY.
37890b57cec5SDimitry Andric   Abbv = std::make_shared<BitCodeAbbrev>();
37900b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_HASH));
37910b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
37920b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
37930b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
37940b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
37950b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
37960b57cec5SDimitry Andric   unsigned AbbrevHash = Stream.EmitAbbrev(std::move(Abbv));
37970b57cec5SDimitry Andric 
37980b57cec5SDimitry Andric   SmallVector<unsigned, 64> Vals;
3799c9157d92SDimitry Andric   forEachModule([&](const StringMapEntry<ModuleHash> &MPSE) {
38000b57cec5SDimitry Andric     StringRef Key = MPSE.getKey();
3801c9157d92SDimitry Andric     const auto &Hash = MPSE.getValue();
38020b57cec5SDimitry Andric     StringEncoding Bits = getStringEncoding(Key);
38030b57cec5SDimitry Andric     unsigned AbbrevToUse = Abbrev8Bit;
38040b57cec5SDimitry Andric     if (Bits == SE_Char6)
38050b57cec5SDimitry Andric       AbbrevToUse = Abbrev6Bit;
38060b57cec5SDimitry Andric     else if (Bits == SE_Fixed7)
38070b57cec5SDimitry Andric       AbbrevToUse = Abbrev7Bit;
38080b57cec5SDimitry Andric 
3809c9157d92SDimitry Andric     auto ModuleId = ModuleIdMap.size();
3810c9157d92SDimitry Andric     ModuleIdMap[Key] = ModuleId;
3811c9157d92SDimitry Andric     Vals.push_back(ModuleId);
38120b57cec5SDimitry Andric     Vals.append(Key.begin(), Key.end());
38130b57cec5SDimitry Andric 
38140b57cec5SDimitry Andric     // Emit the finished record.
38150b57cec5SDimitry Andric     Stream.EmitRecord(bitc::MST_CODE_ENTRY, Vals, AbbrevToUse);
38160b57cec5SDimitry Andric 
38170b57cec5SDimitry Andric     // Emit an optional hash for the module now
38180b57cec5SDimitry Andric     if (llvm::any_of(Hash, [](uint32_t H) { return H; })) {
38190b57cec5SDimitry Andric       Vals.assign(Hash.begin(), Hash.end());
38200b57cec5SDimitry Andric       // Emit the hash record.
38210b57cec5SDimitry Andric       Stream.EmitRecord(bitc::MST_CODE_HASH, Vals, AbbrevHash);
38220b57cec5SDimitry Andric     }
38230b57cec5SDimitry Andric 
38240b57cec5SDimitry Andric     Vals.clear();
38250b57cec5SDimitry Andric   });
38260b57cec5SDimitry Andric   Stream.ExitBlock();
38270b57cec5SDimitry Andric }
38280b57cec5SDimitry Andric 
38290b57cec5SDimitry Andric /// Write the function type metadata related records that need to appear before
38300b57cec5SDimitry Andric /// a function summary entry (whether per-module or combined).
3831e8d8bef9SDimitry Andric template <typename Fn>
writeFunctionTypeMetadataRecords(BitstreamWriter & Stream,FunctionSummary * FS,Fn GetValueID)38320b57cec5SDimitry Andric static void writeFunctionTypeMetadataRecords(BitstreamWriter &Stream,
3833e8d8bef9SDimitry Andric                                              FunctionSummary *FS,
3834e8d8bef9SDimitry Andric                                              Fn GetValueID) {
38350b57cec5SDimitry Andric   if (!FS->type_tests().empty())
38360b57cec5SDimitry Andric     Stream.EmitRecord(bitc::FS_TYPE_TESTS, FS->type_tests());
38370b57cec5SDimitry Andric 
38380b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
38390b57cec5SDimitry Andric 
38400b57cec5SDimitry Andric   auto WriteVFuncIdVec = [&](uint64_t Ty,
38410b57cec5SDimitry Andric                              ArrayRef<FunctionSummary::VFuncId> VFs) {
38420b57cec5SDimitry Andric     if (VFs.empty())
38430b57cec5SDimitry Andric       return;
38440b57cec5SDimitry Andric     Record.clear();
38450b57cec5SDimitry Andric     for (auto &VF : VFs) {
38460b57cec5SDimitry Andric       Record.push_back(VF.GUID);
38470b57cec5SDimitry Andric       Record.push_back(VF.Offset);
38480b57cec5SDimitry Andric     }
38490b57cec5SDimitry Andric     Stream.EmitRecord(Ty, Record);
38500b57cec5SDimitry Andric   };
38510b57cec5SDimitry Andric 
38520b57cec5SDimitry Andric   WriteVFuncIdVec(bitc::FS_TYPE_TEST_ASSUME_VCALLS,
38530b57cec5SDimitry Andric                   FS->type_test_assume_vcalls());
38540b57cec5SDimitry Andric   WriteVFuncIdVec(bitc::FS_TYPE_CHECKED_LOAD_VCALLS,
38550b57cec5SDimitry Andric                   FS->type_checked_load_vcalls());
38560b57cec5SDimitry Andric 
38570b57cec5SDimitry Andric   auto WriteConstVCallVec = [&](uint64_t Ty,
38580b57cec5SDimitry Andric                                 ArrayRef<FunctionSummary::ConstVCall> VCs) {
38590b57cec5SDimitry Andric     for (auto &VC : VCs) {
38600b57cec5SDimitry Andric       Record.clear();
38610b57cec5SDimitry Andric       Record.push_back(VC.VFunc.GUID);
38620b57cec5SDimitry Andric       Record.push_back(VC.VFunc.Offset);
3863e8d8bef9SDimitry Andric       llvm::append_range(Record, VC.Args);
38640b57cec5SDimitry Andric       Stream.EmitRecord(Ty, Record);
38650b57cec5SDimitry Andric     }
38660b57cec5SDimitry Andric   };
38670b57cec5SDimitry Andric 
38680b57cec5SDimitry Andric   WriteConstVCallVec(bitc::FS_TYPE_TEST_ASSUME_CONST_VCALL,
38690b57cec5SDimitry Andric                      FS->type_test_assume_const_vcalls());
38700b57cec5SDimitry Andric   WriteConstVCallVec(bitc::FS_TYPE_CHECKED_LOAD_CONST_VCALL,
38710b57cec5SDimitry Andric                      FS->type_checked_load_const_vcalls());
38725ffd83dbSDimitry Andric 
38735ffd83dbSDimitry Andric   auto WriteRange = [&](ConstantRange Range) {
38745ffd83dbSDimitry Andric     Range = Range.sextOrTrunc(FunctionSummary::ParamAccess::RangeWidth);
38755ffd83dbSDimitry Andric     assert(Range.getLower().getNumWords() == 1);
38765ffd83dbSDimitry Andric     assert(Range.getUpper().getNumWords() == 1);
38775ffd83dbSDimitry Andric     emitSignedInt64(Record, *Range.getLower().getRawData());
38785ffd83dbSDimitry Andric     emitSignedInt64(Record, *Range.getUpper().getRawData());
38795ffd83dbSDimitry Andric   };
38805ffd83dbSDimitry Andric 
38815ffd83dbSDimitry Andric   if (!FS->paramAccesses().empty()) {
38825ffd83dbSDimitry Andric     Record.clear();
38835ffd83dbSDimitry Andric     for (auto &Arg : FS->paramAccesses()) {
3884e8d8bef9SDimitry Andric       size_t UndoSize = Record.size();
38855ffd83dbSDimitry Andric       Record.push_back(Arg.ParamNo);
38865ffd83dbSDimitry Andric       WriteRange(Arg.Use);
38875ffd83dbSDimitry Andric       Record.push_back(Arg.Calls.size());
38885ffd83dbSDimitry Andric       for (auto &Call : Arg.Calls) {
38895ffd83dbSDimitry Andric         Record.push_back(Call.ParamNo);
3890bdd1243dSDimitry Andric         std::optional<unsigned> ValueID = GetValueID(Call.Callee);
3891e8d8bef9SDimitry Andric         if (!ValueID) {
3892e8d8bef9SDimitry Andric           // If ValueID is unknown we can't drop just this call, we must drop
3893e8d8bef9SDimitry Andric           // entire parameter.
3894e8d8bef9SDimitry Andric           Record.resize(UndoSize);
3895e8d8bef9SDimitry Andric           break;
3896e8d8bef9SDimitry Andric         }
3897e8d8bef9SDimitry Andric         Record.push_back(*ValueID);
38985ffd83dbSDimitry Andric         WriteRange(Call.Offsets);
38995ffd83dbSDimitry Andric       }
39005ffd83dbSDimitry Andric     }
3901e8d8bef9SDimitry Andric     if (!Record.empty())
39025ffd83dbSDimitry Andric       Stream.EmitRecord(bitc::FS_PARAM_ACCESS, Record);
39035ffd83dbSDimitry Andric   }
39040b57cec5SDimitry Andric }
39050b57cec5SDimitry Andric 
39060b57cec5SDimitry Andric /// Collect type IDs from type tests used by function.
39070b57cec5SDimitry Andric static void
getReferencedTypeIds(FunctionSummary * FS,std::set<GlobalValue::GUID> & ReferencedTypeIds)39080b57cec5SDimitry Andric getReferencedTypeIds(FunctionSummary *FS,
39090b57cec5SDimitry Andric                      std::set<GlobalValue::GUID> &ReferencedTypeIds) {
39100b57cec5SDimitry Andric   if (!FS->type_tests().empty())
39110b57cec5SDimitry Andric     for (auto &TT : FS->type_tests())
39120b57cec5SDimitry Andric       ReferencedTypeIds.insert(TT);
39130b57cec5SDimitry Andric 
39140b57cec5SDimitry Andric   auto GetReferencedTypesFromVFuncIdVec =
39150b57cec5SDimitry Andric       [&](ArrayRef<FunctionSummary::VFuncId> VFs) {
39160b57cec5SDimitry Andric         for (auto &VF : VFs)
39170b57cec5SDimitry Andric           ReferencedTypeIds.insert(VF.GUID);
39180b57cec5SDimitry Andric       };
39190b57cec5SDimitry Andric 
39200b57cec5SDimitry Andric   GetReferencedTypesFromVFuncIdVec(FS->type_test_assume_vcalls());
39210b57cec5SDimitry Andric   GetReferencedTypesFromVFuncIdVec(FS->type_checked_load_vcalls());
39220b57cec5SDimitry Andric 
39230b57cec5SDimitry Andric   auto GetReferencedTypesFromConstVCallVec =
39240b57cec5SDimitry Andric       [&](ArrayRef<FunctionSummary::ConstVCall> VCs) {
39250b57cec5SDimitry Andric         for (auto &VC : VCs)
39260b57cec5SDimitry Andric           ReferencedTypeIds.insert(VC.VFunc.GUID);
39270b57cec5SDimitry Andric       };
39280b57cec5SDimitry Andric 
39290b57cec5SDimitry Andric   GetReferencedTypesFromConstVCallVec(FS->type_test_assume_const_vcalls());
39300b57cec5SDimitry Andric   GetReferencedTypesFromConstVCallVec(FS->type_checked_load_const_vcalls());
39310b57cec5SDimitry Andric }
39320b57cec5SDimitry Andric 
writeWholeProgramDevirtResolutionByArg(SmallVector<uint64_t,64> & NameVals,const std::vector<uint64_t> & args,const WholeProgramDevirtResolution::ByArg & ByArg)39330b57cec5SDimitry Andric static void writeWholeProgramDevirtResolutionByArg(
39340b57cec5SDimitry Andric     SmallVector<uint64_t, 64> &NameVals, const std::vector<uint64_t> &args,
39350b57cec5SDimitry Andric     const WholeProgramDevirtResolution::ByArg &ByArg) {
39360b57cec5SDimitry Andric   NameVals.push_back(args.size());
3937e8d8bef9SDimitry Andric   llvm::append_range(NameVals, args);
39380b57cec5SDimitry Andric 
39390b57cec5SDimitry Andric   NameVals.push_back(ByArg.TheKind);
39400b57cec5SDimitry Andric   NameVals.push_back(ByArg.Info);
39410b57cec5SDimitry Andric   NameVals.push_back(ByArg.Byte);
39420b57cec5SDimitry Andric   NameVals.push_back(ByArg.Bit);
39430b57cec5SDimitry Andric }
39440b57cec5SDimitry Andric 
writeWholeProgramDevirtResolution(SmallVector<uint64_t,64> & NameVals,StringTableBuilder & StrtabBuilder,uint64_t Id,const WholeProgramDevirtResolution & Wpd)39450b57cec5SDimitry Andric static void writeWholeProgramDevirtResolution(
39460b57cec5SDimitry Andric     SmallVector<uint64_t, 64> &NameVals, StringTableBuilder &StrtabBuilder,
39470b57cec5SDimitry Andric     uint64_t Id, const WholeProgramDevirtResolution &Wpd) {
39480b57cec5SDimitry Andric   NameVals.push_back(Id);
39490b57cec5SDimitry Andric 
39500b57cec5SDimitry Andric   NameVals.push_back(Wpd.TheKind);
39510b57cec5SDimitry Andric   NameVals.push_back(StrtabBuilder.add(Wpd.SingleImplName));
39520b57cec5SDimitry Andric   NameVals.push_back(Wpd.SingleImplName.size());
39530b57cec5SDimitry Andric 
39540b57cec5SDimitry Andric   NameVals.push_back(Wpd.ResByArg.size());
39550b57cec5SDimitry Andric   for (auto &A : Wpd.ResByArg)
39560b57cec5SDimitry Andric     writeWholeProgramDevirtResolutionByArg(NameVals, A.first, A.second);
39570b57cec5SDimitry Andric }
39580b57cec5SDimitry Andric 
writeTypeIdSummaryRecord(SmallVector<uint64_t,64> & NameVals,StringTableBuilder & StrtabBuilder,const std::string & Id,const TypeIdSummary & Summary)39590b57cec5SDimitry Andric static void writeTypeIdSummaryRecord(SmallVector<uint64_t, 64> &NameVals,
39600b57cec5SDimitry Andric                                      StringTableBuilder &StrtabBuilder,
39610b57cec5SDimitry Andric                                      const std::string &Id,
39620b57cec5SDimitry Andric                                      const TypeIdSummary &Summary) {
39630b57cec5SDimitry Andric   NameVals.push_back(StrtabBuilder.add(Id));
39640b57cec5SDimitry Andric   NameVals.push_back(Id.size());
39650b57cec5SDimitry Andric 
39660b57cec5SDimitry Andric   NameVals.push_back(Summary.TTRes.TheKind);
39670b57cec5SDimitry Andric   NameVals.push_back(Summary.TTRes.SizeM1BitWidth);
39680b57cec5SDimitry Andric   NameVals.push_back(Summary.TTRes.AlignLog2);
39690b57cec5SDimitry Andric   NameVals.push_back(Summary.TTRes.SizeM1);
39700b57cec5SDimitry Andric   NameVals.push_back(Summary.TTRes.BitMask);
39710b57cec5SDimitry Andric   NameVals.push_back(Summary.TTRes.InlineBits);
39720b57cec5SDimitry Andric 
39730b57cec5SDimitry Andric   for (auto &W : Summary.WPDRes)
39740b57cec5SDimitry Andric     writeWholeProgramDevirtResolution(NameVals, StrtabBuilder, W.first,
39750b57cec5SDimitry Andric                                       W.second);
39760b57cec5SDimitry Andric }
39770b57cec5SDimitry Andric 
writeTypeIdCompatibleVtableSummaryRecord(SmallVector<uint64_t,64> & NameVals,StringTableBuilder & StrtabBuilder,const std::string & Id,const TypeIdCompatibleVtableInfo & Summary,ValueEnumerator & VE)39780b57cec5SDimitry Andric static void writeTypeIdCompatibleVtableSummaryRecord(
39790b57cec5SDimitry Andric     SmallVector<uint64_t, 64> &NameVals, StringTableBuilder &StrtabBuilder,
39800b57cec5SDimitry Andric     const std::string &Id, const TypeIdCompatibleVtableInfo &Summary,
39810b57cec5SDimitry Andric     ValueEnumerator &VE) {
39820b57cec5SDimitry Andric   NameVals.push_back(StrtabBuilder.add(Id));
39830b57cec5SDimitry Andric   NameVals.push_back(Id.size());
39840b57cec5SDimitry Andric 
39850b57cec5SDimitry Andric   for (auto &P : Summary) {
39860b57cec5SDimitry Andric     NameVals.push_back(P.AddressPointOffset);
39870b57cec5SDimitry Andric     NameVals.push_back(VE.getValueID(P.VTableVI.getValue()));
39880b57cec5SDimitry Andric   }
39890b57cec5SDimitry Andric }
39900b57cec5SDimitry Andric 
writeFunctionHeapProfileRecords(BitstreamWriter & Stream,FunctionSummary * FS,unsigned CallsiteAbbrev,unsigned AllocAbbrev,bool PerModule,std::function<unsigned (const ValueInfo & VI)> GetValueID,std::function<unsigned (unsigned)> GetStackIndex)3991bdd1243dSDimitry Andric static void writeFunctionHeapProfileRecords(
3992bdd1243dSDimitry Andric     BitstreamWriter &Stream, FunctionSummary *FS, unsigned CallsiteAbbrev,
3993bdd1243dSDimitry Andric     unsigned AllocAbbrev, bool PerModule,
3994bdd1243dSDimitry Andric     std::function<unsigned(const ValueInfo &VI)> GetValueID,
3995bdd1243dSDimitry Andric     std::function<unsigned(unsigned)> GetStackIndex) {
3996bdd1243dSDimitry Andric   SmallVector<uint64_t> Record;
3997bdd1243dSDimitry Andric 
3998bdd1243dSDimitry Andric   for (auto &CI : FS->callsites()) {
3999bdd1243dSDimitry Andric     Record.clear();
4000bdd1243dSDimitry Andric     // Per module callsite clones should always have a single entry of
4001bdd1243dSDimitry Andric     // value 0.
4002bdd1243dSDimitry Andric     assert(!PerModule || (CI.Clones.size() == 1 && CI.Clones[0] == 0));
4003bdd1243dSDimitry Andric     Record.push_back(GetValueID(CI.Callee));
4004bdd1243dSDimitry Andric     if (!PerModule) {
4005bdd1243dSDimitry Andric       Record.push_back(CI.StackIdIndices.size());
4006bdd1243dSDimitry Andric       Record.push_back(CI.Clones.size());
4007bdd1243dSDimitry Andric     }
4008bdd1243dSDimitry Andric     for (auto Id : CI.StackIdIndices)
4009bdd1243dSDimitry Andric       Record.push_back(GetStackIndex(Id));
4010bdd1243dSDimitry Andric     if (!PerModule) {
4011bdd1243dSDimitry Andric       for (auto V : CI.Clones)
4012bdd1243dSDimitry Andric         Record.push_back(V);
4013bdd1243dSDimitry Andric     }
4014bdd1243dSDimitry Andric     Stream.EmitRecord(PerModule ? bitc::FS_PERMODULE_CALLSITE_INFO
4015bdd1243dSDimitry Andric                                 : bitc::FS_COMBINED_CALLSITE_INFO,
4016bdd1243dSDimitry Andric                       Record, CallsiteAbbrev);
4017bdd1243dSDimitry Andric   }
4018bdd1243dSDimitry Andric 
4019bdd1243dSDimitry Andric   for (auto &AI : FS->allocs()) {
4020bdd1243dSDimitry Andric     Record.clear();
4021bdd1243dSDimitry Andric     // Per module alloc versions should always have a single entry of
4022bdd1243dSDimitry Andric     // value 0.
4023bdd1243dSDimitry Andric     assert(!PerModule || (AI.Versions.size() == 1 && AI.Versions[0] == 0));
4024bdd1243dSDimitry Andric     if (!PerModule) {
4025bdd1243dSDimitry Andric       Record.push_back(AI.MIBs.size());
4026bdd1243dSDimitry Andric       Record.push_back(AI.Versions.size());
4027bdd1243dSDimitry Andric     }
4028bdd1243dSDimitry Andric     for (auto &MIB : AI.MIBs) {
4029bdd1243dSDimitry Andric       Record.push_back((uint8_t)MIB.AllocType);
4030bdd1243dSDimitry Andric       Record.push_back(MIB.StackIdIndices.size());
4031bdd1243dSDimitry Andric       for (auto Id : MIB.StackIdIndices)
4032bdd1243dSDimitry Andric         Record.push_back(GetStackIndex(Id));
4033bdd1243dSDimitry Andric     }
4034bdd1243dSDimitry Andric     if (!PerModule) {
4035bdd1243dSDimitry Andric       for (auto V : AI.Versions)
4036bdd1243dSDimitry Andric         Record.push_back(V);
4037bdd1243dSDimitry Andric     }
4038bdd1243dSDimitry Andric     Stream.EmitRecord(PerModule ? bitc::FS_PERMODULE_ALLOC_INFO
4039bdd1243dSDimitry Andric                                 : bitc::FS_COMBINED_ALLOC_INFO,
4040bdd1243dSDimitry Andric                       Record, AllocAbbrev);
4041bdd1243dSDimitry Andric   }
4042bdd1243dSDimitry Andric }
4043bdd1243dSDimitry Andric 
40440b57cec5SDimitry Andric // Helper to emit a single function summary record.
writePerModuleFunctionSummaryRecord(SmallVector<uint64_t,64> & NameVals,GlobalValueSummary * Summary,unsigned ValueID,unsigned FSCallsRelBFAbbrev,unsigned FSCallsProfileAbbrev,unsigned CallsiteAbbrev,unsigned AllocAbbrev,const Function & F)40450b57cec5SDimitry Andric void ModuleBitcodeWriterBase::writePerModuleFunctionSummaryRecord(
40460b57cec5SDimitry Andric     SmallVector<uint64_t, 64> &NameVals, GlobalValueSummary *Summary,
4047c9157d92SDimitry Andric     unsigned ValueID, unsigned FSCallsRelBFAbbrev,
4048c9157d92SDimitry Andric     unsigned FSCallsProfileAbbrev, unsigned CallsiteAbbrev,
4049c9157d92SDimitry Andric     unsigned AllocAbbrev, const Function &F) {
40500b57cec5SDimitry Andric   NameVals.push_back(ValueID);
40510b57cec5SDimitry Andric 
40520b57cec5SDimitry Andric   FunctionSummary *FS = cast<FunctionSummary>(Summary);
4053e8d8bef9SDimitry Andric 
4054e8d8bef9SDimitry Andric   writeFunctionTypeMetadataRecords(
4055bdd1243dSDimitry Andric       Stream, FS, [&](const ValueInfo &VI) -> std::optional<unsigned> {
4056e8d8bef9SDimitry Andric         return {VE.getValueID(VI.getValue())};
4057e8d8bef9SDimitry Andric       });
40580b57cec5SDimitry Andric 
4059bdd1243dSDimitry Andric   writeFunctionHeapProfileRecords(
4060bdd1243dSDimitry Andric       Stream, FS, CallsiteAbbrev, AllocAbbrev,
4061bdd1243dSDimitry Andric       /*PerModule*/ true,
4062bdd1243dSDimitry Andric       /*GetValueId*/ [&](const ValueInfo &VI) { return getValueId(VI); },
4063bdd1243dSDimitry Andric       /*GetStackIndex*/ [&](unsigned I) { return I; });
4064bdd1243dSDimitry Andric 
40650b57cec5SDimitry Andric   auto SpecialRefCnts = FS->specialRefCounts();
40660b57cec5SDimitry Andric   NameVals.push_back(getEncodedGVSummaryFlags(FS->flags()));
40670b57cec5SDimitry Andric   NameVals.push_back(FS->instCount());
40680b57cec5SDimitry Andric   NameVals.push_back(getEncodedFFlags(FS->fflags()));
40690b57cec5SDimitry Andric   NameVals.push_back(FS->refs().size());
40700b57cec5SDimitry Andric   NameVals.push_back(SpecialRefCnts.first);  // rorefcnt
40710b57cec5SDimitry Andric   NameVals.push_back(SpecialRefCnts.second); // worefcnt
40720b57cec5SDimitry Andric 
40730b57cec5SDimitry Andric   for (auto &RI : FS->refs())
40740b57cec5SDimitry Andric     NameVals.push_back(VE.getValueID(RI.getValue()));
40750b57cec5SDimitry Andric 
4076c9157d92SDimitry Andric   const bool UseRelBFRecord =
4077c9157d92SDimitry Andric       WriteRelBFToSummary && !F.hasProfileData() &&
4078c9157d92SDimitry Andric       ForceSummaryEdgesCold == FunctionSummary::FSHT_None;
40790b57cec5SDimitry Andric   for (auto &ECI : FS->calls()) {
40800b57cec5SDimitry Andric     NameVals.push_back(getValueId(ECI.first));
4081c9157d92SDimitry Andric     if (UseRelBFRecord)
4082c9157d92SDimitry Andric       NameVals.push_back(getEncodedRelBFCallEdgeInfo(ECI.second));
4083c9157d92SDimitry Andric     else
4084c9157d92SDimitry Andric       NameVals.push_back(getEncodedHotnessCallEdgeInfo(ECI.second));
40850b57cec5SDimitry Andric   }
40860b57cec5SDimitry Andric 
4087c9157d92SDimitry Andric   unsigned FSAbbrev =
4088c9157d92SDimitry Andric       (UseRelBFRecord ? FSCallsRelBFAbbrev : FSCallsProfileAbbrev);
40890b57cec5SDimitry Andric   unsigned Code =
4090c9157d92SDimitry Andric       (UseRelBFRecord ? bitc::FS_PERMODULE_RELBF : bitc::FS_PERMODULE_PROFILE);
40910b57cec5SDimitry Andric 
40920b57cec5SDimitry Andric   // Emit the finished record.
40930b57cec5SDimitry Andric   Stream.EmitRecord(Code, NameVals, FSAbbrev);
40940b57cec5SDimitry Andric   NameVals.clear();
40950b57cec5SDimitry Andric }
40960b57cec5SDimitry Andric 
40970b57cec5SDimitry Andric // Collect the global value references in the given variable's initializer,
40980b57cec5SDimitry Andric // and emit them in a summary record.
writeModuleLevelReferences(const GlobalVariable & V,SmallVector<uint64_t,64> & NameVals,unsigned FSModRefsAbbrev,unsigned FSModVTableRefsAbbrev)40990b57cec5SDimitry Andric void ModuleBitcodeWriterBase::writeModuleLevelReferences(
41000b57cec5SDimitry Andric     const GlobalVariable &V, SmallVector<uint64_t, 64> &NameVals,
41010b57cec5SDimitry Andric     unsigned FSModRefsAbbrev, unsigned FSModVTableRefsAbbrev) {
41020b57cec5SDimitry Andric   auto VI = Index->getValueInfo(V.getGUID());
41030b57cec5SDimitry Andric   if (!VI || VI.getSummaryList().empty()) {
41040b57cec5SDimitry Andric     // Only declarations should not have a summary (a declaration might however
41050b57cec5SDimitry Andric     // have a summary if the def was in module level asm).
41060b57cec5SDimitry Andric     assert(V.isDeclaration());
41070b57cec5SDimitry Andric     return;
41080b57cec5SDimitry Andric   }
41090b57cec5SDimitry Andric   auto *Summary = VI.getSummaryList()[0].get();
41100b57cec5SDimitry Andric   NameVals.push_back(VE.getValueID(&V));
41110b57cec5SDimitry Andric   GlobalVarSummary *VS = cast<GlobalVarSummary>(Summary);
41120b57cec5SDimitry Andric   NameVals.push_back(getEncodedGVSummaryFlags(VS->flags()));
41130b57cec5SDimitry Andric   NameVals.push_back(getEncodedGVarFlags(VS->varflags()));
41140b57cec5SDimitry Andric 
41150b57cec5SDimitry Andric   auto VTableFuncs = VS->vTableFuncs();
41160b57cec5SDimitry Andric   if (!VTableFuncs.empty())
41170b57cec5SDimitry Andric     NameVals.push_back(VS->refs().size());
41180b57cec5SDimitry Andric 
41190b57cec5SDimitry Andric   unsigned SizeBeforeRefs = NameVals.size();
41200b57cec5SDimitry Andric   for (auto &RI : VS->refs())
41210b57cec5SDimitry Andric     NameVals.push_back(VE.getValueID(RI.getValue()));
41220b57cec5SDimitry Andric   // Sort the refs for determinism output, the vector returned by FS->refs() has
41230b57cec5SDimitry Andric   // been initialized from a DenseSet.
4124e8d8bef9SDimitry Andric   llvm::sort(drop_begin(NameVals, SizeBeforeRefs));
41250b57cec5SDimitry Andric 
41260b57cec5SDimitry Andric   if (VTableFuncs.empty())
41270b57cec5SDimitry Andric     Stream.EmitRecord(bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS, NameVals,
41280b57cec5SDimitry Andric                       FSModRefsAbbrev);
41290b57cec5SDimitry Andric   else {
41300b57cec5SDimitry Andric     // VTableFuncs pairs should already be sorted by offset.
41310b57cec5SDimitry Andric     for (auto &P : VTableFuncs) {
41320b57cec5SDimitry Andric       NameVals.push_back(VE.getValueID(P.FuncVI.getValue()));
41330b57cec5SDimitry Andric       NameVals.push_back(P.VTableOffset);
41340b57cec5SDimitry Andric     }
41350b57cec5SDimitry Andric 
41360b57cec5SDimitry Andric     Stream.EmitRecord(bitc::FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS, NameVals,
41370b57cec5SDimitry Andric                       FSModVTableRefsAbbrev);
41380b57cec5SDimitry Andric   }
41390b57cec5SDimitry Andric   NameVals.clear();
41400b57cec5SDimitry Andric }
41410b57cec5SDimitry Andric 
41420b57cec5SDimitry Andric /// Emit the per-module summary section alongside the rest of
41430b57cec5SDimitry Andric /// the module's bitcode.
writePerModuleGlobalValueSummary()41440b57cec5SDimitry Andric void ModuleBitcodeWriterBase::writePerModuleGlobalValueSummary() {
41450b57cec5SDimitry Andric   // By default we compile with ThinLTO if the module has a summary, but the
41460b57cec5SDimitry Andric   // client can request full LTO with a module flag.
41470b57cec5SDimitry Andric   bool IsThinLTO = true;
41480b57cec5SDimitry Andric   if (auto *MD =
41490b57cec5SDimitry Andric           mdconst::extract_or_null<ConstantInt>(M.getModuleFlag("ThinLTO")))
41500b57cec5SDimitry Andric     IsThinLTO = MD->getZExtValue();
41510b57cec5SDimitry Andric   Stream.EnterSubblock(IsThinLTO ? bitc::GLOBALVAL_SUMMARY_BLOCK_ID
41520b57cec5SDimitry Andric                                  : bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID,
41530b57cec5SDimitry Andric                        4);
41540b57cec5SDimitry Andric 
4155480093f4SDimitry Andric   Stream.EmitRecord(
4156480093f4SDimitry Andric       bitc::FS_VERSION,
4157480093f4SDimitry Andric       ArrayRef<uint64_t>{ModuleSummaryIndex::BitcodeSummaryVersion});
41580b57cec5SDimitry Andric 
41590b57cec5SDimitry Andric   // Write the index flags.
41600b57cec5SDimitry Andric   uint64_t Flags = 0;
41610b57cec5SDimitry Andric   // Bits 1-3 are set only in the combined index, skip them.
41620b57cec5SDimitry Andric   if (Index->enableSplitLTOUnit())
41630b57cec5SDimitry Andric     Flags |= 0x8;
4164fe013be4SDimitry Andric   if (Index->hasUnifiedLTO())
4165fe013be4SDimitry Andric     Flags |= 0x200;
4166fe013be4SDimitry Andric 
41670b57cec5SDimitry Andric   Stream.EmitRecord(bitc::FS_FLAGS, ArrayRef<uint64_t>{Flags});
41680b57cec5SDimitry Andric 
41690b57cec5SDimitry Andric   if (Index->begin() == Index->end()) {
41700b57cec5SDimitry Andric     Stream.ExitBlock();
41710b57cec5SDimitry Andric     return;
41720b57cec5SDimitry Andric   }
41730b57cec5SDimitry Andric 
41740b57cec5SDimitry Andric   for (const auto &GVI : valueIds()) {
41750b57cec5SDimitry Andric     Stream.EmitRecord(bitc::FS_VALUE_GUID,
41760b57cec5SDimitry Andric                       ArrayRef<uint64_t>{GVI.second, GVI.first});
41770b57cec5SDimitry Andric   }
41780b57cec5SDimitry Andric 
4179bdd1243dSDimitry Andric   if (!Index->stackIds().empty()) {
4180bdd1243dSDimitry Andric     auto StackIdAbbv = std::make_shared<BitCodeAbbrev>();
4181bdd1243dSDimitry Andric     StackIdAbbv->Add(BitCodeAbbrevOp(bitc::FS_STACK_IDS));
4182bdd1243dSDimitry Andric     // numids x stackid
4183bdd1243dSDimitry Andric     StackIdAbbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4184bdd1243dSDimitry Andric     StackIdAbbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4185bdd1243dSDimitry Andric     unsigned StackIdAbbvId = Stream.EmitAbbrev(std::move(StackIdAbbv));
4186bdd1243dSDimitry Andric     Stream.EmitRecord(bitc::FS_STACK_IDS, Index->stackIds(), StackIdAbbvId);
4187bdd1243dSDimitry Andric   }
4188bdd1243dSDimitry Andric 
41890b57cec5SDimitry Andric   // Abbrev for FS_PERMODULE_PROFILE.
41900b57cec5SDimitry Andric   auto Abbv = std::make_shared<BitCodeAbbrev>();
41910b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_PROFILE));
41920b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // valueid
4193fe013be4SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // flags
41940b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // instcount
41950b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // fflags
41960b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // numrefs
41970b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // rorefcnt
41980b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // worefcnt
4199c9157d92SDimitry Andric   // numrefs x valueid, n x (valueid, hotness+tailcall flags)
42000b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
42010b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
42020b57cec5SDimitry Andric   unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(std::move(Abbv));
42030b57cec5SDimitry Andric 
4204c9157d92SDimitry Andric   // Abbrev for FS_PERMODULE_RELBF.
42050b57cec5SDimitry Andric   Abbv = std::make_shared<BitCodeAbbrev>();
42060b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_RELBF));
42070b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // valueid
42080b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // flags
42090b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // instcount
42100b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // fflags
42110b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // numrefs
42120b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // rorefcnt
42130b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // worefcnt
4214c9157d92SDimitry Andric   // numrefs x valueid, n x (valueid, rel_block_freq+tailcall])
42150b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
42160b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4217c9157d92SDimitry Andric   unsigned FSCallsRelBFAbbrev = Stream.EmitAbbrev(std::move(Abbv));
42180b57cec5SDimitry Andric 
42190b57cec5SDimitry Andric   // Abbrev for FS_PERMODULE_GLOBALVAR_INIT_REFS.
42200b57cec5SDimitry Andric   Abbv = std::make_shared<BitCodeAbbrev>();
42210b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS));
42220b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
42230b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
42240b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));  // valueids
42250b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
42260b57cec5SDimitry Andric   unsigned FSModRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
42270b57cec5SDimitry Andric 
42280b57cec5SDimitry Andric   // Abbrev for FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS.
42290b57cec5SDimitry Andric   Abbv = std::make_shared<BitCodeAbbrev>();
42300b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS));
42310b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
42320b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
42330b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
42340b57cec5SDimitry Andric   // numrefs x valueid, n x (valueid , offset)
42350b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
42360b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
42370b57cec5SDimitry Andric   unsigned FSModVTableRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
42380b57cec5SDimitry Andric 
42390b57cec5SDimitry Andric   // Abbrev for FS_ALIAS.
42400b57cec5SDimitry Andric   Abbv = std::make_shared<BitCodeAbbrev>();
42410b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::FS_ALIAS));
42420b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // valueid
42430b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // flags
42440b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // valueid
42450b57cec5SDimitry Andric   unsigned FSAliasAbbrev = Stream.EmitAbbrev(std::move(Abbv));
42460b57cec5SDimitry Andric 
42470b57cec5SDimitry Andric   // Abbrev for FS_TYPE_ID_METADATA
42480b57cec5SDimitry Andric   Abbv = std::make_shared<BitCodeAbbrev>();
42490b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::FS_TYPE_ID_METADATA));
42500b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // typeid strtab index
42510b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // typeid length
42520b57cec5SDimitry Andric   // n x (valueid , offset)
42530b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
42540b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
42550b57cec5SDimitry Andric   unsigned TypeIdCompatibleVtableAbbrev = Stream.EmitAbbrev(std::move(Abbv));
42560b57cec5SDimitry Andric 
4257bdd1243dSDimitry Andric   Abbv = std::make_shared<BitCodeAbbrev>();
4258bdd1243dSDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_CALLSITE_INFO));
4259bdd1243dSDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4260bdd1243dSDimitry Andric   // n x stackidindex
4261bdd1243dSDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4262bdd1243dSDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4263bdd1243dSDimitry Andric   unsigned CallsiteAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4264bdd1243dSDimitry Andric 
4265bdd1243dSDimitry Andric   Abbv = std::make_shared<BitCodeAbbrev>();
4266bdd1243dSDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_ALLOC_INFO));
4267bdd1243dSDimitry Andric   // n x (alloc type, numstackids, numstackids x stackidindex)
4268bdd1243dSDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4269bdd1243dSDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4270bdd1243dSDimitry Andric   unsigned AllocAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4271bdd1243dSDimitry Andric 
42720b57cec5SDimitry Andric   SmallVector<uint64_t, 64> NameVals;
42730b57cec5SDimitry Andric   // Iterate over the list of functions instead of the Index to
42740b57cec5SDimitry Andric   // ensure the ordering is stable.
42750b57cec5SDimitry Andric   for (const Function &F : M) {
42760b57cec5SDimitry Andric     // Summary emission does not support anonymous functions, they have to
42770b57cec5SDimitry Andric     // renamed using the anonymous function renaming pass.
42780b57cec5SDimitry Andric     if (!F.hasName())
42790b57cec5SDimitry Andric       report_fatal_error("Unexpected anonymous function when writing summary");
42800b57cec5SDimitry Andric 
42810b57cec5SDimitry Andric     ValueInfo VI = Index->getValueInfo(F.getGUID());
42820b57cec5SDimitry Andric     if (!VI || VI.getSummaryList().empty()) {
42830b57cec5SDimitry Andric       // Only declarations should not have a summary (a declaration might
42840b57cec5SDimitry Andric       // however have a summary if the def was in module level asm).
42850b57cec5SDimitry Andric       assert(F.isDeclaration());
42860b57cec5SDimitry Andric       continue;
42870b57cec5SDimitry Andric     }
42880b57cec5SDimitry Andric     auto *Summary = VI.getSummaryList()[0].get();
4289c9157d92SDimitry Andric     writePerModuleFunctionSummaryRecord(
4290c9157d92SDimitry Andric         NameVals, Summary, VE.getValueID(&F), FSCallsRelBFAbbrev,
4291c9157d92SDimitry Andric         FSCallsProfileAbbrev, CallsiteAbbrev, AllocAbbrev, F);
42920b57cec5SDimitry Andric   }
42930b57cec5SDimitry Andric 
42940b57cec5SDimitry Andric   // Capture references from GlobalVariable initializers, which are outside
42950b57cec5SDimitry Andric   // of a function scope.
42960b57cec5SDimitry Andric   for (const GlobalVariable &G : M.globals())
42970b57cec5SDimitry Andric     writeModuleLevelReferences(G, NameVals, FSModRefsAbbrev,
42980b57cec5SDimitry Andric                                FSModVTableRefsAbbrev);
42990b57cec5SDimitry Andric 
43000b57cec5SDimitry Andric   for (const GlobalAlias &A : M.aliases()) {
4301349cc55cSDimitry Andric     auto *Aliasee = A.getAliaseeObject();
4302fcaf7f86SDimitry Andric     // Skip ifunc and nameless functions which don't have an entry in the
4303fcaf7f86SDimitry Andric     // summary.
4304fcaf7f86SDimitry Andric     if (!Aliasee->hasName() || isa<GlobalIFunc>(Aliasee))
43050b57cec5SDimitry Andric       continue;
43060b57cec5SDimitry Andric     auto AliasId = VE.getValueID(&A);
43070b57cec5SDimitry Andric     auto AliaseeId = VE.getValueID(Aliasee);
43080b57cec5SDimitry Andric     NameVals.push_back(AliasId);
43090b57cec5SDimitry Andric     auto *Summary = Index->getGlobalValueSummary(A);
43100b57cec5SDimitry Andric     AliasSummary *AS = cast<AliasSummary>(Summary);
43110b57cec5SDimitry Andric     NameVals.push_back(getEncodedGVSummaryFlags(AS->flags()));
43120b57cec5SDimitry Andric     NameVals.push_back(AliaseeId);
43130b57cec5SDimitry Andric     Stream.EmitRecord(bitc::FS_ALIAS, NameVals, FSAliasAbbrev);
43140b57cec5SDimitry Andric     NameVals.clear();
43150b57cec5SDimitry Andric   }
43160b57cec5SDimitry Andric 
43170b57cec5SDimitry Andric   for (auto &S : Index->typeIdCompatibleVtableMap()) {
43180b57cec5SDimitry Andric     writeTypeIdCompatibleVtableSummaryRecord(NameVals, StrtabBuilder, S.first,
43190b57cec5SDimitry Andric                                              S.second, VE);
43200b57cec5SDimitry Andric     Stream.EmitRecord(bitc::FS_TYPE_ID_METADATA, NameVals,
43210b57cec5SDimitry Andric                       TypeIdCompatibleVtableAbbrev);
43220b57cec5SDimitry Andric     NameVals.clear();
43230b57cec5SDimitry Andric   }
43240b57cec5SDimitry Andric 
4325fe013be4SDimitry Andric   if (Index->getBlockCount())
43265ffd83dbSDimitry Andric     Stream.EmitRecord(bitc::FS_BLOCK_COUNT,
43275ffd83dbSDimitry Andric                       ArrayRef<uint64_t>{Index->getBlockCount()});
43285ffd83dbSDimitry Andric 
43290b57cec5SDimitry Andric   Stream.ExitBlock();
43300b57cec5SDimitry Andric }
43310b57cec5SDimitry Andric 
43320b57cec5SDimitry Andric /// Emit the combined summary section into the combined index file.
writeCombinedGlobalValueSummary()43330b57cec5SDimitry Andric void IndexBitcodeWriter::writeCombinedGlobalValueSummary() {
4334bdd1243dSDimitry Andric   Stream.EnterSubblock(bitc::GLOBALVAL_SUMMARY_BLOCK_ID, 4);
4335480093f4SDimitry Andric   Stream.EmitRecord(
4336480093f4SDimitry Andric       bitc::FS_VERSION,
4337480093f4SDimitry Andric       ArrayRef<uint64_t>{ModuleSummaryIndex::BitcodeSummaryVersion});
43380b57cec5SDimitry Andric 
43390b57cec5SDimitry Andric   // Write the index flags.
43405ffd83dbSDimitry Andric   Stream.EmitRecord(bitc::FS_FLAGS, ArrayRef<uint64_t>{Index.getFlags()});
43410b57cec5SDimitry Andric 
43420b57cec5SDimitry Andric   for (const auto &GVI : valueIds()) {
43430b57cec5SDimitry Andric     Stream.EmitRecord(bitc::FS_VALUE_GUID,
43440b57cec5SDimitry Andric                       ArrayRef<uint64_t>{GVI.second, GVI.first});
43450b57cec5SDimitry Andric   }
43460b57cec5SDimitry Andric 
4347bdd1243dSDimitry Andric   if (!StackIdIndices.empty()) {
4348bdd1243dSDimitry Andric     auto StackIdAbbv = std::make_shared<BitCodeAbbrev>();
4349bdd1243dSDimitry Andric     StackIdAbbv->Add(BitCodeAbbrevOp(bitc::FS_STACK_IDS));
4350bdd1243dSDimitry Andric     // numids x stackid
4351bdd1243dSDimitry Andric     StackIdAbbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4352bdd1243dSDimitry Andric     StackIdAbbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4353bdd1243dSDimitry Andric     unsigned StackIdAbbvId = Stream.EmitAbbrev(std::move(StackIdAbbv));
4354bdd1243dSDimitry Andric     // Write the stack ids used by this index, which will be a subset of those in
4355bdd1243dSDimitry Andric     // the full index in the case of distributed indexes.
4356bdd1243dSDimitry Andric     std::vector<uint64_t> StackIds;
4357bdd1243dSDimitry Andric     for (auto &I : StackIdIndices)
4358bdd1243dSDimitry Andric       StackIds.push_back(Index.getStackIdAtIndex(I));
4359bdd1243dSDimitry Andric     Stream.EmitRecord(bitc::FS_STACK_IDS, StackIds, StackIdAbbvId);
4360bdd1243dSDimitry Andric   }
4361bdd1243dSDimitry Andric 
43620b57cec5SDimitry Andric   // Abbrev for FS_COMBINED_PROFILE.
4363c9157d92SDimitry Andric   auto Abbv = std::make_shared<BitCodeAbbrev>();
43640b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_PROFILE));
43650b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // valueid
43660b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // modid
43670b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // 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, 8));   // entrycount
43710b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // numrefs
43720b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // rorefcnt
43730b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // worefcnt
4374c9157d92SDimitry Andric   // numrefs x valueid, n x (valueid, hotness+tailcall flags)
43750b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
43760b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
43770b57cec5SDimitry Andric   unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(std::move(Abbv));
43780b57cec5SDimitry Andric 
43790b57cec5SDimitry Andric   // Abbrev for FS_COMBINED_GLOBALVAR_INIT_REFS.
43800b57cec5SDimitry Andric   Abbv = std::make_shared<BitCodeAbbrev>();
43810b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_GLOBALVAR_INIT_REFS));
43820b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // valueid
43830b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // modid
43840b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // flags
43850b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));    // valueids
43860b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
43870b57cec5SDimitry Andric   unsigned FSModRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
43880b57cec5SDimitry Andric 
43890b57cec5SDimitry Andric   // Abbrev for FS_COMBINED_ALIAS.
43900b57cec5SDimitry Andric   Abbv = std::make_shared<BitCodeAbbrev>();
43910b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_ALIAS));
43920b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // valueid
43930b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // modid
43940b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // flags
43950b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // valueid
43960b57cec5SDimitry Andric   unsigned FSAliasAbbrev = Stream.EmitAbbrev(std::move(Abbv));
43970b57cec5SDimitry Andric 
4398bdd1243dSDimitry Andric   Abbv = std::make_shared<BitCodeAbbrev>();
4399bdd1243dSDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_CALLSITE_INFO));
4400bdd1243dSDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4401bdd1243dSDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numstackindices
4402bdd1243dSDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numver
4403bdd1243dSDimitry Andric   // numstackindices x stackidindex, numver x version
4404bdd1243dSDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4405bdd1243dSDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4406bdd1243dSDimitry Andric   unsigned CallsiteAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4407bdd1243dSDimitry Andric 
4408bdd1243dSDimitry Andric   Abbv = std::make_shared<BitCodeAbbrev>();
4409bdd1243dSDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_ALLOC_INFO));
4410bdd1243dSDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // nummib
4411bdd1243dSDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numver
4412bdd1243dSDimitry Andric   // nummib x (alloc type, numstackids, numstackids x stackidindex),
4413bdd1243dSDimitry Andric   // numver x version
4414bdd1243dSDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4415bdd1243dSDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4416bdd1243dSDimitry Andric   unsigned AllocAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4417bdd1243dSDimitry Andric 
44180b57cec5SDimitry Andric   // The aliases are emitted as a post-pass, and will point to the value
44190b57cec5SDimitry Andric   // id of the aliasee. Save them in a vector for post-processing.
44200b57cec5SDimitry Andric   SmallVector<AliasSummary *, 64> Aliases;
44210b57cec5SDimitry Andric 
44220b57cec5SDimitry Andric   // Save the value id for each summary for alias emission.
44230b57cec5SDimitry Andric   DenseMap<const GlobalValueSummary *, unsigned> SummaryToValueIdMap;
44240b57cec5SDimitry Andric 
44250b57cec5SDimitry Andric   SmallVector<uint64_t, 64> NameVals;
44260b57cec5SDimitry Andric 
44270b57cec5SDimitry Andric   // Set that will be populated during call to writeFunctionTypeMetadataRecords
44280b57cec5SDimitry Andric   // with the type ids referenced by this index file.
44290b57cec5SDimitry Andric   std::set<GlobalValue::GUID> ReferencedTypeIds;
44300b57cec5SDimitry Andric 
44310b57cec5SDimitry Andric   // For local linkage, we also emit the original name separately
44320b57cec5SDimitry Andric   // immediately after the record.
44330b57cec5SDimitry Andric   auto MaybeEmitOriginalName = [&](GlobalValueSummary &S) {
4434349cc55cSDimitry Andric     // We don't need to emit the original name if we are writing the index for
4435349cc55cSDimitry Andric     // distributed backends (in which case ModuleToSummariesForIndex is
4436349cc55cSDimitry Andric     // non-null). The original name is only needed during the thin link, since
4437349cc55cSDimitry Andric     // for SamplePGO the indirect call targets for local functions have
4438349cc55cSDimitry Andric     // have the original name annotated in profile.
4439349cc55cSDimitry Andric     // Continue to emit it when writing out the entire combined index, which is
4440349cc55cSDimitry Andric     // used in testing the thin link via llvm-lto.
4441349cc55cSDimitry Andric     if (ModuleToSummariesForIndex || !GlobalValue::isLocalLinkage(S.linkage()))
44420b57cec5SDimitry Andric       return;
44430b57cec5SDimitry Andric     NameVals.push_back(S.getOriginalName());
44440b57cec5SDimitry Andric     Stream.EmitRecord(bitc::FS_COMBINED_ORIGINAL_NAME, NameVals);
44450b57cec5SDimitry Andric     NameVals.clear();
44460b57cec5SDimitry Andric   };
44470b57cec5SDimitry Andric 
44480b57cec5SDimitry Andric   std::set<GlobalValue::GUID> DefOrUseGUIDs;
44490b57cec5SDimitry Andric   forEachSummary([&](GVInfo I, bool IsAliasee) {
44500b57cec5SDimitry Andric     GlobalValueSummary *S = I.second;
44510b57cec5SDimitry Andric     assert(S);
44520b57cec5SDimitry Andric     DefOrUseGUIDs.insert(I.first);
44530b57cec5SDimitry Andric     for (const ValueInfo &VI : S->refs())
44540b57cec5SDimitry Andric       DefOrUseGUIDs.insert(VI.getGUID());
44550b57cec5SDimitry Andric 
44560b57cec5SDimitry Andric     auto ValueId = getValueId(I.first);
44570b57cec5SDimitry Andric     assert(ValueId);
44580b57cec5SDimitry Andric     SummaryToValueIdMap[S] = *ValueId;
44590b57cec5SDimitry Andric 
44600b57cec5SDimitry Andric     // If this is invoked for an aliasee, we want to record the above
44610b57cec5SDimitry Andric     // mapping, but then not emit a summary entry (if the aliasee is
44620b57cec5SDimitry Andric     // to be imported, we will invoke this separately with IsAliasee=false).
44630b57cec5SDimitry Andric     if (IsAliasee)
44640b57cec5SDimitry Andric       return;
44650b57cec5SDimitry Andric 
44660b57cec5SDimitry Andric     if (auto *AS = dyn_cast<AliasSummary>(S)) {
44670b57cec5SDimitry Andric       // Will process aliases as a post-pass because the reader wants all
44680b57cec5SDimitry Andric       // global to be loaded first.
44690b57cec5SDimitry Andric       Aliases.push_back(AS);
44700b57cec5SDimitry Andric       return;
44710b57cec5SDimitry Andric     }
44720b57cec5SDimitry Andric 
44730b57cec5SDimitry Andric     if (auto *VS = dyn_cast<GlobalVarSummary>(S)) {
44740b57cec5SDimitry Andric       NameVals.push_back(*ValueId);
4475c9157d92SDimitry Andric       assert(ModuleIdMap.count(VS->modulePath()));
4476c9157d92SDimitry Andric       NameVals.push_back(ModuleIdMap[VS->modulePath()]);
44770b57cec5SDimitry Andric       NameVals.push_back(getEncodedGVSummaryFlags(VS->flags()));
44780b57cec5SDimitry Andric       NameVals.push_back(getEncodedGVarFlags(VS->varflags()));
44790b57cec5SDimitry Andric       for (auto &RI : VS->refs()) {
44800b57cec5SDimitry Andric         auto RefValueId = getValueId(RI.getGUID());
44810b57cec5SDimitry Andric         if (!RefValueId)
44820b57cec5SDimitry Andric           continue;
44830b57cec5SDimitry Andric         NameVals.push_back(*RefValueId);
44840b57cec5SDimitry Andric       }
44850b57cec5SDimitry Andric 
44860b57cec5SDimitry Andric       // Emit the finished record.
44870b57cec5SDimitry Andric       Stream.EmitRecord(bitc::FS_COMBINED_GLOBALVAR_INIT_REFS, NameVals,
44880b57cec5SDimitry Andric                         FSModRefsAbbrev);
44890b57cec5SDimitry Andric       NameVals.clear();
44900b57cec5SDimitry Andric       MaybeEmitOriginalName(*S);
44910b57cec5SDimitry Andric       return;
44920b57cec5SDimitry Andric     }
44930b57cec5SDimitry Andric 
4494bdd1243dSDimitry Andric     auto GetValueId = [&](const ValueInfo &VI) -> std::optional<unsigned> {
4495bdd1243dSDimitry Andric       if (!VI)
4496bdd1243dSDimitry Andric         return std::nullopt;
4497349cc55cSDimitry Andric       return getValueId(VI.getGUID());
4498e8d8bef9SDimitry Andric     };
4499e8d8bef9SDimitry Andric 
45000b57cec5SDimitry Andric     auto *FS = cast<FunctionSummary>(S);
4501e8d8bef9SDimitry Andric     writeFunctionTypeMetadataRecords(Stream, FS, GetValueId);
45020b57cec5SDimitry Andric     getReferencedTypeIds(FS, ReferencedTypeIds);
45030b57cec5SDimitry Andric 
4504bdd1243dSDimitry Andric     writeFunctionHeapProfileRecords(
4505bdd1243dSDimitry Andric         Stream, FS, CallsiteAbbrev, AllocAbbrev,
4506bdd1243dSDimitry Andric         /*PerModule*/ false,
4507bdd1243dSDimitry Andric         /*GetValueId*/ [&](const ValueInfo &VI) -> unsigned {
4508bdd1243dSDimitry Andric           std::optional<unsigned> ValueID = GetValueId(VI);
4509bdd1243dSDimitry Andric           // This can happen in shared index files for distributed ThinLTO if
4510bdd1243dSDimitry Andric           // the callee function summary is not included. Record 0 which we
4511bdd1243dSDimitry Andric           // will have to deal with conservatively when doing any kind of
4512bdd1243dSDimitry Andric           // validation in the ThinLTO backends.
4513bdd1243dSDimitry Andric           if (!ValueID)
4514bdd1243dSDimitry Andric             return 0;
4515bdd1243dSDimitry Andric           return *ValueID;
4516bdd1243dSDimitry Andric         },
4517bdd1243dSDimitry Andric         /*GetStackIndex*/ [&](unsigned I) {
4518bdd1243dSDimitry Andric           // Get the corresponding index into the list of StackIdIndices
4519bdd1243dSDimitry Andric           // actually being written for this combined index (which may be a
4520bdd1243dSDimitry Andric           // subset in the case of distributed indexes).
4521bdd1243dSDimitry Andric           auto Lower = llvm::lower_bound(StackIdIndices, I);
4522bdd1243dSDimitry Andric           return std::distance(StackIdIndices.begin(), Lower);
4523bdd1243dSDimitry Andric         });
4524bdd1243dSDimitry Andric 
45250b57cec5SDimitry Andric     NameVals.push_back(*ValueId);
4526c9157d92SDimitry Andric     assert(ModuleIdMap.count(FS->modulePath()));
4527c9157d92SDimitry Andric     NameVals.push_back(ModuleIdMap[FS->modulePath()]);
45280b57cec5SDimitry Andric     NameVals.push_back(getEncodedGVSummaryFlags(FS->flags()));
45290b57cec5SDimitry Andric     NameVals.push_back(FS->instCount());
45300b57cec5SDimitry Andric     NameVals.push_back(getEncodedFFlags(FS->fflags()));
45310b57cec5SDimitry Andric     NameVals.push_back(FS->entryCount());
45320b57cec5SDimitry Andric 
45330b57cec5SDimitry Andric     // Fill in below
45340b57cec5SDimitry Andric     NameVals.push_back(0); // numrefs
45350b57cec5SDimitry Andric     NameVals.push_back(0); // rorefcnt
45360b57cec5SDimitry Andric     NameVals.push_back(0); // worefcnt
45370b57cec5SDimitry Andric 
45380b57cec5SDimitry Andric     unsigned Count = 0, RORefCnt = 0, WORefCnt = 0;
45390b57cec5SDimitry Andric     for (auto &RI : FS->refs()) {
45400b57cec5SDimitry Andric       auto RefValueId = getValueId(RI.getGUID());
45410b57cec5SDimitry Andric       if (!RefValueId)
45420b57cec5SDimitry Andric         continue;
45430b57cec5SDimitry Andric       NameVals.push_back(*RefValueId);
45440b57cec5SDimitry Andric       if (RI.isReadOnly())
45450b57cec5SDimitry Andric         RORefCnt++;
45460b57cec5SDimitry Andric       else if (RI.isWriteOnly())
45470b57cec5SDimitry Andric         WORefCnt++;
45480b57cec5SDimitry Andric       Count++;
45490b57cec5SDimitry Andric     }
45500b57cec5SDimitry Andric     NameVals[6] = Count;
45510b57cec5SDimitry Andric     NameVals[7] = RORefCnt;
45520b57cec5SDimitry Andric     NameVals[8] = WORefCnt;
45530b57cec5SDimitry Andric 
45540b57cec5SDimitry Andric     for (auto &EI : FS->calls()) {
45550b57cec5SDimitry Andric       // If this GUID doesn't have a value id, it doesn't have a function
45560b57cec5SDimitry Andric       // summary and we don't need to record any calls to it.
4557bdd1243dSDimitry Andric       std::optional<unsigned> CallValueId = GetValueId(EI.first);
45580b57cec5SDimitry Andric       if (!CallValueId)
45590b57cec5SDimitry Andric         continue;
45600b57cec5SDimitry Andric       NameVals.push_back(*CallValueId);
4561c9157d92SDimitry Andric       NameVals.push_back(getEncodedHotnessCallEdgeInfo(EI.second));
45620b57cec5SDimitry Andric     }
45630b57cec5SDimitry Andric 
45640b57cec5SDimitry Andric     // Emit the finished record.
4565c9157d92SDimitry Andric     Stream.EmitRecord(bitc::FS_COMBINED_PROFILE, NameVals,
4566c9157d92SDimitry Andric                       FSCallsProfileAbbrev);
45670b57cec5SDimitry Andric     NameVals.clear();
45680b57cec5SDimitry Andric     MaybeEmitOriginalName(*S);
45690b57cec5SDimitry Andric   });
45700b57cec5SDimitry Andric 
45710b57cec5SDimitry Andric   for (auto *AS : Aliases) {
45720b57cec5SDimitry Andric     auto AliasValueId = SummaryToValueIdMap[AS];
45730b57cec5SDimitry Andric     assert(AliasValueId);
45740b57cec5SDimitry Andric     NameVals.push_back(AliasValueId);
4575c9157d92SDimitry Andric     assert(ModuleIdMap.count(AS->modulePath()));
4576c9157d92SDimitry Andric     NameVals.push_back(ModuleIdMap[AS->modulePath()]);
45770b57cec5SDimitry Andric     NameVals.push_back(getEncodedGVSummaryFlags(AS->flags()));
45780b57cec5SDimitry Andric     auto AliaseeValueId = SummaryToValueIdMap[&AS->getAliasee()];
45790b57cec5SDimitry Andric     assert(AliaseeValueId);
45800b57cec5SDimitry Andric     NameVals.push_back(AliaseeValueId);
45810b57cec5SDimitry Andric 
45820b57cec5SDimitry Andric     // Emit the finished record.
45830b57cec5SDimitry Andric     Stream.EmitRecord(bitc::FS_COMBINED_ALIAS, NameVals, FSAliasAbbrev);
45840b57cec5SDimitry Andric     NameVals.clear();
45850b57cec5SDimitry Andric     MaybeEmitOriginalName(*AS);
45860b57cec5SDimitry Andric 
45870b57cec5SDimitry Andric     if (auto *FS = dyn_cast<FunctionSummary>(&AS->getAliasee()))
45880b57cec5SDimitry Andric       getReferencedTypeIds(FS, ReferencedTypeIds);
45890b57cec5SDimitry Andric   }
45900b57cec5SDimitry Andric 
45910b57cec5SDimitry Andric   if (!Index.cfiFunctionDefs().empty()) {
45920b57cec5SDimitry Andric     for (auto &S : Index.cfiFunctionDefs()) {
45930b57cec5SDimitry Andric       if (DefOrUseGUIDs.count(
45940b57cec5SDimitry Andric               GlobalValue::getGUID(GlobalValue::dropLLVMManglingEscape(S)))) {
45950b57cec5SDimitry Andric         NameVals.push_back(StrtabBuilder.add(S));
45960b57cec5SDimitry Andric         NameVals.push_back(S.size());
45970b57cec5SDimitry Andric       }
45980b57cec5SDimitry Andric     }
45990b57cec5SDimitry Andric     if (!NameVals.empty()) {
46000b57cec5SDimitry Andric       Stream.EmitRecord(bitc::FS_CFI_FUNCTION_DEFS, NameVals);
46010b57cec5SDimitry Andric       NameVals.clear();
46020b57cec5SDimitry Andric     }
46030b57cec5SDimitry Andric   }
46040b57cec5SDimitry Andric 
46050b57cec5SDimitry Andric   if (!Index.cfiFunctionDecls().empty()) {
46060b57cec5SDimitry Andric     for (auto &S : Index.cfiFunctionDecls()) {
46070b57cec5SDimitry Andric       if (DefOrUseGUIDs.count(
46080b57cec5SDimitry Andric               GlobalValue::getGUID(GlobalValue::dropLLVMManglingEscape(S)))) {
46090b57cec5SDimitry Andric         NameVals.push_back(StrtabBuilder.add(S));
46100b57cec5SDimitry Andric         NameVals.push_back(S.size());
46110b57cec5SDimitry Andric       }
46120b57cec5SDimitry Andric     }
46130b57cec5SDimitry Andric     if (!NameVals.empty()) {
46140b57cec5SDimitry Andric       Stream.EmitRecord(bitc::FS_CFI_FUNCTION_DECLS, NameVals);
46150b57cec5SDimitry Andric       NameVals.clear();
46160b57cec5SDimitry Andric     }
46170b57cec5SDimitry Andric   }
46180b57cec5SDimitry Andric 
46190b57cec5SDimitry Andric   // Walk the GUIDs that were referenced, and write the
46200b57cec5SDimitry Andric   // corresponding type id records.
46210b57cec5SDimitry Andric   for (auto &T : ReferencedTypeIds) {
46220b57cec5SDimitry Andric     auto TidIter = Index.typeIds().equal_range(T);
46230b57cec5SDimitry Andric     for (auto It = TidIter.first; It != TidIter.second; ++It) {
46240b57cec5SDimitry Andric       writeTypeIdSummaryRecord(NameVals, StrtabBuilder, It->second.first,
46250b57cec5SDimitry Andric                                It->second.second);
46260b57cec5SDimitry Andric       Stream.EmitRecord(bitc::FS_TYPE_ID, NameVals);
46270b57cec5SDimitry Andric       NameVals.clear();
46280b57cec5SDimitry Andric     }
46290b57cec5SDimitry Andric   }
46300b57cec5SDimitry Andric 
4631fe013be4SDimitry Andric   if (Index.getBlockCount())
46325ffd83dbSDimitry Andric     Stream.EmitRecord(bitc::FS_BLOCK_COUNT,
46335ffd83dbSDimitry Andric                       ArrayRef<uint64_t>{Index.getBlockCount()});
46345ffd83dbSDimitry Andric 
46350b57cec5SDimitry Andric   Stream.ExitBlock();
46360b57cec5SDimitry Andric }
46370b57cec5SDimitry Andric 
46380b57cec5SDimitry Andric /// Create the "IDENTIFICATION_BLOCK_ID" containing a single string with the
46390b57cec5SDimitry Andric /// current llvm version, and a record for the epoch number.
writeIdentificationBlock(BitstreamWriter & Stream)46400b57cec5SDimitry Andric static void writeIdentificationBlock(BitstreamWriter &Stream) {
46410b57cec5SDimitry Andric   Stream.EnterSubblock(bitc::IDENTIFICATION_BLOCK_ID, 5);
46420b57cec5SDimitry Andric 
46430b57cec5SDimitry Andric   // Write the "user readable" string identifying the bitcode producer
46440b57cec5SDimitry Andric   auto Abbv = std::make_shared<BitCodeAbbrev>();
46450b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::IDENTIFICATION_CODE_STRING));
46460b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
46470b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
46480b57cec5SDimitry Andric   auto StringAbbrev = Stream.EmitAbbrev(std::move(Abbv));
46490b57cec5SDimitry Andric   writeStringRecord(Stream, bitc::IDENTIFICATION_CODE_STRING,
46500b57cec5SDimitry Andric                     "LLVM" LLVM_VERSION_STRING, StringAbbrev);
46510b57cec5SDimitry Andric 
46520b57cec5SDimitry Andric   // Write the epoch version
46530b57cec5SDimitry Andric   Abbv = std::make_shared<BitCodeAbbrev>();
46540b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::IDENTIFICATION_CODE_EPOCH));
46550b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
46560b57cec5SDimitry Andric   auto EpochAbbrev = Stream.EmitAbbrev(std::move(Abbv));
46575ffd83dbSDimitry Andric   constexpr std::array<unsigned, 1> Vals = {{bitc::BITCODE_CURRENT_EPOCH}};
46580b57cec5SDimitry Andric   Stream.EmitRecord(bitc::IDENTIFICATION_CODE_EPOCH, Vals, EpochAbbrev);
46590b57cec5SDimitry Andric   Stream.ExitBlock();
46600b57cec5SDimitry Andric }
46610b57cec5SDimitry Andric 
writeModuleHash(size_t BlockStartPos)46620b57cec5SDimitry Andric void ModuleBitcodeWriter::writeModuleHash(size_t BlockStartPos) {
46630b57cec5SDimitry Andric   // Emit the module's hash.
46640b57cec5SDimitry Andric   // MODULE_CODE_HASH: [5*i32]
46650b57cec5SDimitry Andric   if (GenerateHash) {
46660b57cec5SDimitry Andric     uint32_t Vals[5];
46670b57cec5SDimitry Andric     Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&(Buffer)[BlockStartPos],
46680b57cec5SDimitry Andric                                     Buffer.size() - BlockStartPos));
466981ad6265SDimitry Andric     std::array<uint8_t, 20> Hash = Hasher.result();
46700b57cec5SDimitry Andric     for (int Pos = 0; Pos < 20; Pos += 4) {
46710b57cec5SDimitry Andric       Vals[Pos / 4] = support::endian::read32be(Hash.data() + Pos);
46720b57cec5SDimitry Andric     }
46730b57cec5SDimitry Andric 
46740b57cec5SDimitry Andric     // Emit the finished record.
46750b57cec5SDimitry Andric     Stream.EmitRecord(bitc::MODULE_CODE_HASH, Vals);
46760b57cec5SDimitry Andric 
46770b57cec5SDimitry Andric     if (ModHash)
46780b57cec5SDimitry Andric       // Save the written hash value.
46790b57cec5SDimitry Andric       llvm::copy(Vals, std::begin(*ModHash));
46800b57cec5SDimitry Andric   }
46810b57cec5SDimitry Andric }
46820b57cec5SDimitry Andric 
write()46830b57cec5SDimitry Andric void ModuleBitcodeWriter::write() {
46840b57cec5SDimitry Andric   writeIdentificationBlock(Stream);
46850b57cec5SDimitry Andric 
46860b57cec5SDimitry Andric   Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
46870b57cec5SDimitry Andric   size_t BlockStartPos = Buffer.size();
46880b57cec5SDimitry Andric 
46890b57cec5SDimitry Andric   writeModuleVersion();
46900b57cec5SDimitry Andric 
46910b57cec5SDimitry Andric   // Emit blockinfo, which defines the standard abbreviations etc.
46920b57cec5SDimitry Andric   writeBlockInfo();
46930b57cec5SDimitry Andric 
46940b57cec5SDimitry Andric   // Emit information describing all of the types in the module.
46950b57cec5SDimitry Andric   writeTypeTable();
46960b57cec5SDimitry Andric 
46970b57cec5SDimitry Andric   // Emit information about attribute groups.
46980b57cec5SDimitry Andric   writeAttributeGroupTable();
46990b57cec5SDimitry Andric 
47000b57cec5SDimitry Andric   // Emit information about parameter attributes.
47010b57cec5SDimitry Andric   writeAttributeTable();
47020b57cec5SDimitry Andric 
47030b57cec5SDimitry Andric   writeComdats();
47040b57cec5SDimitry Andric 
47050b57cec5SDimitry Andric   // Emit top-level description of module, including target triple, inline asm,
47060b57cec5SDimitry Andric   // descriptors for global variables, and function prototype info.
47070b57cec5SDimitry Andric   writeModuleInfo();
47080b57cec5SDimitry Andric 
47090b57cec5SDimitry Andric   // Emit constants.
47100b57cec5SDimitry Andric   writeModuleConstants();
47110b57cec5SDimitry Andric 
47120b57cec5SDimitry Andric   // Emit metadata kind names.
47130b57cec5SDimitry Andric   writeModuleMetadataKinds();
47140b57cec5SDimitry Andric 
47150b57cec5SDimitry Andric   // Emit metadata.
47160b57cec5SDimitry Andric   writeModuleMetadata();
47170b57cec5SDimitry Andric 
47180b57cec5SDimitry Andric   // Emit module-level use-lists.
47190b57cec5SDimitry Andric   if (VE.shouldPreserveUseListOrder())
47200b57cec5SDimitry Andric     writeUseListBlock(nullptr);
47210b57cec5SDimitry Andric 
47220b57cec5SDimitry Andric   writeOperandBundleTags();
47230b57cec5SDimitry Andric   writeSyncScopeNames();
47240b57cec5SDimitry Andric 
47250b57cec5SDimitry Andric   // Emit function bodies.
47260b57cec5SDimitry Andric   DenseMap<const Function *, uint64_t> FunctionToBitcodeIndex;
47274824e7fdSDimitry Andric   for (const Function &F : M)
47284824e7fdSDimitry Andric     if (!F.isDeclaration())
47294824e7fdSDimitry Andric       writeFunction(F, FunctionToBitcodeIndex);
47300b57cec5SDimitry Andric 
47310b57cec5SDimitry Andric   // Need to write after the above call to WriteFunction which populates
47320b57cec5SDimitry Andric   // the summary information in the index.
47330b57cec5SDimitry Andric   if (Index)
47340b57cec5SDimitry Andric     writePerModuleGlobalValueSummary();
47350b57cec5SDimitry Andric 
47360b57cec5SDimitry Andric   writeGlobalValueSymbolTable(FunctionToBitcodeIndex);
47370b57cec5SDimitry Andric 
47380b57cec5SDimitry Andric   writeModuleHash(BlockStartPos);
47390b57cec5SDimitry Andric 
47400b57cec5SDimitry Andric   Stream.ExitBlock();
47410b57cec5SDimitry Andric }
47420b57cec5SDimitry Andric 
writeInt32ToBuffer(uint32_t Value,SmallVectorImpl<char> & Buffer,uint32_t & Position)47430b57cec5SDimitry Andric static void writeInt32ToBuffer(uint32_t Value, SmallVectorImpl<char> &Buffer,
47440b57cec5SDimitry Andric                                uint32_t &Position) {
47450b57cec5SDimitry Andric   support::endian::write32le(&Buffer[Position], Value);
47460b57cec5SDimitry Andric   Position += 4;
47470b57cec5SDimitry Andric }
47480b57cec5SDimitry Andric 
47490b57cec5SDimitry Andric /// If generating a bc file on darwin, we have to emit a
47500b57cec5SDimitry Andric /// header and trailer to make it compatible with the system archiver.  To do
47510b57cec5SDimitry Andric /// this we emit the following header, and then emit a trailer that pads the
47520b57cec5SDimitry Andric /// file out to be a multiple of 16 bytes.
47530b57cec5SDimitry Andric ///
47540b57cec5SDimitry Andric /// struct bc_header {
47550b57cec5SDimitry Andric ///   uint32_t Magic;         // 0x0B17C0DE
47560b57cec5SDimitry Andric ///   uint32_t Version;       // Version, currently always 0.
47570b57cec5SDimitry Andric ///   uint32_t BitcodeOffset; // Offset to traditional bitcode file.
47580b57cec5SDimitry Andric ///   uint32_t BitcodeSize;   // Size of traditional bitcode file.
47590b57cec5SDimitry Andric ///   uint32_t CPUType;       // CPU specifier.
47600b57cec5SDimitry Andric ///   ... potentially more later ...
47610b57cec5SDimitry Andric /// };
emitDarwinBCHeaderAndTrailer(SmallVectorImpl<char> & Buffer,const Triple & TT)47620b57cec5SDimitry Andric static void emitDarwinBCHeaderAndTrailer(SmallVectorImpl<char> &Buffer,
47630b57cec5SDimitry Andric                                          const Triple &TT) {
47640b57cec5SDimitry Andric   unsigned CPUType = ~0U;
47650b57cec5SDimitry Andric 
47660b57cec5SDimitry Andric   // Match x86_64-*, i[3-9]86-*, powerpc-*, powerpc64-*, arm-*, thumb-*,
47670b57cec5SDimitry Andric   // armv[0-9]-*, thumbv[0-9]-*, armv5te-*, or armv6t2-*. The CPUType is a magic
47680b57cec5SDimitry Andric   // number from /usr/include/mach/machine.h.  It is ok to reproduce the
47690b57cec5SDimitry Andric   // specific constants here because they are implicitly part of the Darwin ABI.
47700b57cec5SDimitry Andric   enum {
47710b57cec5SDimitry Andric     DARWIN_CPU_ARCH_ABI64      = 0x01000000,
47720b57cec5SDimitry Andric     DARWIN_CPU_TYPE_X86        = 7,
47730b57cec5SDimitry Andric     DARWIN_CPU_TYPE_ARM        = 12,
47740b57cec5SDimitry Andric     DARWIN_CPU_TYPE_POWERPC    = 18
47750b57cec5SDimitry Andric   };
47760b57cec5SDimitry Andric 
47770b57cec5SDimitry Andric   Triple::ArchType Arch = TT.getArch();
47780b57cec5SDimitry Andric   if (Arch == Triple::x86_64)
47790b57cec5SDimitry Andric     CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64;
47800b57cec5SDimitry Andric   else if (Arch == Triple::x86)
47810b57cec5SDimitry Andric     CPUType = DARWIN_CPU_TYPE_X86;
47820b57cec5SDimitry Andric   else if (Arch == Triple::ppc)
47830b57cec5SDimitry Andric     CPUType = DARWIN_CPU_TYPE_POWERPC;
47840b57cec5SDimitry Andric   else if (Arch == Triple::ppc64)
47850b57cec5SDimitry Andric     CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64;
47860b57cec5SDimitry Andric   else if (Arch == Triple::arm || Arch == Triple::thumb)
47870b57cec5SDimitry Andric     CPUType = DARWIN_CPU_TYPE_ARM;
47880b57cec5SDimitry Andric 
47890b57cec5SDimitry Andric   // Traditional Bitcode starts after header.
47900b57cec5SDimitry Andric   assert(Buffer.size() >= BWH_HeaderSize &&
47910b57cec5SDimitry Andric          "Expected header size to be reserved");
47920b57cec5SDimitry Andric   unsigned BCOffset = BWH_HeaderSize;
47930b57cec5SDimitry Andric   unsigned BCSize = Buffer.size() - BWH_HeaderSize;
47940b57cec5SDimitry Andric 
47950b57cec5SDimitry Andric   // Write the magic and version.
47960b57cec5SDimitry Andric   unsigned Position = 0;
47970b57cec5SDimitry Andric   writeInt32ToBuffer(0x0B17C0DE, Buffer, Position);
47980b57cec5SDimitry Andric   writeInt32ToBuffer(0, Buffer, Position); // Version.
47990b57cec5SDimitry Andric   writeInt32ToBuffer(BCOffset, Buffer, Position);
48000b57cec5SDimitry Andric   writeInt32ToBuffer(BCSize, Buffer, Position);
48010b57cec5SDimitry Andric   writeInt32ToBuffer(CPUType, Buffer, Position);
48020b57cec5SDimitry Andric 
48030b57cec5SDimitry Andric   // If the file is not a multiple of 16 bytes, insert dummy padding.
48040b57cec5SDimitry Andric   while (Buffer.size() & 15)
48050b57cec5SDimitry Andric     Buffer.push_back(0);
48060b57cec5SDimitry Andric }
48070b57cec5SDimitry Andric 
48080b57cec5SDimitry Andric /// Helper to write the header common to all bitcode files.
writeBitcodeHeader(BitstreamWriter & Stream)48090b57cec5SDimitry Andric static void writeBitcodeHeader(BitstreamWriter &Stream) {
48100b57cec5SDimitry Andric   // Emit the file header.
48110b57cec5SDimitry Andric   Stream.Emit((unsigned)'B', 8);
48120b57cec5SDimitry Andric   Stream.Emit((unsigned)'C', 8);
48130b57cec5SDimitry Andric   Stream.Emit(0x0, 4);
48140b57cec5SDimitry Andric   Stream.Emit(0xC, 4);
48150b57cec5SDimitry Andric   Stream.Emit(0xE, 4);
48160b57cec5SDimitry Andric   Stream.Emit(0xD, 4);
48170b57cec5SDimitry Andric }
48180b57cec5SDimitry Andric 
BitcodeWriter(SmallVectorImpl<char> & Buffer,raw_fd_stream * FS)4819e8d8bef9SDimitry Andric BitcodeWriter::BitcodeWriter(SmallVectorImpl<char> &Buffer, raw_fd_stream *FS)
4820e8d8bef9SDimitry Andric     : Buffer(Buffer), Stream(new BitstreamWriter(Buffer, FS, FlushThreshold)) {
48210b57cec5SDimitry Andric   writeBitcodeHeader(*Stream);
48220b57cec5SDimitry Andric }
48230b57cec5SDimitry Andric 
~BitcodeWriter()48240b57cec5SDimitry Andric BitcodeWriter::~BitcodeWriter() { assert(WroteStrtab); }
48250b57cec5SDimitry Andric 
writeBlob(unsigned Block,unsigned Record,StringRef Blob)48260b57cec5SDimitry Andric void BitcodeWriter::writeBlob(unsigned Block, unsigned Record, StringRef Blob) {
48270b57cec5SDimitry Andric   Stream->EnterSubblock(Block, 3);
48280b57cec5SDimitry Andric 
48290b57cec5SDimitry Andric   auto Abbv = std::make_shared<BitCodeAbbrev>();
48300b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(Record));
48310b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
48320b57cec5SDimitry Andric   auto AbbrevNo = Stream->EmitAbbrev(std::move(Abbv));
48330b57cec5SDimitry Andric 
48340b57cec5SDimitry Andric   Stream->EmitRecordWithBlob(AbbrevNo, ArrayRef<uint64_t>{Record}, Blob);
48350b57cec5SDimitry Andric 
48360b57cec5SDimitry Andric   Stream->ExitBlock();
48370b57cec5SDimitry Andric }
48380b57cec5SDimitry Andric 
writeSymtab()48390b57cec5SDimitry Andric void BitcodeWriter::writeSymtab() {
48400b57cec5SDimitry Andric   assert(!WroteStrtab && !WroteSymtab);
48410b57cec5SDimitry Andric 
48420b57cec5SDimitry Andric   // If any module has module-level inline asm, we will require a registered asm
48430b57cec5SDimitry Andric   // parser for the target so that we can create an accurate symbol table for
48440b57cec5SDimitry Andric   // the module.
48450b57cec5SDimitry Andric   for (Module *M : Mods) {
48460b57cec5SDimitry Andric     if (M->getModuleInlineAsm().empty())
48470b57cec5SDimitry Andric       continue;
48480b57cec5SDimitry Andric 
48490b57cec5SDimitry Andric     std::string Err;
48500b57cec5SDimitry Andric     const Triple TT(M->getTargetTriple());
48510b57cec5SDimitry Andric     const Target *T = TargetRegistry::lookupTarget(TT.str(), Err);
48520b57cec5SDimitry Andric     if (!T || !T->hasMCAsmParser())
48530b57cec5SDimitry Andric       return;
48540b57cec5SDimitry Andric   }
48550b57cec5SDimitry Andric 
48560b57cec5SDimitry Andric   WroteSymtab = true;
48570b57cec5SDimitry Andric   SmallVector<char, 0> Symtab;
48580b57cec5SDimitry Andric   // The irsymtab::build function may be unable to create a symbol table if the
48590b57cec5SDimitry Andric   // module is malformed (e.g. it contains an invalid alias). Writing a symbol
48600b57cec5SDimitry Andric   // table is not required for correctness, but we still want to be able to
48610b57cec5SDimitry Andric   // write malformed modules to bitcode files, so swallow the error.
48620b57cec5SDimitry Andric   if (Error E = irsymtab::build(Mods, Symtab, StrtabBuilder, Alloc)) {
48630b57cec5SDimitry Andric     consumeError(std::move(E));
48640b57cec5SDimitry Andric     return;
48650b57cec5SDimitry Andric   }
48660b57cec5SDimitry Andric 
48670b57cec5SDimitry Andric   writeBlob(bitc::SYMTAB_BLOCK_ID, bitc::SYMTAB_BLOB,
48680b57cec5SDimitry Andric             {Symtab.data(), Symtab.size()});
48690b57cec5SDimitry Andric }
48700b57cec5SDimitry Andric 
writeStrtab()48710b57cec5SDimitry Andric void BitcodeWriter::writeStrtab() {
48720b57cec5SDimitry Andric   assert(!WroteStrtab);
48730b57cec5SDimitry Andric 
48740b57cec5SDimitry Andric   std::vector<char> Strtab;
48750b57cec5SDimitry Andric   StrtabBuilder.finalizeInOrder();
48760b57cec5SDimitry Andric   Strtab.resize(StrtabBuilder.getSize());
48770b57cec5SDimitry Andric   StrtabBuilder.write((uint8_t *)Strtab.data());
48780b57cec5SDimitry Andric 
48790b57cec5SDimitry Andric   writeBlob(bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB,
48800b57cec5SDimitry Andric             {Strtab.data(), Strtab.size()});
48810b57cec5SDimitry Andric 
48820b57cec5SDimitry Andric   WroteStrtab = true;
48830b57cec5SDimitry Andric }
48840b57cec5SDimitry Andric 
copyStrtab(StringRef Strtab)48850b57cec5SDimitry Andric void BitcodeWriter::copyStrtab(StringRef Strtab) {
48860b57cec5SDimitry Andric   writeBlob(bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB, Strtab);
48870b57cec5SDimitry Andric   WroteStrtab = true;
48880b57cec5SDimitry Andric }
48890b57cec5SDimitry Andric 
writeModule(const Module & M,bool ShouldPreserveUseListOrder,const ModuleSummaryIndex * Index,bool GenerateHash,ModuleHash * ModHash)48900b57cec5SDimitry Andric void BitcodeWriter::writeModule(const Module &M,
48910b57cec5SDimitry Andric                                 bool ShouldPreserveUseListOrder,
48920b57cec5SDimitry Andric                                 const ModuleSummaryIndex *Index,
48930b57cec5SDimitry Andric                                 bool GenerateHash, ModuleHash *ModHash) {
48940b57cec5SDimitry Andric   assert(!WroteStrtab);
48950b57cec5SDimitry Andric 
48960b57cec5SDimitry Andric   // The Mods vector is used by irsymtab::build, which requires non-const
48970b57cec5SDimitry Andric   // Modules in case it needs to materialize metadata. But the bitcode writer
48980b57cec5SDimitry Andric   // requires that the module is materialized, so we can cast to non-const here,
48990b57cec5SDimitry Andric   // after checking that it is in fact materialized.
49000b57cec5SDimitry Andric   assert(M.isMaterialized());
49010b57cec5SDimitry Andric   Mods.push_back(const_cast<Module *>(&M));
49020b57cec5SDimitry Andric 
49030b57cec5SDimitry Andric   ModuleBitcodeWriter ModuleWriter(M, Buffer, StrtabBuilder, *Stream,
49040b57cec5SDimitry Andric                                    ShouldPreserveUseListOrder, Index,
49050b57cec5SDimitry Andric                                    GenerateHash, ModHash);
49060b57cec5SDimitry Andric   ModuleWriter.write();
49070b57cec5SDimitry Andric }
49080b57cec5SDimitry Andric 
writeIndex(const ModuleSummaryIndex * Index,const std::map<std::string,GVSummaryMapTy> * ModuleToSummariesForIndex)49090b57cec5SDimitry Andric void BitcodeWriter::writeIndex(
49100b57cec5SDimitry Andric     const ModuleSummaryIndex *Index,
49110b57cec5SDimitry Andric     const std::map<std::string, GVSummaryMapTy> *ModuleToSummariesForIndex) {
49120b57cec5SDimitry Andric   IndexBitcodeWriter IndexWriter(*Stream, StrtabBuilder, *Index,
49130b57cec5SDimitry Andric                                  ModuleToSummariesForIndex);
49140b57cec5SDimitry Andric   IndexWriter.write();
49150b57cec5SDimitry Andric }
49160b57cec5SDimitry Andric 
49170b57cec5SDimitry Andric /// Write the specified module to the specified output stream.
WriteBitcodeToFile(const Module & M,raw_ostream & Out,bool ShouldPreserveUseListOrder,const ModuleSummaryIndex * Index,bool GenerateHash,ModuleHash * ModHash)49180b57cec5SDimitry Andric void llvm::WriteBitcodeToFile(const Module &M, raw_ostream &Out,
49190b57cec5SDimitry Andric                               bool ShouldPreserveUseListOrder,
49200b57cec5SDimitry Andric                               const ModuleSummaryIndex *Index,
49210b57cec5SDimitry Andric                               bool GenerateHash, ModuleHash *ModHash) {
49220b57cec5SDimitry Andric   SmallVector<char, 0> Buffer;
49230b57cec5SDimitry Andric   Buffer.reserve(256*1024);
49240b57cec5SDimitry Andric 
49250b57cec5SDimitry Andric   // If this is darwin or another generic macho target, reserve space for the
49260b57cec5SDimitry Andric   // header.
49270b57cec5SDimitry Andric   Triple TT(M.getTargetTriple());
49280b57cec5SDimitry Andric   if (TT.isOSDarwin() || TT.isOSBinFormatMachO())
49290b57cec5SDimitry Andric     Buffer.insert(Buffer.begin(), BWH_HeaderSize, 0);
49300b57cec5SDimitry Andric 
4931e8d8bef9SDimitry Andric   BitcodeWriter Writer(Buffer, dyn_cast<raw_fd_stream>(&Out));
49320b57cec5SDimitry Andric   Writer.writeModule(M, ShouldPreserveUseListOrder, Index, GenerateHash,
49330b57cec5SDimitry Andric                      ModHash);
49340b57cec5SDimitry Andric   Writer.writeSymtab();
49350b57cec5SDimitry Andric   Writer.writeStrtab();
49360b57cec5SDimitry Andric 
49370b57cec5SDimitry Andric   if (TT.isOSDarwin() || TT.isOSBinFormatMachO())
49380b57cec5SDimitry Andric     emitDarwinBCHeaderAndTrailer(Buffer, TT);
49390b57cec5SDimitry Andric 
49400b57cec5SDimitry Andric   // Write the generated bitstream to "Out".
4941e8d8bef9SDimitry Andric   if (!Buffer.empty())
49420b57cec5SDimitry Andric     Out.write((char *)&Buffer.front(), Buffer.size());
49430b57cec5SDimitry Andric }
49440b57cec5SDimitry Andric 
write()49450b57cec5SDimitry Andric void IndexBitcodeWriter::write() {
49460b57cec5SDimitry Andric   Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
49470b57cec5SDimitry Andric 
49480b57cec5SDimitry Andric   writeModuleVersion();
49490b57cec5SDimitry Andric 
49500b57cec5SDimitry Andric   // Write the module paths in the combined index.
49510b57cec5SDimitry Andric   writeModStrings();
49520b57cec5SDimitry Andric 
49530b57cec5SDimitry Andric   // Write the summary combined index records.
49540b57cec5SDimitry Andric   writeCombinedGlobalValueSummary();
49550b57cec5SDimitry Andric 
49560b57cec5SDimitry Andric   Stream.ExitBlock();
49570b57cec5SDimitry Andric }
49580b57cec5SDimitry Andric 
49590b57cec5SDimitry Andric // Write the specified module summary index to the given raw output stream,
49600b57cec5SDimitry Andric // where it will be written in a new bitcode block. This is used when
49610b57cec5SDimitry Andric // writing the combined index file for ThinLTO. When writing a subset of the
49620b57cec5SDimitry Andric // index for a distributed backend, provide a \p ModuleToSummariesForIndex map.
writeIndexToFile(const ModuleSummaryIndex & Index,raw_ostream & Out,const std::map<std::string,GVSummaryMapTy> * ModuleToSummariesForIndex)49631fd87a68SDimitry Andric void llvm::writeIndexToFile(
49640b57cec5SDimitry Andric     const ModuleSummaryIndex &Index, raw_ostream &Out,
49650b57cec5SDimitry Andric     const std::map<std::string, GVSummaryMapTy> *ModuleToSummariesForIndex) {
49660b57cec5SDimitry Andric   SmallVector<char, 0> Buffer;
49670b57cec5SDimitry Andric   Buffer.reserve(256 * 1024);
49680b57cec5SDimitry Andric 
49690b57cec5SDimitry Andric   BitcodeWriter Writer(Buffer);
49700b57cec5SDimitry Andric   Writer.writeIndex(&Index, ModuleToSummariesForIndex);
49710b57cec5SDimitry Andric   Writer.writeStrtab();
49720b57cec5SDimitry Andric 
49730b57cec5SDimitry Andric   Out.write((char *)&Buffer.front(), Buffer.size());
49740b57cec5SDimitry Andric }
49750b57cec5SDimitry Andric 
49760b57cec5SDimitry Andric namespace {
49770b57cec5SDimitry Andric 
49780b57cec5SDimitry Andric /// Class to manage the bitcode writing for a thin link bitcode file.
49790b57cec5SDimitry Andric class ThinLinkBitcodeWriter : public ModuleBitcodeWriterBase {
49800b57cec5SDimitry Andric   /// ModHash is for use in ThinLTO incremental build, generated while writing
49810b57cec5SDimitry Andric   /// the module bitcode file.
49820b57cec5SDimitry Andric   const ModuleHash *ModHash;
49830b57cec5SDimitry Andric 
49840b57cec5SDimitry Andric public:
ThinLinkBitcodeWriter(const Module & M,StringTableBuilder & StrtabBuilder,BitstreamWriter & Stream,const ModuleSummaryIndex & Index,const ModuleHash & ModHash)49850b57cec5SDimitry Andric   ThinLinkBitcodeWriter(const Module &M, StringTableBuilder &StrtabBuilder,
49860b57cec5SDimitry Andric                         BitstreamWriter &Stream,
49870b57cec5SDimitry Andric                         const ModuleSummaryIndex &Index,
49880b57cec5SDimitry Andric                         const ModuleHash &ModHash)
49890b57cec5SDimitry Andric       : ModuleBitcodeWriterBase(M, StrtabBuilder, Stream,
49900b57cec5SDimitry Andric                                 /*ShouldPreserveUseListOrder=*/false, &Index),
49910b57cec5SDimitry Andric         ModHash(&ModHash) {}
49920b57cec5SDimitry Andric 
49930b57cec5SDimitry Andric   void write();
49940b57cec5SDimitry Andric 
49950b57cec5SDimitry Andric private:
49960b57cec5SDimitry Andric   void writeSimplifiedModuleInfo();
49970b57cec5SDimitry Andric };
49980b57cec5SDimitry Andric 
49990b57cec5SDimitry Andric } // end anonymous namespace
50000b57cec5SDimitry Andric 
50010b57cec5SDimitry Andric // This function writes a simpilified module info for thin link bitcode file.
50020b57cec5SDimitry Andric // It only contains the source file name along with the name(the offset and
50030b57cec5SDimitry Andric // size in strtab) and linkage for global values. For the global value info
50040b57cec5SDimitry Andric // entry, in order to keep linkage at offset 5, there are three zeros used
50050b57cec5SDimitry Andric // as padding.
writeSimplifiedModuleInfo()50060b57cec5SDimitry Andric void ThinLinkBitcodeWriter::writeSimplifiedModuleInfo() {
50070b57cec5SDimitry Andric   SmallVector<unsigned, 64> Vals;
50080b57cec5SDimitry Andric   // Emit the module's source file name.
50090b57cec5SDimitry Andric   {
50100b57cec5SDimitry Andric     StringEncoding Bits = getStringEncoding(M.getSourceFileName());
50110b57cec5SDimitry Andric     BitCodeAbbrevOp AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8);
50120b57cec5SDimitry Andric     if (Bits == SE_Char6)
50130b57cec5SDimitry Andric       AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Char6);
50140b57cec5SDimitry Andric     else if (Bits == SE_Fixed7)
50150b57cec5SDimitry Andric       AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7);
50160b57cec5SDimitry Andric 
50170b57cec5SDimitry Andric     // MODULE_CODE_SOURCE_FILENAME: [namechar x N]
50180b57cec5SDimitry Andric     auto Abbv = std::make_shared<BitCodeAbbrev>();
50190b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_SOURCE_FILENAME));
50200b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
50210b57cec5SDimitry Andric     Abbv->Add(AbbrevOpToUse);
50220b57cec5SDimitry Andric     unsigned FilenameAbbrev = Stream.EmitAbbrev(std::move(Abbv));
50230b57cec5SDimitry Andric 
50240b57cec5SDimitry Andric     for (const auto P : M.getSourceFileName())
50250b57cec5SDimitry Andric       Vals.push_back((unsigned char)P);
50260b57cec5SDimitry Andric 
50270b57cec5SDimitry Andric     Stream.EmitRecord(bitc::MODULE_CODE_SOURCE_FILENAME, Vals, FilenameAbbrev);
50280b57cec5SDimitry Andric     Vals.clear();
50290b57cec5SDimitry Andric   }
50300b57cec5SDimitry Andric 
50310b57cec5SDimitry Andric   // Emit the global variable information.
50320b57cec5SDimitry Andric   for (const GlobalVariable &GV : M.globals()) {
50330b57cec5SDimitry Andric     // GLOBALVAR: [strtab offset, strtab size, 0, 0, 0, linkage]
50340b57cec5SDimitry Andric     Vals.push_back(StrtabBuilder.add(GV.getName()));
50350b57cec5SDimitry Andric     Vals.push_back(GV.getName().size());
50360b57cec5SDimitry Andric     Vals.push_back(0);
50370b57cec5SDimitry Andric     Vals.push_back(0);
50380b57cec5SDimitry Andric     Vals.push_back(0);
50390b57cec5SDimitry Andric     Vals.push_back(getEncodedLinkage(GV));
50400b57cec5SDimitry Andric 
50410b57cec5SDimitry Andric     Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals);
50420b57cec5SDimitry Andric     Vals.clear();
50430b57cec5SDimitry Andric   }
50440b57cec5SDimitry Andric 
50450b57cec5SDimitry Andric   // Emit the function proto information.
50460b57cec5SDimitry Andric   for (const Function &F : M) {
50470b57cec5SDimitry Andric     // FUNCTION:  [strtab offset, strtab size, 0, 0, 0, linkage]
50480b57cec5SDimitry Andric     Vals.push_back(StrtabBuilder.add(F.getName()));
50490b57cec5SDimitry Andric     Vals.push_back(F.getName().size());
50500b57cec5SDimitry Andric     Vals.push_back(0);
50510b57cec5SDimitry Andric     Vals.push_back(0);
50520b57cec5SDimitry Andric     Vals.push_back(0);
50530b57cec5SDimitry Andric     Vals.push_back(getEncodedLinkage(F));
50540b57cec5SDimitry Andric 
50550b57cec5SDimitry Andric     Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals);
50560b57cec5SDimitry Andric     Vals.clear();
50570b57cec5SDimitry Andric   }
50580b57cec5SDimitry Andric 
50590b57cec5SDimitry Andric   // Emit the alias information.
50600b57cec5SDimitry Andric   for (const GlobalAlias &A : M.aliases()) {
50610b57cec5SDimitry Andric     // ALIAS: [strtab offset, strtab size, 0, 0, 0, linkage]
50620b57cec5SDimitry Andric     Vals.push_back(StrtabBuilder.add(A.getName()));
50630b57cec5SDimitry Andric     Vals.push_back(A.getName().size());
50640b57cec5SDimitry Andric     Vals.push_back(0);
50650b57cec5SDimitry Andric     Vals.push_back(0);
50660b57cec5SDimitry Andric     Vals.push_back(0);
50670b57cec5SDimitry Andric     Vals.push_back(getEncodedLinkage(A));
50680b57cec5SDimitry Andric 
50690b57cec5SDimitry Andric     Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals);
50700b57cec5SDimitry Andric     Vals.clear();
50710b57cec5SDimitry Andric   }
50720b57cec5SDimitry Andric 
50730b57cec5SDimitry Andric   // Emit the ifunc information.
50740b57cec5SDimitry Andric   for (const GlobalIFunc &I : M.ifuncs()) {
50750b57cec5SDimitry Andric     // IFUNC: [strtab offset, strtab size, 0, 0, 0, linkage]
50760b57cec5SDimitry Andric     Vals.push_back(StrtabBuilder.add(I.getName()));
50770b57cec5SDimitry Andric     Vals.push_back(I.getName().size());
50780b57cec5SDimitry Andric     Vals.push_back(0);
50790b57cec5SDimitry Andric     Vals.push_back(0);
50800b57cec5SDimitry Andric     Vals.push_back(0);
50810b57cec5SDimitry Andric     Vals.push_back(getEncodedLinkage(I));
50820b57cec5SDimitry Andric 
50830b57cec5SDimitry Andric     Stream.EmitRecord(bitc::MODULE_CODE_IFUNC, Vals);
50840b57cec5SDimitry Andric     Vals.clear();
50850b57cec5SDimitry Andric   }
50860b57cec5SDimitry Andric }
50870b57cec5SDimitry Andric 
write()50880b57cec5SDimitry Andric void ThinLinkBitcodeWriter::write() {
50890b57cec5SDimitry Andric   Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
50900b57cec5SDimitry Andric 
50910b57cec5SDimitry Andric   writeModuleVersion();
50920b57cec5SDimitry Andric 
50930b57cec5SDimitry Andric   writeSimplifiedModuleInfo();
50940b57cec5SDimitry Andric 
50950b57cec5SDimitry Andric   writePerModuleGlobalValueSummary();
50960b57cec5SDimitry Andric 
50970b57cec5SDimitry Andric   // Write module hash.
50980b57cec5SDimitry Andric   Stream.EmitRecord(bitc::MODULE_CODE_HASH, ArrayRef<uint32_t>(*ModHash));
50990b57cec5SDimitry Andric 
51000b57cec5SDimitry Andric   Stream.ExitBlock();
51010b57cec5SDimitry Andric }
51020b57cec5SDimitry Andric 
writeThinLinkBitcode(const Module & M,const ModuleSummaryIndex & Index,const ModuleHash & ModHash)51030b57cec5SDimitry Andric void BitcodeWriter::writeThinLinkBitcode(const Module &M,
51040b57cec5SDimitry Andric                                          const ModuleSummaryIndex &Index,
51050b57cec5SDimitry Andric                                          const ModuleHash &ModHash) {
51060b57cec5SDimitry Andric   assert(!WroteStrtab);
51070b57cec5SDimitry Andric 
51080b57cec5SDimitry Andric   // The Mods vector is used by irsymtab::build, which requires non-const
51090b57cec5SDimitry Andric   // Modules in case it needs to materialize metadata. But the bitcode writer
51100b57cec5SDimitry Andric   // requires that the module is materialized, so we can cast to non-const here,
51110b57cec5SDimitry Andric   // after checking that it is in fact materialized.
51120b57cec5SDimitry Andric   assert(M.isMaterialized());
51130b57cec5SDimitry Andric   Mods.push_back(const_cast<Module *>(&M));
51140b57cec5SDimitry Andric 
51150b57cec5SDimitry Andric   ThinLinkBitcodeWriter ThinLinkWriter(M, StrtabBuilder, *Stream, Index,
51160b57cec5SDimitry Andric                                        ModHash);
51170b57cec5SDimitry Andric   ThinLinkWriter.write();
51180b57cec5SDimitry Andric }
51190b57cec5SDimitry Andric 
51200b57cec5SDimitry Andric // Write the specified thin link bitcode file to the given raw output stream,
51210b57cec5SDimitry Andric // where it will be written in a new bitcode block. This is used when
51220b57cec5SDimitry Andric // writing the per-module index file for ThinLTO.
writeThinLinkBitcodeToFile(const Module & M,raw_ostream & Out,const ModuleSummaryIndex & Index,const ModuleHash & ModHash)51231fd87a68SDimitry Andric void llvm::writeThinLinkBitcodeToFile(const Module &M, raw_ostream &Out,
51240b57cec5SDimitry Andric                                       const ModuleSummaryIndex &Index,
51250b57cec5SDimitry Andric                                       const ModuleHash &ModHash) {
51260b57cec5SDimitry Andric   SmallVector<char, 0> Buffer;
51270b57cec5SDimitry Andric   Buffer.reserve(256 * 1024);
51280b57cec5SDimitry Andric 
51290b57cec5SDimitry Andric   BitcodeWriter Writer(Buffer);
51300b57cec5SDimitry Andric   Writer.writeThinLinkBitcode(M, Index, ModHash);
51310b57cec5SDimitry Andric   Writer.writeSymtab();
51320b57cec5SDimitry Andric   Writer.writeStrtab();
51330b57cec5SDimitry Andric 
51340b57cec5SDimitry Andric   Out.write((char *)&Buffer.front(), Buffer.size());
51350b57cec5SDimitry Andric }
5136480093f4SDimitry Andric 
getSectionNameForBitcode(const Triple & T)5137480093f4SDimitry Andric static const char *getSectionNameForBitcode(const Triple &T) {
5138480093f4SDimitry Andric   switch (T.getObjectFormat()) {
5139480093f4SDimitry Andric   case Triple::MachO:
5140480093f4SDimitry Andric     return "__LLVM,__bitcode";
5141480093f4SDimitry Andric   case Triple::COFF:
5142480093f4SDimitry Andric   case Triple::ELF:
5143480093f4SDimitry Andric   case Triple::Wasm:
5144480093f4SDimitry Andric   case Triple::UnknownObjectFormat:
5145480093f4SDimitry Andric     return ".llvmbc";
5146e8d8bef9SDimitry Andric   case Triple::GOFF:
5147e8d8bef9SDimitry Andric     llvm_unreachable("GOFF is not yet implemented");
5148e8d8bef9SDimitry Andric     break;
514981ad6265SDimitry Andric   case Triple::SPIRV:
515081ad6265SDimitry Andric     llvm_unreachable("SPIRV is not yet implemented");
515181ad6265SDimitry Andric     break;
5152480093f4SDimitry Andric   case Triple::XCOFF:
5153480093f4SDimitry Andric     llvm_unreachable("XCOFF is not yet implemented");
5154480093f4SDimitry Andric     break;
515581ad6265SDimitry Andric   case Triple::DXContainer:
515681ad6265SDimitry Andric     llvm_unreachable("DXContainer is not yet implemented");
515781ad6265SDimitry Andric     break;
5158480093f4SDimitry Andric   }
5159480093f4SDimitry Andric   llvm_unreachable("Unimplemented ObjectFormatType");
5160480093f4SDimitry Andric }
5161480093f4SDimitry Andric 
getSectionNameForCommandline(const Triple & T)5162480093f4SDimitry Andric static const char *getSectionNameForCommandline(const Triple &T) {
5163480093f4SDimitry Andric   switch (T.getObjectFormat()) {
5164480093f4SDimitry Andric   case Triple::MachO:
5165480093f4SDimitry Andric     return "__LLVM,__cmdline";
5166480093f4SDimitry Andric   case Triple::COFF:
5167480093f4SDimitry Andric   case Triple::ELF:
5168480093f4SDimitry Andric   case Triple::Wasm:
5169480093f4SDimitry Andric   case Triple::UnknownObjectFormat:
5170480093f4SDimitry Andric     return ".llvmcmd";
5171e8d8bef9SDimitry Andric   case Triple::GOFF:
5172e8d8bef9SDimitry Andric     llvm_unreachable("GOFF is not yet implemented");
5173e8d8bef9SDimitry Andric     break;
517481ad6265SDimitry Andric   case Triple::SPIRV:
517581ad6265SDimitry Andric     llvm_unreachable("SPIRV is not yet implemented");
517681ad6265SDimitry Andric     break;
5177480093f4SDimitry Andric   case Triple::XCOFF:
5178480093f4SDimitry Andric     llvm_unreachable("XCOFF is not yet implemented");
5179480093f4SDimitry Andric     break;
518081ad6265SDimitry Andric   case Triple::DXContainer:
518181ad6265SDimitry Andric     llvm_unreachable("DXC is not yet implemented");
518281ad6265SDimitry Andric     break;
5183480093f4SDimitry Andric   }
5184480093f4SDimitry Andric   llvm_unreachable("Unimplemented ObjectFormatType");
5185480093f4SDimitry Andric }
5186480093f4SDimitry Andric 
embedBitcodeInModule(llvm::Module & M,llvm::MemoryBufferRef Buf,bool EmbedBitcode,bool EmbedCmdline,const std::vector<uint8_t> & CmdArgs)51871fd87a68SDimitry Andric void llvm::embedBitcodeInModule(llvm::Module &M, llvm::MemoryBufferRef Buf,
5188e8d8bef9SDimitry Andric                                 bool EmbedBitcode, bool EmbedCmdline,
5189e8d8bef9SDimitry Andric                                 const std::vector<uint8_t> &CmdArgs) {
5190480093f4SDimitry Andric   // Save llvm.compiler.used and remove it.
5191480093f4SDimitry Andric   SmallVector<Constant *, 2> UsedArray;
5192fe6060f1SDimitry Andric   SmallVector<GlobalValue *, 4> UsedGlobals;
5193c9157d92SDimitry Andric   Type *UsedElementType = PointerType::getUnqual(M.getContext());
5194480093f4SDimitry Andric   GlobalVariable *Used = collectUsedGlobalVariables(M, UsedGlobals, true);
5195480093f4SDimitry Andric   for (auto *GV : UsedGlobals) {
5196480093f4SDimitry Andric     if (GV->getName() != "llvm.embedded.module" &&
5197480093f4SDimitry Andric         GV->getName() != "llvm.cmdline")
5198480093f4SDimitry Andric       UsedArray.push_back(
5199480093f4SDimitry Andric           ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
5200480093f4SDimitry Andric   }
5201480093f4SDimitry Andric   if (Used)
5202480093f4SDimitry Andric     Used->eraseFromParent();
5203480093f4SDimitry Andric 
5204480093f4SDimitry Andric   // Embed the bitcode for the llvm module.
5205480093f4SDimitry Andric   std::string Data;
5206480093f4SDimitry Andric   ArrayRef<uint8_t> ModuleData;
5207480093f4SDimitry Andric   Triple T(M.getTargetTriple());
5208e8d8bef9SDimitry Andric 
5209480093f4SDimitry Andric   if (EmbedBitcode) {
5210e8d8bef9SDimitry Andric     if (Buf.getBufferSize() == 0 ||
5211e8d8bef9SDimitry Andric         !isBitcode((const unsigned char *)Buf.getBufferStart(),
5212480093f4SDimitry Andric                    (const unsigned char *)Buf.getBufferEnd())) {
5213480093f4SDimitry Andric       // If the input is LLVM Assembly, bitcode is produced by serializing
5214480093f4SDimitry Andric       // the module. Use-lists order need to be preserved in this case.
5215480093f4SDimitry Andric       llvm::raw_string_ostream OS(Data);
5216480093f4SDimitry Andric       llvm::WriteBitcodeToFile(M, OS, /* ShouldPreserveUseListOrder */ true);
5217480093f4SDimitry Andric       ModuleData =
5218480093f4SDimitry Andric           ArrayRef<uint8_t>((const uint8_t *)OS.str().data(), OS.str().size());
5219480093f4SDimitry Andric     } else
5220480093f4SDimitry Andric       // If the input is LLVM bitcode, write the input byte stream directly.
5221480093f4SDimitry Andric       ModuleData = ArrayRef<uint8_t>((const uint8_t *)Buf.getBufferStart(),
5222480093f4SDimitry Andric                                      Buf.getBufferSize());
5223480093f4SDimitry Andric   }
5224480093f4SDimitry Andric   llvm::Constant *ModuleConstant =
5225480093f4SDimitry Andric       llvm::ConstantDataArray::get(M.getContext(), ModuleData);
5226480093f4SDimitry Andric   llvm::GlobalVariable *GV = new llvm::GlobalVariable(
5227480093f4SDimitry Andric       M, ModuleConstant->getType(), true, llvm::GlobalValue::PrivateLinkage,
5228480093f4SDimitry Andric       ModuleConstant);
5229480093f4SDimitry Andric   GV->setSection(getSectionNameForBitcode(T));
5230e8d8bef9SDimitry Andric   // Set alignment to 1 to prevent padding between two contributions from input
5231e8d8bef9SDimitry Andric   // sections after linking.
5232e8d8bef9SDimitry Andric   GV->setAlignment(Align(1));
5233480093f4SDimitry Andric   UsedArray.push_back(
5234480093f4SDimitry Andric       ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
5235480093f4SDimitry Andric   if (llvm::GlobalVariable *Old =
5236480093f4SDimitry Andric           M.getGlobalVariable("llvm.embedded.module", true)) {
523781ad6265SDimitry Andric     assert(Old->hasZeroLiveUses() &&
5238480093f4SDimitry Andric            "llvm.embedded.module can only be used once in llvm.compiler.used");
5239480093f4SDimitry Andric     GV->takeName(Old);
5240480093f4SDimitry Andric     Old->eraseFromParent();
5241480093f4SDimitry Andric   } else {
5242480093f4SDimitry Andric     GV->setName("llvm.embedded.module");
5243480093f4SDimitry Andric   }
5244480093f4SDimitry Andric 
5245480093f4SDimitry Andric   // Skip if only bitcode needs to be embedded.
5246e8d8bef9SDimitry Andric   if (EmbedCmdline) {
5247480093f4SDimitry Andric     // Embed command-line options.
5248e8d8bef9SDimitry Andric     ArrayRef<uint8_t> CmdData(const_cast<uint8_t *>(CmdArgs.data()),
5249e8d8bef9SDimitry Andric                               CmdArgs.size());
5250480093f4SDimitry Andric     llvm::Constant *CmdConstant =
5251480093f4SDimitry Andric         llvm::ConstantDataArray::get(M.getContext(), CmdData);
5252480093f4SDimitry Andric     GV = new llvm::GlobalVariable(M, CmdConstant->getType(), true,
5253480093f4SDimitry Andric                                   llvm::GlobalValue::PrivateLinkage,
5254480093f4SDimitry Andric                                   CmdConstant);
5255480093f4SDimitry Andric     GV->setSection(getSectionNameForCommandline(T));
5256e8d8bef9SDimitry Andric     GV->setAlignment(Align(1));
5257480093f4SDimitry Andric     UsedArray.push_back(
5258480093f4SDimitry Andric         ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
5259480093f4SDimitry Andric     if (llvm::GlobalVariable *Old = M.getGlobalVariable("llvm.cmdline", true)) {
526081ad6265SDimitry Andric       assert(Old->hasZeroLiveUses() &&
5261480093f4SDimitry Andric              "llvm.cmdline can only be used once in llvm.compiler.used");
5262480093f4SDimitry Andric       GV->takeName(Old);
5263480093f4SDimitry Andric       Old->eraseFromParent();
5264480093f4SDimitry Andric     } else {
5265480093f4SDimitry Andric       GV->setName("llvm.cmdline");
5266480093f4SDimitry Andric     }
5267480093f4SDimitry Andric   }
5268480093f4SDimitry Andric 
5269480093f4SDimitry Andric   if (UsedArray.empty())
5270480093f4SDimitry Andric     return;
5271480093f4SDimitry Andric 
5272480093f4SDimitry Andric   // Recreate llvm.compiler.used.
5273480093f4SDimitry Andric   ArrayType *ATy = ArrayType::get(UsedElementType, UsedArray.size());
5274480093f4SDimitry Andric   auto *NewUsed = new GlobalVariable(
5275480093f4SDimitry Andric       M, ATy, false, llvm::GlobalValue::AppendingLinkage,
5276480093f4SDimitry Andric       llvm::ConstantArray::get(ATy, UsedArray), "llvm.compiler.used");
5277480093f4SDimitry Andric   NewUsed->setSection("llvm.metadata");
5278480093f4SDimitry Andric }
5279