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/None.h"
200b57cec5SDimitry Andric #include "llvm/ADT/Optional.h"
210b57cec5SDimitry Andric #include "llvm/ADT/STLExtras.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"
260b57cec5SDimitry Andric #include "llvm/ADT/Triple.h"
27af732203SDimitry Andric #include "llvm/Bitcode/BitcodeCommon.h"
28480093f4SDimitry Andric #include "llvm/Bitcode/BitcodeReader.h"
29480093f4SDimitry Andric #include "llvm/Bitcode/LLVMBitCodes.h"
300b57cec5SDimitry Andric #include "llvm/Bitstream/BitCodes.h"
310b57cec5SDimitry Andric #include "llvm/Bitstream/BitstreamWriter.h"
320b57cec5SDimitry Andric #include "llvm/Config/llvm-config.h"
330b57cec5SDimitry Andric #include "llvm/IR/Attributes.h"
340b57cec5SDimitry Andric #include "llvm/IR/BasicBlock.h"
350b57cec5SDimitry Andric #include "llvm/IR/Comdat.h"
360b57cec5SDimitry Andric #include "llvm/IR/Constant.h"
370b57cec5SDimitry Andric #include "llvm/IR/Constants.h"
380b57cec5SDimitry Andric #include "llvm/IR/DebugInfoMetadata.h"
390b57cec5SDimitry Andric #include "llvm/IR/DebugLoc.h"
400b57cec5SDimitry Andric #include "llvm/IR/DerivedTypes.h"
410b57cec5SDimitry Andric #include "llvm/IR/Function.h"
420b57cec5SDimitry Andric #include "llvm/IR/GlobalAlias.h"
430b57cec5SDimitry Andric #include "llvm/IR/GlobalIFunc.h"
440b57cec5SDimitry Andric #include "llvm/IR/GlobalObject.h"
450b57cec5SDimitry Andric #include "llvm/IR/GlobalValue.h"
460b57cec5SDimitry Andric #include "llvm/IR/GlobalVariable.h"
470b57cec5SDimitry Andric #include "llvm/IR/InlineAsm.h"
480b57cec5SDimitry Andric #include "llvm/IR/InstrTypes.h"
490b57cec5SDimitry Andric #include "llvm/IR/Instruction.h"
500b57cec5SDimitry Andric #include "llvm/IR/Instructions.h"
510b57cec5SDimitry Andric #include "llvm/IR/LLVMContext.h"
520b57cec5SDimitry Andric #include "llvm/IR/Metadata.h"
530b57cec5SDimitry Andric #include "llvm/IR/Module.h"
540b57cec5SDimitry Andric #include "llvm/IR/ModuleSummaryIndex.h"
550b57cec5SDimitry Andric #include "llvm/IR/Operator.h"
560b57cec5SDimitry Andric #include "llvm/IR/Type.h"
570b57cec5SDimitry Andric #include "llvm/IR/UseListOrder.h"
580b57cec5SDimitry Andric #include "llvm/IR/Value.h"
590b57cec5SDimitry Andric #include "llvm/IR/ValueSymbolTable.h"
600b57cec5SDimitry Andric #include "llvm/MC/StringTableBuilder.h"
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/TargetRegistry.h"
710b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.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>
790b57cec5SDimitry Andric #include <string>
800b57cec5SDimitry Andric #include <utility>
810b57cec5SDimitry Andric #include <vector>
820b57cec5SDimitry Andric 
830b57cec5SDimitry Andric using namespace llvm;
840b57cec5SDimitry Andric 
850b57cec5SDimitry Andric static cl::opt<unsigned>
860b57cec5SDimitry Andric     IndexThreshold("bitcode-mdindex-threshold", cl::Hidden, cl::init(25),
870b57cec5SDimitry Andric                    cl::desc("Number of metadatas above which we emit an index "
880b57cec5SDimitry Andric                             "to enable lazy-loading"));
89af732203SDimitry Andric static cl::opt<uint32_t> FlushThreshold(
90af732203SDimitry Andric     "bitcode-flush-threshold", cl::Hidden, cl::init(512),
91af732203SDimitry Andric     cl::desc("The threshold (unit M) for flushing LLVM bitcode."));
920b57cec5SDimitry Andric 
938bcb0991SDimitry Andric static cl::opt<bool> WriteRelBFToSummary(
940b57cec5SDimitry Andric     "write-relbf-to-summary", cl::Hidden, cl::init(false),
950b57cec5SDimitry Andric     cl::desc("Write relative block frequency to function summary "));
960b57cec5SDimitry Andric 
970b57cec5SDimitry Andric extern FunctionSummary::ForceSummaryHotnessType ForceSummaryEdgesCold;
980b57cec5SDimitry Andric 
990b57cec5SDimitry Andric namespace {
1000b57cec5SDimitry Andric 
1010b57cec5SDimitry Andric /// These are manifest constants used by the bitcode writer. They do not need to
1020b57cec5SDimitry Andric /// be kept in sync with the reader, but need to be consistent within this file.
1030b57cec5SDimitry Andric enum {
1040b57cec5SDimitry Andric   // VALUE_SYMTAB_BLOCK abbrev id's.
1050b57cec5SDimitry Andric   VST_ENTRY_8_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
1060b57cec5SDimitry Andric   VST_ENTRY_7_ABBREV,
1070b57cec5SDimitry Andric   VST_ENTRY_6_ABBREV,
1080b57cec5SDimitry Andric   VST_BBENTRY_6_ABBREV,
1090b57cec5SDimitry Andric 
1100b57cec5SDimitry Andric   // CONSTANTS_BLOCK abbrev id's.
1110b57cec5SDimitry Andric   CONSTANTS_SETTYPE_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
1120b57cec5SDimitry Andric   CONSTANTS_INTEGER_ABBREV,
1130b57cec5SDimitry Andric   CONSTANTS_CE_CAST_Abbrev,
1140b57cec5SDimitry Andric   CONSTANTS_NULL_Abbrev,
1150b57cec5SDimitry Andric 
1160b57cec5SDimitry Andric   // FUNCTION_BLOCK abbrev id's.
1170b57cec5SDimitry Andric   FUNCTION_INST_LOAD_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
1180b57cec5SDimitry Andric   FUNCTION_INST_UNOP_ABBREV,
1190b57cec5SDimitry Andric   FUNCTION_INST_UNOP_FLAGS_ABBREV,
1200b57cec5SDimitry Andric   FUNCTION_INST_BINOP_ABBREV,
1210b57cec5SDimitry Andric   FUNCTION_INST_BINOP_FLAGS_ABBREV,
1220b57cec5SDimitry Andric   FUNCTION_INST_CAST_ABBREV,
1230b57cec5SDimitry Andric   FUNCTION_INST_RET_VOID_ABBREV,
1240b57cec5SDimitry Andric   FUNCTION_INST_RET_VAL_ABBREV,
1250b57cec5SDimitry Andric   FUNCTION_INST_UNREACHABLE_ABBREV,
1260b57cec5SDimitry Andric   FUNCTION_INST_GEP_ABBREV,
1270b57cec5SDimitry Andric };
1280b57cec5SDimitry Andric 
1290b57cec5SDimitry Andric /// Abstract class to manage the bitcode writing, subclassed for each bitcode
1300b57cec5SDimitry Andric /// file type.
1310b57cec5SDimitry Andric class BitcodeWriterBase {
1320b57cec5SDimitry Andric protected:
1330b57cec5SDimitry Andric   /// The stream created and owned by the client.
1340b57cec5SDimitry Andric   BitstreamWriter &Stream;
1350b57cec5SDimitry Andric 
1360b57cec5SDimitry Andric   StringTableBuilder &StrtabBuilder;
1370b57cec5SDimitry Andric 
1380b57cec5SDimitry Andric public:
1390b57cec5SDimitry Andric   /// Constructs a BitcodeWriterBase object that writes to the provided
1400b57cec5SDimitry Andric   /// \p Stream.
BitcodeWriterBase(BitstreamWriter & Stream,StringTableBuilder & StrtabBuilder)1410b57cec5SDimitry Andric   BitcodeWriterBase(BitstreamWriter &Stream, StringTableBuilder &StrtabBuilder)
1420b57cec5SDimitry Andric       : Stream(Stream), StrtabBuilder(StrtabBuilder) {}
1430b57cec5SDimitry Andric 
1440b57cec5SDimitry Andric protected:
1450b57cec5SDimitry Andric   void writeBitcodeHeader();
1460b57cec5SDimitry Andric   void writeModuleVersion();
1470b57cec5SDimitry Andric };
1480b57cec5SDimitry Andric 
writeModuleVersion()1490b57cec5SDimitry Andric void BitcodeWriterBase::writeModuleVersion() {
1500b57cec5SDimitry Andric   // VERSION: [version#]
1510b57cec5SDimitry Andric   Stream.EmitRecord(bitc::MODULE_CODE_VERSION, ArrayRef<uint64_t>{2});
1520b57cec5SDimitry Andric }
1530b57cec5SDimitry Andric 
1540b57cec5SDimitry Andric /// Base class to manage the module bitcode writing, currently subclassed for
1550b57cec5SDimitry Andric /// ModuleBitcodeWriter and ThinLinkBitcodeWriter.
1560b57cec5SDimitry Andric class ModuleBitcodeWriterBase : public BitcodeWriterBase {
1570b57cec5SDimitry Andric protected:
1580b57cec5SDimitry Andric   /// The Module to write to bitcode.
1590b57cec5SDimitry Andric   const Module &M;
1600b57cec5SDimitry Andric 
1610b57cec5SDimitry Andric   /// Enumerates ids for all values in the module.
1620b57cec5SDimitry Andric   ValueEnumerator VE;
1630b57cec5SDimitry Andric 
1640b57cec5SDimitry Andric   /// Optional per-module index to write for ThinLTO.
1650b57cec5SDimitry Andric   const ModuleSummaryIndex *Index;
1660b57cec5SDimitry Andric 
1670b57cec5SDimitry Andric   /// Map that holds the correspondence between GUIDs in the summary index,
1680b57cec5SDimitry Andric   /// that came from indirect call profiles, and a value id generated by this
1690b57cec5SDimitry Andric   /// class to use in the VST and summary block records.
1700b57cec5SDimitry Andric   std::map<GlobalValue::GUID, unsigned> GUIDToValueIdMap;
1710b57cec5SDimitry Andric 
1720b57cec5SDimitry Andric   /// Tracks the last value id recorded in the GUIDToValueMap.
1730b57cec5SDimitry Andric   unsigned GlobalValueId;
1740b57cec5SDimitry Andric 
1750b57cec5SDimitry Andric   /// Saves the offset of the VSTOffset record that must eventually be
1760b57cec5SDimitry Andric   /// backpatched with the offset of the actual VST.
1770b57cec5SDimitry Andric   uint64_t VSTOffsetPlaceholder = 0;
1780b57cec5SDimitry Andric 
1790b57cec5SDimitry Andric public:
1800b57cec5SDimitry Andric   /// Constructs a ModuleBitcodeWriterBase object for the given Module,
1810b57cec5SDimitry Andric   /// writing to the provided \p Buffer.
ModuleBitcodeWriterBase(const Module & M,StringTableBuilder & StrtabBuilder,BitstreamWriter & Stream,bool ShouldPreserveUseListOrder,const ModuleSummaryIndex * Index)1820b57cec5SDimitry Andric   ModuleBitcodeWriterBase(const Module &M, StringTableBuilder &StrtabBuilder,
1830b57cec5SDimitry Andric                           BitstreamWriter &Stream,
1840b57cec5SDimitry Andric                           bool ShouldPreserveUseListOrder,
1850b57cec5SDimitry Andric                           const ModuleSummaryIndex *Index)
1860b57cec5SDimitry Andric       : BitcodeWriterBase(Stream, StrtabBuilder), M(M),
1870b57cec5SDimitry Andric         VE(M, ShouldPreserveUseListOrder), Index(Index) {
1880b57cec5SDimitry Andric     // Assign ValueIds to any callee values in the index that came from
1890b57cec5SDimitry Andric     // indirect call profiles and were recorded as a GUID not a Value*
1900b57cec5SDimitry Andric     // (which would have been assigned an ID by the ValueEnumerator).
1910b57cec5SDimitry Andric     // The starting ValueId is just after the number of values in the
1920b57cec5SDimitry Andric     // ValueEnumerator, so that they can be emitted in the VST.
1930b57cec5SDimitry Andric     GlobalValueId = VE.getValues().size();
1940b57cec5SDimitry Andric     if (!Index)
1950b57cec5SDimitry Andric       return;
1960b57cec5SDimitry Andric     for (const auto &GUIDSummaryLists : *Index)
1970b57cec5SDimitry Andric       // Examine all summaries for this GUID.
1980b57cec5SDimitry Andric       for (auto &Summary : GUIDSummaryLists.second.SummaryList)
1990b57cec5SDimitry Andric         if (auto FS = dyn_cast<FunctionSummary>(Summary.get()))
2000b57cec5SDimitry Andric           // For each call in the function summary, see if the call
2010b57cec5SDimitry Andric           // is to a GUID (which means it is for an indirect call,
2020b57cec5SDimitry Andric           // otherwise we would have a Value for it). If so, synthesize
2030b57cec5SDimitry Andric           // a value id.
2040b57cec5SDimitry Andric           for (auto &CallEdge : FS->calls())
2050b57cec5SDimitry Andric             if (!CallEdge.first.haveGVs() || !CallEdge.first.getValue())
2060b57cec5SDimitry Andric               assignValueId(CallEdge.first.getGUID());
2070b57cec5SDimitry Andric   }
2080b57cec5SDimitry Andric 
2090b57cec5SDimitry Andric protected:
2100b57cec5SDimitry Andric   void writePerModuleGlobalValueSummary();
2110b57cec5SDimitry Andric 
2120b57cec5SDimitry Andric private:
2130b57cec5SDimitry Andric   void writePerModuleFunctionSummaryRecord(SmallVector<uint64_t, 64> &NameVals,
2140b57cec5SDimitry Andric                                            GlobalValueSummary *Summary,
2150b57cec5SDimitry Andric                                            unsigned ValueID,
2160b57cec5SDimitry Andric                                            unsigned FSCallsAbbrev,
2170b57cec5SDimitry Andric                                            unsigned FSCallsProfileAbbrev,
2180b57cec5SDimitry Andric                                            const Function &F);
2190b57cec5SDimitry Andric   void writeModuleLevelReferences(const GlobalVariable &V,
2200b57cec5SDimitry Andric                                   SmallVector<uint64_t, 64> &NameVals,
2210b57cec5SDimitry Andric                                   unsigned FSModRefsAbbrev,
2220b57cec5SDimitry Andric                                   unsigned FSModVTableRefsAbbrev);
2230b57cec5SDimitry Andric 
assignValueId(GlobalValue::GUID ValGUID)2240b57cec5SDimitry Andric   void assignValueId(GlobalValue::GUID ValGUID) {
2250b57cec5SDimitry Andric     GUIDToValueIdMap[ValGUID] = ++GlobalValueId;
2260b57cec5SDimitry Andric   }
2270b57cec5SDimitry Andric 
getValueId(GlobalValue::GUID ValGUID)2280b57cec5SDimitry Andric   unsigned getValueId(GlobalValue::GUID ValGUID) {
2290b57cec5SDimitry Andric     const auto &VMI = GUIDToValueIdMap.find(ValGUID);
2300b57cec5SDimitry Andric     // Expect that any GUID value had a value Id assigned by an
2310b57cec5SDimitry Andric     // earlier call to assignValueId.
2320b57cec5SDimitry Andric     assert(VMI != GUIDToValueIdMap.end() &&
2330b57cec5SDimitry Andric            "GUID does not have assigned value Id");
2340b57cec5SDimitry Andric     return VMI->second;
2350b57cec5SDimitry Andric   }
2360b57cec5SDimitry Andric 
2370b57cec5SDimitry Andric   // Helper to get the valueId for the type of value recorded in VI.
getValueId(ValueInfo VI)2380b57cec5SDimitry Andric   unsigned getValueId(ValueInfo VI) {
2390b57cec5SDimitry Andric     if (!VI.haveGVs() || !VI.getValue())
2400b57cec5SDimitry Andric       return getValueId(VI.getGUID());
2410b57cec5SDimitry Andric     return VE.getValueID(VI.getValue());
2420b57cec5SDimitry Andric   }
2430b57cec5SDimitry Andric 
valueIds()2440b57cec5SDimitry Andric   std::map<GlobalValue::GUID, unsigned> &valueIds() { return GUIDToValueIdMap; }
2450b57cec5SDimitry Andric };
2460b57cec5SDimitry Andric 
2470b57cec5SDimitry Andric /// Class to manage the bitcode writing for a module.
2480b57cec5SDimitry Andric class ModuleBitcodeWriter : public ModuleBitcodeWriterBase {
2490b57cec5SDimitry Andric   /// Pointer to the buffer allocated by caller for bitcode writing.
2500b57cec5SDimitry Andric   const SmallVectorImpl<char> &Buffer;
2510b57cec5SDimitry Andric 
2520b57cec5SDimitry Andric   /// True if a module hash record should be written.
2530b57cec5SDimitry Andric   bool GenerateHash;
2540b57cec5SDimitry Andric 
2550b57cec5SDimitry Andric   /// If non-null, when GenerateHash is true, the resulting hash is written
2560b57cec5SDimitry Andric   /// into ModHash.
2570b57cec5SDimitry Andric   ModuleHash *ModHash;
2580b57cec5SDimitry Andric 
2590b57cec5SDimitry Andric   SHA1 Hasher;
2600b57cec5SDimitry Andric 
2610b57cec5SDimitry Andric   /// The start bit of the identification block.
2620b57cec5SDimitry Andric   uint64_t BitcodeStartBit;
2630b57cec5SDimitry Andric 
2640b57cec5SDimitry Andric public:
2650b57cec5SDimitry Andric   /// Constructs a ModuleBitcodeWriter object for the given Module,
2660b57cec5SDimitry 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)2670b57cec5SDimitry Andric   ModuleBitcodeWriter(const Module &M, SmallVectorImpl<char> &Buffer,
2680b57cec5SDimitry Andric                       StringTableBuilder &StrtabBuilder,
2690b57cec5SDimitry Andric                       BitstreamWriter &Stream, bool ShouldPreserveUseListOrder,
2700b57cec5SDimitry Andric                       const ModuleSummaryIndex *Index, bool GenerateHash,
2710b57cec5SDimitry Andric                       ModuleHash *ModHash = nullptr)
2720b57cec5SDimitry Andric       : ModuleBitcodeWriterBase(M, StrtabBuilder, Stream,
2730b57cec5SDimitry Andric                                 ShouldPreserveUseListOrder, Index),
2740b57cec5SDimitry Andric         Buffer(Buffer), GenerateHash(GenerateHash), ModHash(ModHash),
2750b57cec5SDimitry Andric         BitcodeStartBit(Stream.GetCurrentBitNo()) {}
2760b57cec5SDimitry Andric 
2770b57cec5SDimitry Andric   /// Emit the current module to the bitstream.
2780b57cec5SDimitry Andric   void write();
2790b57cec5SDimitry Andric 
2800b57cec5SDimitry Andric private:
bitcodeStartBit()2810b57cec5SDimitry Andric   uint64_t bitcodeStartBit() { return BitcodeStartBit; }
2820b57cec5SDimitry Andric 
2830b57cec5SDimitry Andric   size_t addToStrtab(StringRef Str);
2840b57cec5SDimitry Andric 
2850b57cec5SDimitry Andric   void writeAttributeGroupTable();
2860b57cec5SDimitry Andric   void writeAttributeTable();
2870b57cec5SDimitry Andric   void writeTypeTable();
2880b57cec5SDimitry Andric   void writeComdats();
2890b57cec5SDimitry Andric   void writeValueSymbolTableForwardDecl();
2900b57cec5SDimitry Andric   void writeModuleInfo();
2910b57cec5SDimitry Andric   void writeValueAsMetadata(const ValueAsMetadata *MD,
2920b57cec5SDimitry Andric                             SmallVectorImpl<uint64_t> &Record);
2930b57cec5SDimitry Andric   void writeMDTuple(const MDTuple *N, SmallVectorImpl<uint64_t> &Record,
2940b57cec5SDimitry Andric                     unsigned Abbrev);
2950b57cec5SDimitry Andric   unsigned createDILocationAbbrev();
2960b57cec5SDimitry Andric   void writeDILocation(const DILocation *N, SmallVectorImpl<uint64_t> &Record,
2970b57cec5SDimitry Andric                        unsigned &Abbrev);
2980b57cec5SDimitry Andric   unsigned createGenericDINodeAbbrev();
2990b57cec5SDimitry Andric   void writeGenericDINode(const GenericDINode *N,
3000b57cec5SDimitry Andric                           SmallVectorImpl<uint64_t> &Record, unsigned &Abbrev);
3010b57cec5SDimitry Andric   void writeDISubrange(const DISubrange *N, SmallVectorImpl<uint64_t> &Record,
3020b57cec5SDimitry Andric                        unsigned Abbrev);
303af732203SDimitry Andric   void writeDIGenericSubrange(const DIGenericSubrange *N,
304af732203SDimitry Andric                               SmallVectorImpl<uint64_t> &Record,
305af732203SDimitry Andric                               unsigned Abbrev);
3060b57cec5SDimitry Andric   void writeDIEnumerator(const DIEnumerator *N,
3070b57cec5SDimitry Andric                          SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
3080b57cec5SDimitry Andric   void writeDIBasicType(const DIBasicType *N, SmallVectorImpl<uint64_t> &Record,
3090b57cec5SDimitry Andric                         unsigned Abbrev);
310af732203SDimitry Andric   void writeDIStringType(const DIStringType *N,
311af732203SDimitry Andric                          SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
3120b57cec5SDimitry Andric   void writeDIDerivedType(const DIDerivedType *N,
3130b57cec5SDimitry Andric                           SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
3140b57cec5SDimitry Andric   void writeDICompositeType(const DICompositeType *N,
3150b57cec5SDimitry Andric                             SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
3160b57cec5SDimitry Andric   void writeDISubroutineType(const DISubroutineType *N,
3170b57cec5SDimitry Andric                              SmallVectorImpl<uint64_t> &Record,
3180b57cec5SDimitry Andric                              unsigned Abbrev);
3190b57cec5SDimitry Andric   void writeDIFile(const DIFile *N, SmallVectorImpl<uint64_t> &Record,
3200b57cec5SDimitry Andric                    unsigned Abbrev);
3210b57cec5SDimitry Andric   void writeDICompileUnit(const DICompileUnit *N,
3220b57cec5SDimitry Andric                           SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
3230b57cec5SDimitry Andric   void writeDISubprogram(const DISubprogram *N,
3240b57cec5SDimitry Andric                          SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
3250b57cec5SDimitry Andric   void writeDILexicalBlock(const DILexicalBlock *N,
3260b57cec5SDimitry Andric                            SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
3270b57cec5SDimitry Andric   void writeDILexicalBlockFile(const DILexicalBlockFile *N,
3280b57cec5SDimitry Andric                                SmallVectorImpl<uint64_t> &Record,
3290b57cec5SDimitry Andric                                unsigned Abbrev);
3300b57cec5SDimitry Andric   void writeDICommonBlock(const DICommonBlock *N,
3310b57cec5SDimitry Andric                           SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
3320b57cec5SDimitry Andric   void writeDINamespace(const DINamespace *N, SmallVectorImpl<uint64_t> &Record,
3330b57cec5SDimitry Andric                         unsigned Abbrev);
3340b57cec5SDimitry Andric   void writeDIMacro(const DIMacro *N, SmallVectorImpl<uint64_t> &Record,
3350b57cec5SDimitry Andric                     unsigned Abbrev);
3360b57cec5SDimitry Andric   void writeDIMacroFile(const DIMacroFile *N, SmallVectorImpl<uint64_t> &Record,
3370b57cec5SDimitry Andric                         unsigned Abbrev);
338*5f7ddb14SDimitry Andric   void writeDIArgList(const DIArgList *N, SmallVectorImpl<uint64_t> &Record,
339*5f7ddb14SDimitry Andric                       unsigned Abbrev);
3400b57cec5SDimitry Andric   void writeDIModule(const DIModule *N, SmallVectorImpl<uint64_t> &Record,
3410b57cec5SDimitry Andric                      unsigned Abbrev);
3420b57cec5SDimitry Andric   void writeDITemplateTypeParameter(const DITemplateTypeParameter *N,
3430b57cec5SDimitry Andric                                     SmallVectorImpl<uint64_t> &Record,
3440b57cec5SDimitry Andric                                     unsigned Abbrev);
3450b57cec5SDimitry Andric   void writeDITemplateValueParameter(const DITemplateValueParameter *N,
3460b57cec5SDimitry Andric                                      SmallVectorImpl<uint64_t> &Record,
3470b57cec5SDimitry Andric                                      unsigned Abbrev);
3480b57cec5SDimitry Andric   void writeDIGlobalVariable(const DIGlobalVariable *N,
3490b57cec5SDimitry Andric                              SmallVectorImpl<uint64_t> &Record,
3500b57cec5SDimitry Andric                              unsigned Abbrev);
3510b57cec5SDimitry Andric   void writeDILocalVariable(const DILocalVariable *N,
3520b57cec5SDimitry Andric                             SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
3530b57cec5SDimitry Andric   void writeDILabel(const DILabel *N,
3540b57cec5SDimitry Andric                     SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
3550b57cec5SDimitry Andric   void writeDIExpression(const DIExpression *N,
3560b57cec5SDimitry Andric                          SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
3570b57cec5SDimitry Andric   void writeDIGlobalVariableExpression(const DIGlobalVariableExpression *N,
3580b57cec5SDimitry Andric                                        SmallVectorImpl<uint64_t> &Record,
3590b57cec5SDimitry Andric                                        unsigned Abbrev);
3600b57cec5SDimitry Andric   void writeDIObjCProperty(const DIObjCProperty *N,
3610b57cec5SDimitry Andric                            SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
3620b57cec5SDimitry Andric   void writeDIImportedEntity(const DIImportedEntity *N,
3630b57cec5SDimitry Andric                              SmallVectorImpl<uint64_t> &Record,
3640b57cec5SDimitry Andric                              unsigned Abbrev);
3650b57cec5SDimitry Andric   unsigned createNamedMetadataAbbrev();
3660b57cec5SDimitry Andric   void writeNamedMetadata(SmallVectorImpl<uint64_t> &Record);
3670b57cec5SDimitry Andric   unsigned createMetadataStringsAbbrev();
3680b57cec5SDimitry Andric   void writeMetadataStrings(ArrayRef<const Metadata *> Strings,
3690b57cec5SDimitry Andric                             SmallVectorImpl<uint64_t> &Record);
3700b57cec5SDimitry Andric   void writeMetadataRecords(ArrayRef<const Metadata *> MDs,
3710b57cec5SDimitry Andric                             SmallVectorImpl<uint64_t> &Record,
3720b57cec5SDimitry Andric                             std::vector<unsigned> *MDAbbrevs = nullptr,
3730b57cec5SDimitry Andric                             std::vector<uint64_t> *IndexPos = nullptr);
3740b57cec5SDimitry Andric   void writeModuleMetadata();
3750b57cec5SDimitry Andric   void writeFunctionMetadata(const Function &F);
3760b57cec5SDimitry Andric   void writeFunctionMetadataAttachment(const Function &F);
3770b57cec5SDimitry Andric   void writeGlobalVariableMetadataAttachment(const GlobalVariable &GV);
3780b57cec5SDimitry Andric   void pushGlobalMetadataAttachment(SmallVectorImpl<uint64_t> &Record,
3790b57cec5SDimitry Andric                                     const GlobalObject &GO);
3800b57cec5SDimitry Andric   void writeModuleMetadataKinds();
3810b57cec5SDimitry Andric   void writeOperandBundleTags();
3820b57cec5SDimitry Andric   void writeSyncScopeNames();
3830b57cec5SDimitry Andric   void writeConstants(unsigned FirstVal, unsigned LastVal, bool isGlobal);
3840b57cec5SDimitry Andric   void writeModuleConstants();
3850b57cec5SDimitry Andric   bool pushValueAndType(const Value *V, unsigned InstID,
3860b57cec5SDimitry Andric                         SmallVectorImpl<unsigned> &Vals);
3875ffd83dbSDimitry Andric   void writeOperandBundles(const CallBase &CB, unsigned InstID);
3880b57cec5SDimitry Andric   void pushValue(const Value *V, unsigned InstID,
3890b57cec5SDimitry Andric                  SmallVectorImpl<unsigned> &Vals);
3900b57cec5SDimitry Andric   void pushValueSigned(const Value *V, unsigned InstID,
3910b57cec5SDimitry Andric                        SmallVectorImpl<uint64_t> &Vals);
3920b57cec5SDimitry Andric   void writeInstruction(const Instruction &I, unsigned InstID,
3930b57cec5SDimitry Andric                         SmallVectorImpl<unsigned> &Vals);
3940b57cec5SDimitry Andric   void writeFunctionLevelValueSymbolTable(const ValueSymbolTable &VST);
3950b57cec5SDimitry Andric   void writeGlobalValueSymbolTable(
3960b57cec5SDimitry Andric       DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex);
3970b57cec5SDimitry Andric   void writeUseList(UseListOrder &&Order);
3980b57cec5SDimitry Andric   void writeUseListBlock(const Function *F);
3990b57cec5SDimitry Andric   void
4000b57cec5SDimitry Andric   writeFunction(const Function &F,
4010b57cec5SDimitry Andric                 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex);
4020b57cec5SDimitry Andric   void writeBlockInfo();
4030b57cec5SDimitry Andric   void writeModuleHash(size_t BlockStartPos);
4040b57cec5SDimitry Andric 
getEncodedSyncScopeID(SyncScope::ID SSID)4050b57cec5SDimitry Andric   unsigned getEncodedSyncScopeID(SyncScope::ID SSID) {
4060b57cec5SDimitry Andric     return unsigned(SSID);
4070b57cec5SDimitry Andric   }
408af732203SDimitry Andric 
getEncodedAlign(MaybeAlign Alignment)409af732203SDimitry Andric   unsigned getEncodedAlign(MaybeAlign Alignment) { return encode(Alignment); }
4100b57cec5SDimitry Andric };
4110b57cec5SDimitry Andric 
4120b57cec5SDimitry Andric /// Class to manage the bitcode writing for a combined index.
4130b57cec5SDimitry Andric class IndexBitcodeWriter : public BitcodeWriterBase {
4140b57cec5SDimitry Andric   /// The combined index to write to bitcode.
4150b57cec5SDimitry Andric   const ModuleSummaryIndex &Index;
4160b57cec5SDimitry Andric 
4170b57cec5SDimitry Andric   /// When writing a subset of the index for distributed backends, client
4180b57cec5SDimitry Andric   /// provides a map of modules to the corresponding GUIDs/summaries to write.
4190b57cec5SDimitry Andric   const std::map<std::string, GVSummaryMapTy> *ModuleToSummariesForIndex;
4200b57cec5SDimitry Andric 
4210b57cec5SDimitry Andric   /// Map that holds the correspondence between the GUID used in the combined
4220b57cec5SDimitry Andric   /// index and a value id generated by this class to use in references.
4230b57cec5SDimitry Andric   std::map<GlobalValue::GUID, unsigned> GUIDToValueIdMap;
4240b57cec5SDimitry Andric 
4250b57cec5SDimitry Andric   /// Tracks the last value id recorded in the GUIDToValueMap.
4260b57cec5SDimitry Andric   unsigned GlobalValueId = 0;
4270b57cec5SDimitry Andric 
4280b57cec5SDimitry Andric public:
4290b57cec5SDimitry Andric   /// Constructs a IndexBitcodeWriter object for the given combined index,
4300b57cec5SDimitry Andric   /// writing to the provided \p Buffer. When writing a subset of the index
4310b57cec5SDimitry 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)4320b57cec5SDimitry Andric   IndexBitcodeWriter(BitstreamWriter &Stream, StringTableBuilder &StrtabBuilder,
4330b57cec5SDimitry Andric                      const ModuleSummaryIndex &Index,
4340b57cec5SDimitry Andric                      const std::map<std::string, GVSummaryMapTy>
4350b57cec5SDimitry Andric                          *ModuleToSummariesForIndex = nullptr)
4360b57cec5SDimitry Andric       : BitcodeWriterBase(Stream, StrtabBuilder), Index(Index),
4370b57cec5SDimitry Andric         ModuleToSummariesForIndex(ModuleToSummariesForIndex) {
4380b57cec5SDimitry Andric     // Assign unique value ids to all summaries to be written, for use
4390b57cec5SDimitry Andric     // in writing out the call graph edges. Save the mapping from GUID
4400b57cec5SDimitry Andric     // to the new global value id to use when writing those edges, which
4410b57cec5SDimitry Andric     // are currently saved in the index in terms of GUID.
4420b57cec5SDimitry Andric     forEachSummary([&](GVInfo I, bool) {
4430b57cec5SDimitry Andric       GUIDToValueIdMap[I.first] = ++GlobalValueId;
4440b57cec5SDimitry Andric     });
4450b57cec5SDimitry Andric   }
4460b57cec5SDimitry Andric 
4470b57cec5SDimitry Andric   /// The below iterator returns the GUID and associated summary.
4480b57cec5SDimitry Andric   using GVInfo = std::pair<GlobalValue::GUID, GlobalValueSummary *>;
4490b57cec5SDimitry Andric 
4500b57cec5SDimitry Andric   /// Calls the callback for each value GUID and summary to be written to
4510b57cec5SDimitry Andric   /// bitcode. This hides the details of whether they are being pulled from the
4520b57cec5SDimitry Andric   /// entire index or just those in a provided ModuleToSummariesForIndex map.
4530b57cec5SDimitry Andric   template<typename Functor>
forEachSummary(Functor Callback)4540b57cec5SDimitry Andric   void forEachSummary(Functor Callback) {
4550b57cec5SDimitry Andric     if (ModuleToSummariesForIndex) {
4560b57cec5SDimitry Andric       for (auto &M : *ModuleToSummariesForIndex)
4570b57cec5SDimitry Andric         for (auto &Summary : M.second) {
4580b57cec5SDimitry Andric           Callback(Summary, false);
4590b57cec5SDimitry Andric           // Ensure aliasee is handled, e.g. for assigning a valueId,
4600b57cec5SDimitry Andric           // even if we are not importing the aliasee directly (the
4610b57cec5SDimitry Andric           // imported alias will contain a copy of aliasee).
4620b57cec5SDimitry Andric           if (auto *AS = dyn_cast<AliasSummary>(Summary.getSecond()))
4630b57cec5SDimitry Andric             Callback({AS->getAliaseeGUID(), &AS->getAliasee()}, true);
4640b57cec5SDimitry Andric         }
4650b57cec5SDimitry Andric     } else {
4660b57cec5SDimitry Andric       for (auto &Summaries : Index)
4670b57cec5SDimitry Andric         for (auto &Summary : Summaries.second.SummaryList)
4680b57cec5SDimitry Andric           Callback({Summaries.first, Summary.get()}, false);
4690b57cec5SDimitry Andric     }
4700b57cec5SDimitry Andric   }
4710b57cec5SDimitry Andric 
4720b57cec5SDimitry Andric   /// Calls the callback for each entry in the modulePaths StringMap that
4730b57cec5SDimitry Andric   /// should be written to the module path string table. This hides the details
4740b57cec5SDimitry Andric   /// of whether they are being pulled from the entire index or just those in a
4750b57cec5SDimitry Andric   /// provided ModuleToSummariesForIndex map.
forEachModule(Functor Callback)4760b57cec5SDimitry Andric   template <typename Functor> void forEachModule(Functor Callback) {
4770b57cec5SDimitry Andric     if (ModuleToSummariesForIndex) {
4780b57cec5SDimitry Andric       for (const auto &M : *ModuleToSummariesForIndex) {
4790b57cec5SDimitry Andric         const auto &MPI = Index.modulePaths().find(M.first);
4800b57cec5SDimitry Andric         if (MPI == Index.modulePaths().end()) {
4810b57cec5SDimitry Andric           // This should only happen if the bitcode file was empty, in which
4820b57cec5SDimitry Andric           // case we shouldn't be importing (the ModuleToSummariesForIndex
4830b57cec5SDimitry Andric           // would only include the module we are writing and index for).
4840b57cec5SDimitry Andric           assert(ModuleToSummariesForIndex->size() == 1);
4850b57cec5SDimitry Andric           continue;
4860b57cec5SDimitry Andric         }
4870b57cec5SDimitry Andric         Callback(*MPI);
4880b57cec5SDimitry Andric       }
4890b57cec5SDimitry Andric     } else {
4900b57cec5SDimitry Andric       for (const auto &MPSE : Index.modulePaths())
4910b57cec5SDimitry Andric         Callback(MPSE);
4920b57cec5SDimitry Andric     }
4930b57cec5SDimitry Andric   }
4940b57cec5SDimitry Andric 
4950b57cec5SDimitry Andric   /// Main entry point for writing a combined index to bitcode.
4960b57cec5SDimitry Andric   void write();
4970b57cec5SDimitry Andric 
4980b57cec5SDimitry Andric private:
4990b57cec5SDimitry Andric   void writeModStrings();
5000b57cec5SDimitry Andric   void writeCombinedGlobalValueSummary();
5010b57cec5SDimitry Andric 
getValueId(GlobalValue::GUID ValGUID)5020b57cec5SDimitry Andric   Optional<unsigned> getValueId(GlobalValue::GUID ValGUID) {
5030b57cec5SDimitry Andric     auto VMI = GUIDToValueIdMap.find(ValGUID);
5040b57cec5SDimitry Andric     if (VMI == GUIDToValueIdMap.end())
5050b57cec5SDimitry Andric       return None;
5060b57cec5SDimitry Andric     return VMI->second;
5070b57cec5SDimitry Andric   }
5080b57cec5SDimitry Andric 
valueIds()5090b57cec5SDimitry Andric   std::map<GlobalValue::GUID, unsigned> &valueIds() { return GUIDToValueIdMap; }
5100b57cec5SDimitry Andric };
5110b57cec5SDimitry Andric 
5120b57cec5SDimitry Andric } // end anonymous namespace
5130b57cec5SDimitry Andric 
getEncodedCastOpcode(unsigned Opcode)5140b57cec5SDimitry Andric static unsigned getEncodedCastOpcode(unsigned Opcode) {
5150b57cec5SDimitry Andric   switch (Opcode) {
5160b57cec5SDimitry Andric   default: llvm_unreachable("Unknown cast instruction!");
5170b57cec5SDimitry Andric   case Instruction::Trunc   : return bitc::CAST_TRUNC;
5180b57cec5SDimitry Andric   case Instruction::ZExt    : return bitc::CAST_ZEXT;
5190b57cec5SDimitry Andric   case Instruction::SExt    : return bitc::CAST_SEXT;
5200b57cec5SDimitry Andric   case Instruction::FPToUI  : return bitc::CAST_FPTOUI;
5210b57cec5SDimitry Andric   case Instruction::FPToSI  : return bitc::CAST_FPTOSI;
5220b57cec5SDimitry Andric   case Instruction::UIToFP  : return bitc::CAST_UITOFP;
5230b57cec5SDimitry Andric   case Instruction::SIToFP  : return bitc::CAST_SITOFP;
5240b57cec5SDimitry Andric   case Instruction::FPTrunc : return bitc::CAST_FPTRUNC;
5250b57cec5SDimitry Andric   case Instruction::FPExt   : return bitc::CAST_FPEXT;
5260b57cec5SDimitry Andric   case Instruction::PtrToInt: return bitc::CAST_PTRTOINT;
5270b57cec5SDimitry Andric   case Instruction::IntToPtr: return bitc::CAST_INTTOPTR;
5280b57cec5SDimitry Andric   case Instruction::BitCast : return bitc::CAST_BITCAST;
5290b57cec5SDimitry Andric   case Instruction::AddrSpaceCast: return bitc::CAST_ADDRSPACECAST;
5300b57cec5SDimitry Andric   }
5310b57cec5SDimitry Andric }
5320b57cec5SDimitry Andric 
getEncodedUnaryOpcode(unsigned Opcode)5330b57cec5SDimitry Andric static unsigned getEncodedUnaryOpcode(unsigned Opcode) {
5340b57cec5SDimitry Andric   switch (Opcode) {
5350b57cec5SDimitry Andric   default: llvm_unreachable("Unknown binary instruction!");
5368bcb0991SDimitry Andric   case Instruction::FNeg: return bitc::UNOP_FNEG;
5370b57cec5SDimitry Andric   }
5380b57cec5SDimitry Andric }
5390b57cec5SDimitry Andric 
getEncodedBinaryOpcode(unsigned Opcode)5400b57cec5SDimitry Andric static unsigned getEncodedBinaryOpcode(unsigned Opcode) {
5410b57cec5SDimitry Andric   switch (Opcode) {
5420b57cec5SDimitry Andric   default: llvm_unreachable("Unknown binary instruction!");
5430b57cec5SDimitry Andric   case Instruction::Add:
5440b57cec5SDimitry Andric   case Instruction::FAdd: return bitc::BINOP_ADD;
5450b57cec5SDimitry Andric   case Instruction::Sub:
5460b57cec5SDimitry Andric   case Instruction::FSub: return bitc::BINOP_SUB;
5470b57cec5SDimitry Andric   case Instruction::Mul:
5480b57cec5SDimitry Andric   case Instruction::FMul: return bitc::BINOP_MUL;
5490b57cec5SDimitry Andric   case Instruction::UDiv: return bitc::BINOP_UDIV;
5500b57cec5SDimitry Andric   case Instruction::FDiv:
5510b57cec5SDimitry Andric   case Instruction::SDiv: return bitc::BINOP_SDIV;
5520b57cec5SDimitry Andric   case Instruction::URem: return bitc::BINOP_UREM;
5530b57cec5SDimitry Andric   case Instruction::FRem:
5540b57cec5SDimitry Andric   case Instruction::SRem: return bitc::BINOP_SREM;
5550b57cec5SDimitry Andric   case Instruction::Shl:  return bitc::BINOP_SHL;
5560b57cec5SDimitry Andric   case Instruction::LShr: return bitc::BINOP_LSHR;
5570b57cec5SDimitry Andric   case Instruction::AShr: return bitc::BINOP_ASHR;
5580b57cec5SDimitry Andric   case Instruction::And:  return bitc::BINOP_AND;
5590b57cec5SDimitry Andric   case Instruction::Or:   return bitc::BINOP_OR;
5600b57cec5SDimitry Andric   case Instruction::Xor:  return bitc::BINOP_XOR;
5610b57cec5SDimitry Andric   }
5620b57cec5SDimitry Andric }
5630b57cec5SDimitry Andric 
getEncodedRMWOperation(AtomicRMWInst::BinOp Op)5640b57cec5SDimitry Andric static unsigned getEncodedRMWOperation(AtomicRMWInst::BinOp Op) {
5650b57cec5SDimitry Andric   switch (Op) {
5660b57cec5SDimitry Andric   default: llvm_unreachable("Unknown RMW operation!");
5670b57cec5SDimitry Andric   case AtomicRMWInst::Xchg: return bitc::RMW_XCHG;
5680b57cec5SDimitry Andric   case AtomicRMWInst::Add: return bitc::RMW_ADD;
5690b57cec5SDimitry Andric   case AtomicRMWInst::Sub: return bitc::RMW_SUB;
5700b57cec5SDimitry Andric   case AtomicRMWInst::And: return bitc::RMW_AND;
5710b57cec5SDimitry Andric   case AtomicRMWInst::Nand: return bitc::RMW_NAND;
5720b57cec5SDimitry Andric   case AtomicRMWInst::Or: return bitc::RMW_OR;
5730b57cec5SDimitry Andric   case AtomicRMWInst::Xor: return bitc::RMW_XOR;
5740b57cec5SDimitry Andric   case AtomicRMWInst::Max: return bitc::RMW_MAX;
5750b57cec5SDimitry Andric   case AtomicRMWInst::Min: return bitc::RMW_MIN;
5760b57cec5SDimitry Andric   case AtomicRMWInst::UMax: return bitc::RMW_UMAX;
5770b57cec5SDimitry Andric   case AtomicRMWInst::UMin: return bitc::RMW_UMIN;
5780b57cec5SDimitry Andric   case AtomicRMWInst::FAdd: return bitc::RMW_FADD;
5790b57cec5SDimitry Andric   case AtomicRMWInst::FSub: return bitc::RMW_FSUB;
5800b57cec5SDimitry Andric   }
5810b57cec5SDimitry Andric }
5820b57cec5SDimitry Andric 
getEncodedOrdering(AtomicOrdering Ordering)5830b57cec5SDimitry Andric static unsigned getEncodedOrdering(AtomicOrdering Ordering) {
5840b57cec5SDimitry Andric   switch (Ordering) {
5850b57cec5SDimitry Andric   case AtomicOrdering::NotAtomic: return bitc::ORDERING_NOTATOMIC;
5860b57cec5SDimitry Andric   case AtomicOrdering::Unordered: return bitc::ORDERING_UNORDERED;
5870b57cec5SDimitry Andric   case AtomicOrdering::Monotonic: return bitc::ORDERING_MONOTONIC;
5880b57cec5SDimitry Andric   case AtomicOrdering::Acquire: return bitc::ORDERING_ACQUIRE;
5890b57cec5SDimitry Andric   case AtomicOrdering::Release: return bitc::ORDERING_RELEASE;
5900b57cec5SDimitry Andric   case AtomicOrdering::AcquireRelease: return bitc::ORDERING_ACQREL;
5910b57cec5SDimitry Andric   case AtomicOrdering::SequentiallyConsistent: return bitc::ORDERING_SEQCST;
5920b57cec5SDimitry Andric   }
5930b57cec5SDimitry Andric   llvm_unreachable("Invalid ordering");
5940b57cec5SDimitry Andric }
5950b57cec5SDimitry Andric 
writeStringRecord(BitstreamWriter & Stream,unsigned Code,StringRef Str,unsigned AbbrevToUse)5960b57cec5SDimitry Andric static void writeStringRecord(BitstreamWriter &Stream, unsigned Code,
5970b57cec5SDimitry Andric                               StringRef Str, unsigned AbbrevToUse) {
5980b57cec5SDimitry Andric   SmallVector<unsigned, 64> Vals;
5990b57cec5SDimitry Andric 
6000b57cec5SDimitry Andric   // Code: [strchar x N]
6010b57cec5SDimitry Andric   for (unsigned i = 0, e = Str.size(); i != e; ++i) {
6020b57cec5SDimitry Andric     if (AbbrevToUse && !BitCodeAbbrevOp::isChar6(Str[i]))
6030b57cec5SDimitry Andric       AbbrevToUse = 0;
6040b57cec5SDimitry Andric     Vals.push_back(Str[i]);
6050b57cec5SDimitry Andric   }
6060b57cec5SDimitry Andric 
6070b57cec5SDimitry Andric   // Emit the finished record.
6080b57cec5SDimitry Andric   Stream.EmitRecord(Code, Vals, AbbrevToUse);
6090b57cec5SDimitry Andric }
6100b57cec5SDimitry Andric 
getAttrKindEncoding(Attribute::AttrKind Kind)6110b57cec5SDimitry Andric static uint64_t getAttrKindEncoding(Attribute::AttrKind Kind) {
6120b57cec5SDimitry Andric   switch (Kind) {
6130b57cec5SDimitry Andric   case Attribute::Alignment:
6140b57cec5SDimitry Andric     return bitc::ATTR_KIND_ALIGNMENT;
6150b57cec5SDimitry Andric   case Attribute::AllocSize:
6160b57cec5SDimitry Andric     return bitc::ATTR_KIND_ALLOC_SIZE;
6170b57cec5SDimitry Andric   case Attribute::AlwaysInline:
6180b57cec5SDimitry Andric     return bitc::ATTR_KIND_ALWAYS_INLINE;
6190b57cec5SDimitry Andric   case Attribute::ArgMemOnly:
6200b57cec5SDimitry Andric     return bitc::ATTR_KIND_ARGMEMONLY;
6210b57cec5SDimitry Andric   case Attribute::Builtin:
6220b57cec5SDimitry Andric     return bitc::ATTR_KIND_BUILTIN;
6230b57cec5SDimitry Andric   case Attribute::ByVal:
6240b57cec5SDimitry Andric     return bitc::ATTR_KIND_BY_VAL;
6250b57cec5SDimitry Andric   case Attribute::Convergent:
6260b57cec5SDimitry Andric     return bitc::ATTR_KIND_CONVERGENT;
6270b57cec5SDimitry Andric   case Attribute::InAlloca:
6280b57cec5SDimitry Andric     return bitc::ATTR_KIND_IN_ALLOCA;
6290b57cec5SDimitry Andric   case Attribute::Cold:
6300b57cec5SDimitry Andric     return bitc::ATTR_KIND_COLD;
631af732203SDimitry Andric   case Attribute::Hot:
632af732203SDimitry Andric     return bitc::ATTR_KIND_HOT;
633*5f7ddb14SDimitry Andric   case Attribute::ElementType:
634*5f7ddb14SDimitry Andric     return bitc::ATTR_KIND_ELEMENTTYPE;
6350b57cec5SDimitry Andric   case Attribute::InaccessibleMemOnly:
6360b57cec5SDimitry Andric     return bitc::ATTR_KIND_INACCESSIBLEMEM_ONLY;
6370b57cec5SDimitry Andric   case Attribute::InaccessibleMemOrArgMemOnly:
6380b57cec5SDimitry Andric     return bitc::ATTR_KIND_INACCESSIBLEMEM_OR_ARGMEMONLY;
6390b57cec5SDimitry Andric   case Attribute::InlineHint:
6400b57cec5SDimitry Andric     return bitc::ATTR_KIND_INLINE_HINT;
6410b57cec5SDimitry Andric   case Attribute::InReg:
6420b57cec5SDimitry Andric     return bitc::ATTR_KIND_IN_REG;
6430b57cec5SDimitry Andric   case Attribute::JumpTable:
6440b57cec5SDimitry Andric     return bitc::ATTR_KIND_JUMP_TABLE;
6450b57cec5SDimitry Andric   case Attribute::MinSize:
6460b57cec5SDimitry Andric     return bitc::ATTR_KIND_MIN_SIZE;
6470b57cec5SDimitry Andric   case Attribute::Naked:
6480b57cec5SDimitry Andric     return bitc::ATTR_KIND_NAKED;
6490b57cec5SDimitry Andric   case Attribute::Nest:
6500b57cec5SDimitry Andric     return bitc::ATTR_KIND_NEST;
6510b57cec5SDimitry Andric   case Attribute::NoAlias:
6520b57cec5SDimitry Andric     return bitc::ATTR_KIND_NO_ALIAS;
6530b57cec5SDimitry Andric   case Attribute::NoBuiltin:
6540b57cec5SDimitry Andric     return bitc::ATTR_KIND_NO_BUILTIN;
655af732203SDimitry Andric   case Attribute::NoCallback:
656af732203SDimitry Andric     return bitc::ATTR_KIND_NO_CALLBACK;
6570b57cec5SDimitry Andric   case Attribute::NoCapture:
6580b57cec5SDimitry Andric     return bitc::ATTR_KIND_NO_CAPTURE;
6590b57cec5SDimitry Andric   case Attribute::NoDuplicate:
6600b57cec5SDimitry Andric     return bitc::ATTR_KIND_NO_DUPLICATE;
6610b57cec5SDimitry Andric   case Attribute::NoFree:
6620b57cec5SDimitry Andric     return bitc::ATTR_KIND_NOFREE;
6630b57cec5SDimitry Andric   case Attribute::NoImplicitFloat:
6640b57cec5SDimitry Andric     return bitc::ATTR_KIND_NO_IMPLICIT_FLOAT;
6650b57cec5SDimitry Andric   case Attribute::NoInline:
6660b57cec5SDimitry Andric     return bitc::ATTR_KIND_NO_INLINE;
6670b57cec5SDimitry Andric   case Attribute::NoRecurse:
6680b57cec5SDimitry Andric     return bitc::ATTR_KIND_NO_RECURSE;
6695ffd83dbSDimitry Andric   case Attribute::NoMerge:
6705ffd83dbSDimitry Andric     return bitc::ATTR_KIND_NO_MERGE;
6710b57cec5SDimitry Andric   case Attribute::NonLazyBind:
6720b57cec5SDimitry Andric     return bitc::ATTR_KIND_NON_LAZY_BIND;
6730b57cec5SDimitry Andric   case Attribute::NonNull:
6740b57cec5SDimitry Andric     return bitc::ATTR_KIND_NON_NULL;
6750b57cec5SDimitry Andric   case Attribute::Dereferenceable:
6760b57cec5SDimitry Andric     return bitc::ATTR_KIND_DEREFERENCEABLE;
6770b57cec5SDimitry Andric   case Attribute::DereferenceableOrNull:
6780b57cec5SDimitry Andric     return bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL;
6790b57cec5SDimitry Andric   case Attribute::NoRedZone:
6800b57cec5SDimitry Andric     return bitc::ATTR_KIND_NO_RED_ZONE;
6810b57cec5SDimitry Andric   case Attribute::NoReturn:
6820b57cec5SDimitry Andric     return bitc::ATTR_KIND_NO_RETURN;
6830b57cec5SDimitry Andric   case Attribute::NoSync:
6840b57cec5SDimitry Andric     return bitc::ATTR_KIND_NOSYNC;
6850b57cec5SDimitry Andric   case Attribute::NoCfCheck:
6860b57cec5SDimitry Andric     return bitc::ATTR_KIND_NOCF_CHECK;
687af732203SDimitry Andric   case Attribute::NoProfile:
688af732203SDimitry Andric     return bitc::ATTR_KIND_NO_PROFILE;
6890b57cec5SDimitry Andric   case Attribute::NoUnwind:
6900b57cec5SDimitry Andric     return bitc::ATTR_KIND_NO_UNWIND;
691*5f7ddb14SDimitry Andric   case Attribute::NoSanitizeCoverage:
692*5f7ddb14SDimitry Andric     return bitc::ATTR_KIND_NO_SANITIZE_COVERAGE;
6935ffd83dbSDimitry Andric   case Attribute::NullPointerIsValid:
6945ffd83dbSDimitry Andric     return bitc::ATTR_KIND_NULL_POINTER_IS_VALID;
6950b57cec5SDimitry Andric   case Attribute::OptForFuzzing:
6960b57cec5SDimitry Andric     return bitc::ATTR_KIND_OPT_FOR_FUZZING;
6970b57cec5SDimitry Andric   case Attribute::OptimizeForSize:
6980b57cec5SDimitry Andric     return bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE;
6990b57cec5SDimitry Andric   case Attribute::OptimizeNone:
7000b57cec5SDimitry Andric     return bitc::ATTR_KIND_OPTIMIZE_NONE;
7010b57cec5SDimitry Andric   case Attribute::ReadNone:
7020b57cec5SDimitry Andric     return bitc::ATTR_KIND_READ_NONE;
7030b57cec5SDimitry Andric   case Attribute::ReadOnly:
7040b57cec5SDimitry Andric     return bitc::ATTR_KIND_READ_ONLY;
7050b57cec5SDimitry Andric   case Attribute::Returned:
7060b57cec5SDimitry Andric     return bitc::ATTR_KIND_RETURNED;
7070b57cec5SDimitry Andric   case Attribute::ReturnsTwice:
7080b57cec5SDimitry Andric     return bitc::ATTR_KIND_RETURNS_TWICE;
7090b57cec5SDimitry Andric   case Attribute::SExt:
7100b57cec5SDimitry Andric     return bitc::ATTR_KIND_S_EXT;
7110b57cec5SDimitry Andric   case Attribute::Speculatable:
7120b57cec5SDimitry Andric     return bitc::ATTR_KIND_SPECULATABLE;
7130b57cec5SDimitry Andric   case Attribute::StackAlignment:
7140b57cec5SDimitry Andric     return bitc::ATTR_KIND_STACK_ALIGNMENT;
7150b57cec5SDimitry Andric   case Attribute::StackProtect:
7160b57cec5SDimitry Andric     return bitc::ATTR_KIND_STACK_PROTECT;
7170b57cec5SDimitry Andric   case Attribute::StackProtectReq:
7180b57cec5SDimitry Andric     return bitc::ATTR_KIND_STACK_PROTECT_REQ;
7190b57cec5SDimitry Andric   case Attribute::StackProtectStrong:
7200b57cec5SDimitry Andric     return bitc::ATTR_KIND_STACK_PROTECT_STRONG;
7210b57cec5SDimitry Andric   case Attribute::SafeStack:
7220b57cec5SDimitry Andric     return bitc::ATTR_KIND_SAFESTACK;
7230b57cec5SDimitry Andric   case Attribute::ShadowCallStack:
7240b57cec5SDimitry Andric     return bitc::ATTR_KIND_SHADOWCALLSTACK;
7250b57cec5SDimitry Andric   case Attribute::StrictFP:
7260b57cec5SDimitry Andric     return bitc::ATTR_KIND_STRICT_FP;
7270b57cec5SDimitry Andric   case Attribute::StructRet:
7280b57cec5SDimitry Andric     return bitc::ATTR_KIND_STRUCT_RET;
7290b57cec5SDimitry Andric   case Attribute::SanitizeAddress:
7300b57cec5SDimitry Andric     return bitc::ATTR_KIND_SANITIZE_ADDRESS;
7310b57cec5SDimitry Andric   case Attribute::SanitizeHWAddress:
7320b57cec5SDimitry Andric     return bitc::ATTR_KIND_SANITIZE_HWADDRESS;
7330b57cec5SDimitry Andric   case Attribute::SanitizeThread:
7340b57cec5SDimitry Andric     return bitc::ATTR_KIND_SANITIZE_THREAD;
7350b57cec5SDimitry Andric   case Attribute::SanitizeMemory:
7360b57cec5SDimitry Andric     return bitc::ATTR_KIND_SANITIZE_MEMORY;
7370b57cec5SDimitry Andric   case Attribute::SpeculativeLoadHardening:
7380b57cec5SDimitry Andric     return bitc::ATTR_KIND_SPECULATIVE_LOAD_HARDENING;
7390b57cec5SDimitry Andric   case Attribute::SwiftError:
7400b57cec5SDimitry Andric     return bitc::ATTR_KIND_SWIFT_ERROR;
7410b57cec5SDimitry Andric   case Attribute::SwiftSelf:
7420b57cec5SDimitry Andric     return bitc::ATTR_KIND_SWIFT_SELF;
743*5f7ddb14SDimitry Andric   case Attribute::SwiftAsync:
744*5f7ddb14SDimitry Andric     return bitc::ATTR_KIND_SWIFT_ASYNC;
7450b57cec5SDimitry Andric   case Attribute::UWTable:
7460b57cec5SDimitry Andric     return bitc::ATTR_KIND_UW_TABLE;
747*5f7ddb14SDimitry Andric   case Attribute::VScaleRange:
748*5f7ddb14SDimitry Andric     return bitc::ATTR_KIND_VSCALE_RANGE;
7490b57cec5SDimitry Andric   case Attribute::WillReturn:
7500b57cec5SDimitry Andric     return bitc::ATTR_KIND_WILLRETURN;
7510b57cec5SDimitry Andric   case Attribute::WriteOnly:
7520b57cec5SDimitry Andric     return bitc::ATTR_KIND_WRITEONLY;
7530b57cec5SDimitry Andric   case Attribute::ZExt:
7540b57cec5SDimitry Andric     return bitc::ATTR_KIND_Z_EXT;
7550b57cec5SDimitry Andric   case Attribute::ImmArg:
7560b57cec5SDimitry Andric     return bitc::ATTR_KIND_IMMARG;
7570b57cec5SDimitry Andric   case Attribute::SanitizeMemTag:
7580b57cec5SDimitry Andric     return bitc::ATTR_KIND_SANITIZE_MEMTAG;
7595ffd83dbSDimitry Andric   case Attribute::Preallocated:
7605ffd83dbSDimitry Andric     return bitc::ATTR_KIND_PREALLOCATED;
7615ffd83dbSDimitry Andric   case Attribute::NoUndef:
7625ffd83dbSDimitry Andric     return bitc::ATTR_KIND_NOUNDEF;
763af732203SDimitry Andric   case Attribute::ByRef:
764af732203SDimitry Andric     return bitc::ATTR_KIND_BYREF;
765af732203SDimitry Andric   case Attribute::MustProgress:
766af732203SDimitry Andric     return bitc::ATTR_KIND_MUSTPROGRESS;
7670b57cec5SDimitry Andric   case Attribute::EndAttrKinds:
7680b57cec5SDimitry Andric     llvm_unreachable("Can not encode end-attribute kinds marker.");
7690b57cec5SDimitry Andric   case Attribute::None:
7700b57cec5SDimitry Andric     llvm_unreachable("Can not encode none-attribute.");
7715ffd83dbSDimitry Andric   case Attribute::EmptyKey:
7725ffd83dbSDimitry Andric   case Attribute::TombstoneKey:
7735ffd83dbSDimitry Andric     llvm_unreachable("Trying to encode EmptyKey/TombstoneKey");
7740b57cec5SDimitry Andric   }
7750b57cec5SDimitry Andric 
7760b57cec5SDimitry Andric   llvm_unreachable("Trying to encode unknown attribute");
7770b57cec5SDimitry Andric }
7780b57cec5SDimitry Andric 
writeAttributeGroupTable()7790b57cec5SDimitry Andric void ModuleBitcodeWriter::writeAttributeGroupTable() {
7800b57cec5SDimitry Andric   const std::vector<ValueEnumerator::IndexAndAttrSet> &AttrGrps =
7810b57cec5SDimitry Andric       VE.getAttributeGroups();
7820b57cec5SDimitry Andric   if (AttrGrps.empty()) return;
7830b57cec5SDimitry Andric 
7840b57cec5SDimitry Andric   Stream.EnterSubblock(bitc::PARAMATTR_GROUP_BLOCK_ID, 3);
7850b57cec5SDimitry Andric 
7860b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
7870b57cec5SDimitry Andric   for (ValueEnumerator::IndexAndAttrSet Pair : AttrGrps) {
7880b57cec5SDimitry Andric     unsigned AttrListIndex = Pair.first;
7890b57cec5SDimitry Andric     AttributeSet AS = Pair.second;
7900b57cec5SDimitry Andric     Record.push_back(VE.getAttributeGroupID(Pair));
7910b57cec5SDimitry Andric     Record.push_back(AttrListIndex);
7920b57cec5SDimitry Andric 
7930b57cec5SDimitry Andric     for (Attribute Attr : AS) {
7940b57cec5SDimitry Andric       if (Attr.isEnumAttribute()) {
7950b57cec5SDimitry Andric         Record.push_back(0);
7960b57cec5SDimitry Andric         Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
7970b57cec5SDimitry Andric       } else if (Attr.isIntAttribute()) {
7980b57cec5SDimitry Andric         Record.push_back(1);
7990b57cec5SDimitry Andric         Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
8000b57cec5SDimitry Andric         Record.push_back(Attr.getValueAsInt());
8010b57cec5SDimitry Andric       } else if (Attr.isStringAttribute()) {
8020b57cec5SDimitry Andric         StringRef Kind = Attr.getKindAsString();
8030b57cec5SDimitry Andric         StringRef Val = Attr.getValueAsString();
8040b57cec5SDimitry Andric 
8050b57cec5SDimitry Andric         Record.push_back(Val.empty() ? 3 : 4);
8060b57cec5SDimitry Andric         Record.append(Kind.begin(), Kind.end());
8070b57cec5SDimitry Andric         Record.push_back(0);
8080b57cec5SDimitry Andric         if (!Val.empty()) {
8090b57cec5SDimitry Andric           Record.append(Val.begin(), Val.end());
8100b57cec5SDimitry Andric           Record.push_back(0);
8110b57cec5SDimitry Andric         }
8120b57cec5SDimitry Andric       } else {
8130b57cec5SDimitry Andric         assert(Attr.isTypeAttribute());
8140b57cec5SDimitry Andric         Type *Ty = Attr.getValueAsType();
8150b57cec5SDimitry Andric         Record.push_back(Ty ? 6 : 5);
8160b57cec5SDimitry Andric         Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
8170b57cec5SDimitry Andric         if (Ty)
8180b57cec5SDimitry Andric           Record.push_back(VE.getTypeID(Attr.getValueAsType()));
8190b57cec5SDimitry Andric       }
8200b57cec5SDimitry Andric     }
8210b57cec5SDimitry Andric 
8220b57cec5SDimitry Andric     Stream.EmitRecord(bitc::PARAMATTR_GRP_CODE_ENTRY, Record);
8230b57cec5SDimitry Andric     Record.clear();
8240b57cec5SDimitry Andric   }
8250b57cec5SDimitry Andric 
8260b57cec5SDimitry Andric   Stream.ExitBlock();
8270b57cec5SDimitry Andric }
8280b57cec5SDimitry Andric 
writeAttributeTable()8290b57cec5SDimitry Andric void ModuleBitcodeWriter::writeAttributeTable() {
8300b57cec5SDimitry Andric   const std::vector<AttributeList> &Attrs = VE.getAttributeLists();
8310b57cec5SDimitry Andric   if (Attrs.empty()) return;
8320b57cec5SDimitry Andric 
8330b57cec5SDimitry Andric   Stream.EnterSubblock(bitc::PARAMATTR_BLOCK_ID, 3);
8340b57cec5SDimitry Andric 
8350b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
8360b57cec5SDimitry Andric   for (unsigned i = 0, e = Attrs.size(); i != e; ++i) {
8370b57cec5SDimitry Andric     AttributeList AL = Attrs[i];
8380b57cec5SDimitry Andric     for (unsigned i = AL.index_begin(), e = AL.index_end(); i != e; ++i) {
8390b57cec5SDimitry Andric       AttributeSet AS = AL.getAttributes(i);
8400b57cec5SDimitry Andric       if (AS.hasAttributes())
8410b57cec5SDimitry Andric         Record.push_back(VE.getAttributeGroupID({i, AS}));
8420b57cec5SDimitry Andric     }
8430b57cec5SDimitry Andric 
8440b57cec5SDimitry Andric     Stream.EmitRecord(bitc::PARAMATTR_CODE_ENTRY, Record);
8450b57cec5SDimitry Andric     Record.clear();
8460b57cec5SDimitry Andric   }
8470b57cec5SDimitry Andric 
8480b57cec5SDimitry Andric   Stream.ExitBlock();
8490b57cec5SDimitry Andric }
8500b57cec5SDimitry Andric 
8510b57cec5SDimitry Andric /// WriteTypeTable - Write out the type table for a module.
writeTypeTable()8520b57cec5SDimitry Andric void ModuleBitcodeWriter::writeTypeTable() {
8530b57cec5SDimitry Andric   const ValueEnumerator::TypeList &TypeList = VE.getTypes();
8540b57cec5SDimitry Andric 
8550b57cec5SDimitry Andric   Stream.EnterSubblock(bitc::TYPE_BLOCK_ID_NEW, 4 /*count from # abbrevs */);
8560b57cec5SDimitry Andric   SmallVector<uint64_t, 64> TypeVals;
8570b57cec5SDimitry Andric 
8580b57cec5SDimitry Andric   uint64_t NumBits = VE.computeBitsRequiredForTypeIndicies();
8590b57cec5SDimitry Andric 
8600b57cec5SDimitry Andric   // Abbrev for TYPE_CODE_POINTER.
8610b57cec5SDimitry Andric   auto Abbv = std::make_shared<BitCodeAbbrev>();
8620b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_POINTER));
8630b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
8640b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(0));  // Addrspace = 0
8650b57cec5SDimitry Andric   unsigned PtrAbbrev = Stream.EmitAbbrev(std::move(Abbv));
8660b57cec5SDimitry Andric 
867*5f7ddb14SDimitry Andric   // Abbrev for TYPE_CODE_OPAQUE_POINTER.
868*5f7ddb14SDimitry Andric   Abbv = std::make_shared<BitCodeAbbrev>();
869*5f7ddb14SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_OPAQUE_POINTER));
870*5f7ddb14SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(0)); // Addrspace = 0
871*5f7ddb14SDimitry Andric   unsigned OpaquePtrAbbrev = Stream.EmitAbbrev(std::move(Abbv));
872*5f7ddb14SDimitry Andric 
8730b57cec5SDimitry Andric   // Abbrev for TYPE_CODE_FUNCTION.
8740b57cec5SDimitry Andric   Abbv = std::make_shared<BitCodeAbbrev>();
8750b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_FUNCTION));
8760b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));  // isvararg
8770b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
8780b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
8790b57cec5SDimitry Andric   unsigned FunctionAbbrev = Stream.EmitAbbrev(std::move(Abbv));
8800b57cec5SDimitry Andric 
8810b57cec5SDimitry Andric   // Abbrev for TYPE_CODE_STRUCT_ANON.
8820b57cec5SDimitry Andric   Abbv = std::make_shared<BitCodeAbbrev>();
8830b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_ANON));
8840b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));  // ispacked
8850b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
8860b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
8870b57cec5SDimitry Andric   unsigned StructAnonAbbrev = Stream.EmitAbbrev(std::move(Abbv));
8880b57cec5SDimitry Andric 
8890b57cec5SDimitry Andric   // Abbrev for TYPE_CODE_STRUCT_NAME.
8900b57cec5SDimitry Andric   Abbv = std::make_shared<BitCodeAbbrev>();
8910b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAME));
8920b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
8930b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
8940b57cec5SDimitry Andric   unsigned StructNameAbbrev = Stream.EmitAbbrev(std::move(Abbv));
8950b57cec5SDimitry Andric 
8960b57cec5SDimitry Andric   // Abbrev for TYPE_CODE_STRUCT_NAMED.
8970b57cec5SDimitry Andric   Abbv = std::make_shared<BitCodeAbbrev>();
8980b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAMED));
8990b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));  // ispacked
9000b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
9010b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
9020b57cec5SDimitry Andric   unsigned StructNamedAbbrev = Stream.EmitAbbrev(std::move(Abbv));
9030b57cec5SDimitry Andric 
9040b57cec5SDimitry Andric   // Abbrev for TYPE_CODE_ARRAY.
9050b57cec5SDimitry Andric   Abbv = std::make_shared<BitCodeAbbrev>();
9060b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_ARRAY));
9070b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // size
9080b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
9090b57cec5SDimitry Andric   unsigned ArrayAbbrev = Stream.EmitAbbrev(std::move(Abbv));
9100b57cec5SDimitry Andric 
9110b57cec5SDimitry Andric   // Emit an entry count so the reader can reserve space.
9120b57cec5SDimitry Andric   TypeVals.push_back(TypeList.size());
9130b57cec5SDimitry Andric   Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals);
9140b57cec5SDimitry Andric   TypeVals.clear();
9150b57cec5SDimitry Andric 
9160b57cec5SDimitry Andric   // Loop over all of the types, emitting each in turn.
9170b57cec5SDimitry Andric   for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
9180b57cec5SDimitry Andric     Type *T = TypeList[i];
9190b57cec5SDimitry Andric     int AbbrevToUse = 0;
9200b57cec5SDimitry Andric     unsigned Code = 0;
9210b57cec5SDimitry Andric 
9220b57cec5SDimitry Andric     switch (T->getTypeID()) {
9230b57cec5SDimitry Andric     case Type::VoidTyID:      Code = bitc::TYPE_CODE_VOID;      break;
9240b57cec5SDimitry Andric     case Type::HalfTyID:      Code = bitc::TYPE_CODE_HALF;      break;
9255ffd83dbSDimitry Andric     case Type::BFloatTyID:    Code = bitc::TYPE_CODE_BFLOAT;    break;
9260b57cec5SDimitry Andric     case Type::FloatTyID:     Code = bitc::TYPE_CODE_FLOAT;     break;
9270b57cec5SDimitry Andric     case Type::DoubleTyID:    Code = bitc::TYPE_CODE_DOUBLE;    break;
9280b57cec5SDimitry Andric     case Type::X86_FP80TyID:  Code = bitc::TYPE_CODE_X86_FP80;  break;
9290b57cec5SDimitry Andric     case Type::FP128TyID:     Code = bitc::TYPE_CODE_FP128;     break;
9300b57cec5SDimitry Andric     case Type::PPC_FP128TyID: Code = bitc::TYPE_CODE_PPC_FP128; break;
9310b57cec5SDimitry Andric     case Type::LabelTyID:     Code = bitc::TYPE_CODE_LABEL;     break;
9320b57cec5SDimitry Andric     case Type::MetadataTyID:  Code = bitc::TYPE_CODE_METADATA;  break;
9330b57cec5SDimitry Andric     case Type::X86_MMXTyID:   Code = bitc::TYPE_CODE_X86_MMX;   break;
934af732203SDimitry Andric     case Type::X86_AMXTyID:   Code = bitc::TYPE_CODE_X86_AMX;   break;
9350b57cec5SDimitry Andric     case Type::TokenTyID:     Code = bitc::TYPE_CODE_TOKEN;     break;
9360b57cec5SDimitry Andric     case Type::IntegerTyID:
9370b57cec5SDimitry Andric       // INTEGER: [width]
9380b57cec5SDimitry Andric       Code = bitc::TYPE_CODE_INTEGER;
9390b57cec5SDimitry Andric       TypeVals.push_back(cast<IntegerType>(T)->getBitWidth());
9400b57cec5SDimitry Andric       break;
9410b57cec5SDimitry Andric     case Type::PointerTyID: {
9420b57cec5SDimitry Andric       PointerType *PTy = cast<PointerType>(T);
943*5f7ddb14SDimitry Andric       unsigned AddressSpace = PTy->getAddressSpace();
944*5f7ddb14SDimitry Andric       if (PTy->isOpaque()) {
945*5f7ddb14SDimitry Andric         // OPAQUE_POINTER: [address space]
946*5f7ddb14SDimitry Andric         Code = bitc::TYPE_CODE_OPAQUE_POINTER;
947*5f7ddb14SDimitry Andric         TypeVals.push_back(AddressSpace);
948*5f7ddb14SDimitry Andric         if (AddressSpace == 0)
949*5f7ddb14SDimitry Andric           AbbrevToUse = OpaquePtrAbbrev;
950*5f7ddb14SDimitry Andric       } else {
9510b57cec5SDimitry Andric         // POINTER: [pointee type, address space]
9520b57cec5SDimitry Andric         Code = bitc::TYPE_CODE_POINTER;
9530b57cec5SDimitry Andric         TypeVals.push_back(VE.getTypeID(PTy->getElementType()));
9540b57cec5SDimitry Andric         TypeVals.push_back(AddressSpace);
955*5f7ddb14SDimitry Andric         if (AddressSpace == 0)
956*5f7ddb14SDimitry Andric           AbbrevToUse = PtrAbbrev;
957*5f7ddb14SDimitry Andric       }
9580b57cec5SDimitry Andric       break;
9590b57cec5SDimitry Andric     }
9600b57cec5SDimitry Andric     case Type::FunctionTyID: {
9610b57cec5SDimitry Andric       FunctionType *FT = cast<FunctionType>(T);
9620b57cec5SDimitry Andric       // FUNCTION: [isvararg, retty, paramty x N]
9630b57cec5SDimitry Andric       Code = bitc::TYPE_CODE_FUNCTION;
9640b57cec5SDimitry Andric       TypeVals.push_back(FT->isVarArg());
9650b57cec5SDimitry Andric       TypeVals.push_back(VE.getTypeID(FT->getReturnType()));
9660b57cec5SDimitry Andric       for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
9670b57cec5SDimitry Andric         TypeVals.push_back(VE.getTypeID(FT->getParamType(i)));
9680b57cec5SDimitry Andric       AbbrevToUse = FunctionAbbrev;
9690b57cec5SDimitry Andric       break;
9700b57cec5SDimitry Andric     }
9710b57cec5SDimitry Andric     case Type::StructTyID: {
9720b57cec5SDimitry Andric       StructType *ST = cast<StructType>(T);
9730b57cec5SDimitry Andric       // STRUCT: [ispacked, eltty x N]
9740b57cec5SDimitry Andric       TypeVals.push_back(ST->isPacked());
9750b57cec5SDimitry Andric       // Output all of the element types.
9760b57cec5SDimitry Andric       for (StructType::element_iterator I = ST->element_begin(),
9770b57cec5SDimitry Andric            E = ST->element_end(); I != E; ++I)
9780b57cec5SDimitry Andric         TypeVals.push_back(VE.getTypeID(*I));
9790b57cec5SDimitry Andric 
9800b57cec5SDimitry Andric       if (ST->isLiteral()) {
9810b57cec5SDimitry Andric         Code = bitc::TYPE_CODE_STRUCT_ANON;
9820b57cec5SDimitry Andric         AbbrevToUse = StructAnonAbbrev;
9830b57cec5SDimitry Andric       } else {
9840b57cec5SDimitry Andric         if (ST->isOpaque()) {
9850b57cec5SDimitry Andric           Code = bitc::TYPE_CODE_OPAQUE;
9860b57cec5SDimitry Andric         } else {
9870b57cec5SDimitry Andric           Code = bitc::TYPE_CODE_STRUCT_NAMED;
9880b57cec5SDimitry Andric           AbbrevToUse = StructNamedAbbrev;
9890b57cec5SDimitry Andric         }
9900b57cec5SDimitry Andric 
9910b57cec5SDimitry Andric         // Emit the name if it is present.
9920b57cec5SDimitry Andric         if (!ST->getName().empty())
9930b57cec5SDimitry Andric           writeStringRecord(Stream, bitc::TYPE_CODE_STRUCT_NAME, ST->getName(),
9940b57cec5SDimitry Andric                             StructNameAbbrev);
9950b57cec5SDimitry Andric       }
9960b57cec5SDimitry Andric       break;
9970b57cec5SDimitry Andric     }
9980b57cec5SDimitry Andric     case Type::ArrayTyID: {
9990b57cec5SDimitry Andric       ArrayType *AT = cast<ArrayType>(T);
10000b57cec5SDimitry Andric       // ARRAY: [numelts, eltty]
10010b57cec5SDimitry Andric       Code = bitc::TYPE_CODE_ARRAY;
10020b57cec5SDimitry Andric       TypeVals.push_back(AT->getNumElements());
10030b57cec5SDimitry Andric       TypeVals.push_back(VE.getTypeID(AT->getElementType()));
10040b57cec5SDimitry Andric       AbbrevToUse = ArrayAbbrev;
10050b57cec5SDimitry Andric       break;
10060b57cec5SDimitry Andric     }
10075ffd83dbSDimitry Andric     case Type::FixedVectorTyID:
10085ffd83dbSDimitry Andric     case Type::ScalableVectorTyID: {
10090b57cec5SDimitry Andric       VectorType *VT = cast<VectorType>(T);
10100b57cec5SDimitry Andric       // VECTOR [numelts, eltty] or
10110b57cec5SDimitry Andric       //        [numelts, eltty, scalable]
10120b57cec5SDimitry Andric       Code = bitc::TYPE_CODE_VECTOR;
1013af732203SDimitry Andric       TypeVals.push_back(VT->getElementCount().getKnownMinValue());
10140b57cec5SDimitry Andric       TypeVals.push_back(VE.getTypeID(VT->getElementType()));
10155ffd83dbSDimitry Andric       if (isa<ScalableVectorType>(VT))
10165ffd83dbSDimitry Andric         TypeVals.push_back(true);
10170b57cec5SDimitry Andric       break;
10180b57cec5SDimitry Andric     }
10190b57cec5SDimitry Andric     }
10200b57cec5SDimitry Andric 
10210b57cec5SDimitry Andric     // Emit the finished record.
10220b57cec5SDimitry Andric     Stream.EmitRecord(Code, TypeVals, AbbrevToUse);
10230b57cec5SDimitry Andric     TypeVals.clear();
10240b57cec5SDimitry Andric   }
10250b57cec5SDimitry Andric 
10260b57cec5SDimitry Andric   Stream.ExitBlock();
10270b57cec5SDimitry Andric }
10280b57cec5SDimitry Andric 
getEncodedLinkage(const GlobalValue::LinkageTypes Linkage)10290b57cec5SDimitry Andric static unsigned getEncodedLinkage(const GlobalValue::LinkageTypes Linkage) {
10300b57cec5SDimitry Andric   switch (Linkage) {
10310b57cec5SDimitry Andric   case GlobalValue::ExternalLinkage:
10320b57cec5SDimitry Andric     return 0;
10330b57cec5SDimitry Andric   case GlobalValue::WeakAnyLinkage:
10340b57cec5SDimitry Andric     return 16;
10350b57cec5SDimitry Andric   case GlobalValue::AppendingLinkage:
10360b57cec5SDimitry Andric     return 2;
10370b57cec5SDimitry Andric   case GlobalValue::InternalLinkage:
10380b57cec5SDimitry Andric     return 3;
10390b57cec5SDimitry Andric   case GlobalValue::LinkOnceAnyLinkage:
10400b57cec5SDimitry Andric     return 18;
10410b57cec5SDimitry Andric   case GlobalValue::ExternalWeakLinkage:
10420b57cec5SDimitry Andric     return 7;
10430b57cec5SDimitry Andric   case GlobalValue::CommonLinkage:
10440b57cec5SDimitry Andric     return 8;
10450b57cec5SDimitry Andric   case GlobalValue::PrivateLinkage:
10460b57cec5SDimitry Andric     return 9;
10470b57cec5SDimitry Andric   case GlobalValue::WeakODRLinkage:
10480b57cec5SDimitry Andric     return 17;
10490b57cec5SDimitry Andric   case GlobalValue::LinkOnceODRLinkage:
10500b57cec5SDimitry Andric     return 19;
10510b57cec5SDimitry Andric   case GlobalValue::AvailableExternallyLinkage:
10520b57cec5SDimitry Andric     return 12;
10530b57cec5SDimitry Andric   }
10540b57cec5SDimitry Andric   llvm_unreachable("Invalid linkage");
10550b57cec5SDimitry Andric }
10560b57cec5SDimitry Andric 
getEncodedLinkage(const GlobalValue & GV)10570b57cec5SDimitry Andric static unsigned getEncodedLinkage(const GlobalValue &GV) {
10580b57cec5SDimitry Andric   return getEncodedLinkage(GV.getLinkage());
10590b57cec5SDimitry Andric }
10600b57cec5SDimitry Andric 
getEncodedFFlags(FunctionSummary::FFlags Flags)10610b57cec5SDimitry Andric static uint64_t getEncodedFFlags(FunctionSummary::FFlags Flags) {
10620b57cec5SDimitry Andric   uint64_t RawFlags = 0;
10630b57cec5SDimitry Andric   RawFlags |= Flags.ReadNone;
10640b57cec5SDimitry Andric   RawFlags |= (Flags.ReadOnly << 1);
10650b57cec5SDimitry Andric   RawFlags |= (Flags.NoRecurse << 2);
10660b57cec5SDimitry Andric   RawFlags |= (Flags.ReturnDoesNotAlias << 3);
10670b57cec5SDimitry Andric   RawFlags |= (Flags.NoInline << 4);
1068480093f4SDimitry Andric   RawFlags |= (Flags.AlwaysInline << 5);
10690b57cec5SDimitry Andric   return RawFlags;
10700b57cec5SDimitry Andric }
10710b57cec5SDimitry Andric 
1072*5f7ddb14SDimitry Andric // Decode the flags for GlobalValue in the summary. See getDecodedGVSummaryFlags
1073*5f7ddb14SDimitry Andric // in BitcodeReader.cpp.
getEncodedGVSummaryFlags(GlobalValueSummary::GVFlags Flags)10740b57cec5SDimitry Andric static uint64_t getEncodedGVSummaryFlags(GlobalValueSummary::GVFlags Flags) {
10750b57cec5SDimitry Andric   uint64_t RawFlags = 0;
10760b57cec5SDimitry Andric 
10770b57cec5SDimitry Andric   RawFlags |= Flags.NotEligibleToImport; // bool
10780b57cec5SDimitry Andric   RawFlags |= (Flags.Live << 1);
10790b57cec5SDimitry Andric   RawFlags |= (Flags.DSOLocal << 2);
10800b57cec5SDimitry Andric   RawFlags |= (Flags.CanAutoHide << 3);
10810b57cec5SDimitry Andric 
10820b57cec5SDimitry Andric   // Linkage don't need to be remapped at that time for the summary. Any future
10830b57cec5SDimitry Andric   // change to the getEncodedLinkage() function will need to be taken into
10840b57cec5SDimitry Andric   // account here as well.
10850b57cec5SDimitry Andric   RawFlags = (RawFlags << 4) | Flags.Linkage; // 4 bits
10860b57cec5SDimitry Andric 
1087*5f7ddb14SDimitry Andric   RawFlags |= (Flags.Visibility << 8); // 2 bits
1088*5f7ddb14SDimitry Andric 
10890b57cec5SDimitry Andric   return RawFlags;
10900b57cec5SDimitry Andric }
10910b57cec5SDimitry Andric 
getEncodedGVarFlags(GlobalVarSummary::GVarFlags Flags)10920b57cec5SDimitry Andric static uint64_t getEncodedGVarFlags(GlobalVarSummary::GVarFlags Flags) {
10935ffd83dbSDimitry Andric   uint64_t RawFlags = Flags.MaybeReadOnly | (Flags.MaybeWriteOnly << 1) |
10945ffd83dbSDimitry Andric                       (Flags.Constant << 2) | Flags.VCallVisibility << 3;
10950b57cec5SDimitry Andric   return RawFlags;
10960b57cec5SDimitry Andric }
10970b57cec5SDimitry Andric 
getEncodedVisibility(const GlobalValue & GV)10980b57cec5SDimitry Andric static unsigned getEncodedVisibility(const GlobalValue &GV) {
10990b57cec5SDimitry Andric   switch (GV.getVisibility()) {
11000b57cec5SDimitry Andric   case GlobalValue::DefaultVisibility:   return 0;
11010b57cec5SDimitry Andric   case GlobalValue::HiddenVisibility:    return 1;
11020b57cec5SDimitry Andric   case GlobalValue::ProtectedVisibility: return 2;
11030b57cec5SDimitry Andric   }
11040b57cec5SDimitry Andric   llvm_unreachable("Invalid visibility");
11050b57cec5SDimitry Andric }
11060b57cec5SDimitry Andric 
getEncodedDLLStorageClass(const GlobalValue & GV)11070b57cec5SDimitry Andric static unsigned getEncodedDLLStorageClass(const GlobalValue &GV) {
11080b57cec5SDimitry Andric   switch (GV.getDLLStorageClass()) {
11090b57cec5SDimitry Andric   case GlobalValue::DefaultStorageClass:   return 0;
11100b57cec5SDimitry Andric   case GlobalValue::DLLImportStorageClass: return 1;
11110b57cec5SDimitry Andric   case GlobalValue::DLLExportStorageClass: return 2;
11120b57cec5SDimitry Andric   }
11130b57cec5SDimitry Andric   llvm_unreachable("Invalid DLL storage class");
11140b57cec5SDimitry Andric }
11150b57cec5SDimitry Andric 
getEncodedThreadLocalMode(const GlobalValue & GV)11160b57cec5SDimitry Andric static unsigned getEncodedThreadLocalMode(const GlobalValue &GV) {
11170b57cec5SDimitry Andric   switch (GV.getThreadLocalMode()) {
11180b57cec5SDimitry Andric     case GlobalVariable::NotThreadLocal:         return 0;
11190b57cec5SDimitry Andric     case GlobalVariable::GeneralDynamicTLSModel: return 1;
11200b57cec5SDimitry Andric     case GlobalVariable::LocalDynamicTLSModel:   return 2;
11210b57cec5SDimitry Andric     case GlobalVariable::InitialExecTLSModel:    return 3;
11220b57cec5SDimitry Andric     case GlobalVariable::LocalExecTLSModel:      return 4;
11230b57cec5SDimitry Andric   }
11240b57cec5SDimitry Andric   llvm_unreachable("Invalid TLS model");
11250b57cec5SDimitry Andric }
11260b57cec5SDimitry Andric 
getEncodedComdatSelectionKind(const Comdat & C)11270b57cec5SDimitry Andric static unsigned getEncodedComdatSelectionKind(const Comdat &C) {
11280b57cec5SDimitry Andric   switch (C.getSelectionKind()) {
11290b57cec5SDimitry Andric   case Comdat::Any:
11300b57cec5SDimitry Andric     return bitc::COMDAT_SELECTION_KIND_ANY;
11310b57cec5SDimitry Andric   case Comdat::ExactMatch:
11320b57cec5SDimitry Andric     return bitc::COMDAT_SELECTION_KIND_EXACT_MATCH;
11330b57cec5SDimitry Andric   case Comdat::Largest:
11340b57cec5SDimitry Andric     return bitc::COMDAT_SELECTION_KIND_LARGEST;
1135*5f7ddb14SDimitry Andric   case Comdat::NoDeduplicate:
11360b57cec5SDimitry Andric     return bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES;
11370b57cec5SDimitry Andric   case Comdat::SameSize:
11380b57cec5SDimitry Andric     return bitc::COMDAT_SELECTION_KIND_SAME_SIZE;
11390b57cec5SDimitry Andric   }
11400b57cec5SDimitry Andric   llvm_unreachable("Invalid selection kind");
11410b57cec5SDimitry Andric }
11420b57cec5SDimitry Andric 
getEncodedUnnamedAddr(const GlobalValue & GV)11430b57cec5SDimitry Andric static unsigned getEncodedUnnamedAddr(const GlobalValue &GV) {
11440b57cec5SDimitry Andric   switch (GV.getUnnamedAddr()) {
11450b57cec5SDimitry Andric   case GlobalValue::UnnamedAddr::None:   return 0;
11460b57cec5SDimitry Andric   case GlobalValue::UnnamedAddr::Local:  return 2;
11470b57cec5SDimitry Andric   case GlobalValue::UnnamedAddr::Global: return 1;
11480b57cec5SDimitry Andric   }
11490b57cec5SDimitry Andric   llvm_unreachable("Invalid unnamed_addr");
11500b57cec5SDimitry Andric }
11510b57cec5SDimitry Andric 
addToStrtab(StringRef Str)11520b57cec5SDimitry Andric size_t ModuleBitcodeWriter::addToStrtab(StringRef Str) {
11530b57cec5SDimitry Andric   if (GenerateHash)
11540b57cec5SDimitry Andric     Hasher.update(Str);
11550b57cec5SDimitry Andric   return StrtabBuilder.add(Str);
11560b57cec5SDimitry Andric }
11570b57cec5SDimitry Andric 
writeComdats()11580b57cec5SDimitry Andric void ModuleBitcodeWriter::writeComdats() {
11590b57cec5SDimitry Andric   SmallVector<unsigned, 64> Vals;
11600b57cec5SDimitry Andric   for (const Comdat *C : VE.getComdats()) {
11610b57cec5SDimitry Andric     // COMDAT: [strtab offset, strtab size, selection_kind]
11620b57cec5SDimitry Andric     Vals.push_back(addToStrtab(C->getName()));
11630b57cec5SDimitry Andric     Vals.push_back(C->getName().size());
11640b57cec5SDimitry Andric     Vals.push_back(getEncodedComdatSelectionKind(*C));
11650b57cec5SDimitry Andric     Stream.EmitRecord(bitc::MODULE_CODE_COMDAT, Vals, /*AbbrevToUse=*/0);
11660b57cec5SDimitry Andric     Vals.clear();
11670b57cec5SDimitry Andric   }
11680b57cec5SDimitry Andric }
11690b57cec5SDimitry Andric 
11700b57cec5SDimitry Andric /// Write a record that will eventually hold the word offset of the
11710b57cec5SDimitry Andric /// module-level VST. For now the offset is 0, which will be backpatched
11720b57cec5SDimitry Andric /// after the real VST is written. Saves the bit offset to backpatch.
writeValueSymbolTableForwardDecl()11730b57cec5SDimitry Andric void ModuleBitcodeWriter::writeValueSymbolTableForwardDecl() {
11740b57cec5SDimitry Andric   // Write a placeholder value in for the offset of the real VST,
11750b57cec5SDimitry Andric   // which is written after the function blocks so that it can include
11760b57cec5SDimitry Andric   // the offset of each function. The placeholder offset will be
11770b57cec5SDimitry Andric   // updated when the real VST is written.
11780b57cec5SDimitry Andric   auto Abbv = std::make_shared<BitCodeAbbrev>();
11790b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_VSTOFFSET));
11800b57cec5SDimitry Andric   // Blocks are 32-bit aligned, so we can use a 32-bit word offset to
11810b57cec5SDimitry Andric   // hold the real VST offset. Must use fixed instead of VBR as we don't
11820b57cec5SDimitry Andric   // know how many VBR chunks to reserve ahead of time.
11830b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
11840b57cec5SDimitry Andric   unsigned VSTOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbv));
11850b57cec5SDimitry Andric 
11860b57cec5SDimitry Andric   // Emit the placeholder
11870b57cec5SDimitry Andric   uint64_t Vals[] = {bitc::MODULE_CODE_VSTOFFSET, 0};
11880b57cec5SDimitry Andric   Stream.EmitRecordWithAbbrev(VSTOffsetAbbrev, Vals);
11890b57cec5SDimitry Andric 
11900b57cec5SDimitry Andric   // Compute and save the bit offset to the placeholder, which will be
11910b57cec5SDimitry Andric   // patched when the real VST is written. We can simply subtract the 32-bit
11920b57cec5SDimitry Andric   // fixed size from the current bit number to get the location to backpatch.
11930b57cec5SDimitry Andric   VSTOffsetPlaceholder = Stream.GetCurrentBitNo() - 32;
11940b57cec5SDimitry Andric }
11950b57cec5SDimitry Andric 
11960b57cec5SDimitry Andric enum StringEncoding { SE_Char6, SE_Fixed7, SE_Fixed8 };
11970b57cec5SDimitry Andric 
11980b57cec5SDimitry Andric /// Determine the encoding to use for the given string name and length.
getStringEncoding(StringRef Str)11990b57cec5SDimitry Andric static StringEncoding getStringEncoding(StringRef Str) {
12000b57cec5SDimitry Andric   bool isChar6 = true;
12010b57cec5SDimitry Andric   for (char C : Str) {
12020b57cec5SDimitry Andric     if (isChar6)
12030b57cec5SDimitry Andric       isChar6 = BitCodeAbbrevOp::isChar6(C);
12040b57cec5SDimitry Andric     if ((unsigned char)C & 128)
12050b57cec5SDimitry Andric       // don't bother scanning the rest.
12060b57cec5SDimitry Andric       return SE_Fixed8;
12070b57cec5SDimitry Andric   }
12080b57cec5SDimitry Andric   if (isChar6)
12090b57cec5SDimitry Andric     return SE_Char6;
12100b57cec5SDimitry Andric   return SE_Fixed7;
12110b57cec5SDimitry Andric }
12120b57cec5SDimitry Andric 
12130b57cec5SDimitry Andric /// Emit top-level description of module, including target triple, inline asm,
12140b57cec5SDimitry Andric /// descriptors for global variables, and function prototype info.
12150b57cec5SDimitry Andric /// Returns the bit offset to backpatch with the location of the real VST.
writeModuleInfo()12160b57cec5SDimitry Andric void ModuleBitcodeWriter::writeModuleInfo() {
12170b57cec5SDimitry Andric   // Emit various pieces of data attached to a module.
12180b57cec5SDimitry Andric   if (!M.getTargetTriple().empty())
12190b57cec5SDimitry Andric     writeStringRecord(Stream, bitc::MODULE_CODE_TRIPLE, M.getTargetTriple(),
12200b57cec5SDimitry Andric                       0 /*TODO*/);
12210b57cec5SDimitry Andric   const std::string &DL = M.getDataLayoutStr();
12220b57cec5SDimitry Andric   if (!DL.empty())
12230b57cec5SDimitry Andric     writeStringRecord(Stream, bitc::MODULE_CODE_DATALAYOUT, DL, 0 /*TODO*/);
12240b57cec5SDimitry Andric   if (!M.getModuleInlineAsm().empty())
12250b57cec5SDimitry Andric     writeStringRecord(Stream, bitc::MODULE_CODE_ASM, M.getModuleInlineAsm(),
12260b57cec5SDimitry Andric                       0 /*TODO*/);
12270b57cec5SDimitry Andric 
12280b57cec5SDimitry Andric   // Emit information about sections and GC, computing how many there are. Also
12290b57cec5SDimitry Andric   // compute the maximum alignment value.
12300b57cec5SDimitry Andric   std::map<std::string, unsigned> SectionMap;
12310b57cec5SDimitry Andric   std::map<std::string, unsigned> GCMap;
1232af732203SDimitry Andric   MaybeAlign MaxAlignment;
12330b57cec5SDimitry Andric   unsigned MaxGlobalType = 0;
1234af732203SDimitry Andric   const auto UpdateMaxAlignment = [&MaxAlignment](const MaybeAlign A) {
1235af732203SDimitry Andric     if (A)
1236af732203SDimitry Andric       MaxAlignment = !MaxAlignment ? *A : std::max(*MaxAlignment, *A);
1237af732203SDimitry Andric   };
12385ffd83dbSDimitry Andric   for (const GlobalVariable &GV : M.globals()) {
1239af732203SDimitry Andric     UpdateMaxAlignment(GV.getAlign());
12400b57cec5SDimitry Andric     MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV.getValueType()));
12410b57cec5SDimitry Andric     if (GV.hasSection()) {
12420b57cec5SDimitry Andric       // Give section names unique ID's.
12435ffd83dbSDimitry Andric       unsigned &Entry = SectionMap[std::string(GV.getSection())];
12440b57cec5SDimitry Andric       if (!Entry) {
12450b57cec5SDimitry Andric         writeStringRecord(Stream, bitc::MODULE_CODE_SECTIONNAME, GV.getSection(),
12460b57cec5SDimitry Andric                           0 /*TODO*/);
12470b57cec5SDimitry Andric         Entry = SectionMap.size();
12480b57cec5SDimitry Andric       }
12490b57cec5SDimitry Andric     }
12500b57cec5SDimitry Andric   }
12510b57cec5SDimitry Andric   for (const Function &F : M) {
1252af732203SDimitry Andric     UpdateMaxAlignment(F.getAlign());
12530b57cec5SDimitry Andric     if (F.hasSection()) {
12540b57cec5SDimitry Andric       // Give section names unique ID's.
12555ffd83dbSDimitry Andric       unsigned &Entry = SectionMap[std::string(F.getSection())];
12560b57cec5SDimitry Andric       if (!Entry) {
12570b57cec5SDimitry Andric         writeStringRecord(Stream, bitc::MODULE_CODE_SECTIONNAME, F.getSection(),
12580b57cec5SDimitry Andric                           0 /*TODO*/);
12590b57cec5SDimitry Andric         Entry = SectionMap.size();
12600b57cec5SDimitry Andric       }
12610b57cec5SDimitry Andric     }
12620b57cec5SDimitry Andric     if (F.hasGC()) {
12630b57cec5SDimitry Andric       // Same for GC names.
12640b57cec5SDimitry Andric       unsigned &Entry = GCMap[F.getGC()];
12650b57cec5SDimitry Andric       if (!Entry) {
12660b57cec5SDimitry Andric         writeStringRecord(Stream, bitc::MODULE_CODE_GCNAME, F.getGC(),
12670b57cec5SDimitry Andric                           0 /*TODO*/);
12680b57cec5SDimitry Andric         Entry = GCMap.size();
12690b57cec5SDimitry Andric       }
12700b57cec5SDimitry Andric     }
12710b57cec5SDimitry Andric   }
12720b57cec5SDimitry Andric 
12730b57cec5SDimitry Andric   // Emit abbrev for globals, now that we know # sections and max alignment.
12740b57cec5SDimitry Andric   unsigned SimpleGVarAbbrev = 0;
12750b57cec5SDimitry Andric   if (!M.global_empty()) {
12760b57cec5SDimitry Andric     // Add an abbrev for common globals with no visibility or thread localness.
12770b57cec5SDimitry Andric     auto Abbv = std::make_shared<BitCodeAbbrev>();
12780b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GLOBALVAR));
12790b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
12800b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
12810b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
12820b57cec5SDimitry Andric                               Log2_32_Ceil(MaxGlobalType+1)));
12830b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // AddrSpace << 2
12840b57cec5SDimitry Andric                                                            //| explicitType << 1
12850b57cec5SDimitry Andric                                                            //| constant
12860b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // Initializer.
12870b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5)); // Linkage.
1288af732203SDimitry Andric     if (!MaxAlignment)                                     // Alignment.
12890b57cec5SDimitry Andric       Abbv->Add(BitCodeAbbrevOp(0));
12900b57cec5SDimitry Andric     else {
1291af732203SDimitry Andric       unsigned MaxEncAlignment = getEncodedAlign(MaxAlignment);
12920b57cec5SDimitry Andric       Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
12930b57cec5SDimitry Andric                                Log2_32_Ceil(MaxEncAlignment+1)));
12940b57cec5SDimitry Andric     }
12950b57cec5SDimitry Andric     if (SectionMap.empty())                                    // Section.
12960b57cec5SDimitry Andric       Abbv->Add(BitCodeAbbrevOp(0));
12970b57cec5SDimitry Andric     else
12980b57cec5SDimitry Andric       Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
12990b57cec5SDimitry Andric                                Log2_32_Ceil(SectionMap.size()+1)));
13000b57cec5SDimitry Andric     // Don't bother emitting vis + thread local.
13010b57cec5SDimitry Andric     SimpleGVarAbbrev = Stream.EmitAbbrev(std::move(Abbv));
13020b57cec5SDimitry Andric   }
13030b57cec5SDimitry Andric 
13040b57cec5SDimitry Andric   SmallVector<unsigned, 64> Vals;
13050b57cec5SDimitry Andric   // Emit the module's source file name.
13060b57cec5SDimitry Andric   {
13070b57cec5SDimitry Andric     StringEncoding Bits = getStringEncoding(M.getSourceFileName());
13080b57cec5SDimitry Andric     BitCodeAbbrevOp AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8);
13090b57cec5SDimitry Andric     if (Bits == SE_Char6)
13100b57cec5SDimitry Andric       AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Char6);
13110b57cec5SDimitry Andric     else if (Bits == SE_Fixed7)
13120b57cec5SDimitry Andric       AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7);
13130b57cec5SDimitry Andric 
13140b57cec5SDimitry Andric     // MODULE_CODE_SOURCE_FILENAME: [namechar x N]
13150b57cec5SDimitry Andric     auto Abbv = std::make_shared<BitCodeAbbrev>();
13160b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_SOURCE_FILENAME));
13170b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
13180b57cec5SDimitry Andric     Abbv->Add(AbbrevOpToUse);
13190b57cec5SDimitry Andric     unsigned FilenameAbbrev = Stream.EmitAbbrev(std::move(Abbv));
13200b57cec5SDimitry Andric 
13210b57cec5SDimitry Andric     for (const auto P : M.getSourceFileName())
13220b57cec5SDimitry Andric       Vals.push_back((unsigned char)P);
13230b57cec5SDimitry Andric 
13240b57cec5SDimitry Andric     // Emit the finished record.
13250b57cec5SDimitry Andric     Stream.EmitRecord(bitc::MODULE_CODE_SOURCE_FILENAME, Vals, FilenameAbbrev);
13260b57cec5SDimitry Andric     Vals.clear();
13270b57cec5SDimitry Andric   }
13280b57cec5SDimitry Andric 
13290b57cec5SDimitry Andric   // Emit the global variable information.
13300b57cec5SDimitry Andric   for (const GlobalVariable &GV : M.globals()) {
13310b57cec5SDimitry Andric     unsigned AbbrevToUse = 0;
13320b57cec5SDimitry Andric 
13330b57cec5SDimitry Andric     // GLOBALVAR: [strtab offset, strtab size, type, isconst, initid,
13340b57cec5SDimitry Andric     //             linkage, alignment, section, visibility, threadlocal,
13350b57cec5SDimitry Andric     //             unnamed_addr, externally_initialized, dllstorageclass,
13360b57cec5SDimitry Andric     //             comdat, attributes, DSO_Local]
13370b57cec5SDimitry Andric     Vals.push_back(addToStrtab(GV.getName()));
13380b57cec5SDimitry Andric     Vals.push_back(GV.getName().size());
13390b57cec5SDimitry Andric     Vals.push_back(VE.getTypeID(GV.getValueType()));
13400b57cec5SDimitry Andric     Vals.push_back(GV.getType()->getAddressSpace() << 2 | 2 | GV.isConstant());
13410b57cec5SDimitry Andric     Vals.push_back(GV.isDeclaration() ? 0 :
13420b57cec5SDimitry Andric                    (VE.getValueID(GV.getInitializer()) + 1));
13430b57cec5SDimitry Andric     Vals.push_back(getEncodedLinkage(GV));
1344af732203SDimitry Andric     Vals.push_back(getEncodedAlign(GV.getAlign()));
13455ffd83dbSDimitry Andric     Vals.push_back(GV.hasSection() ? SectionMap[std::string(GV.getSection())]
13465ffd83dbSDimitry Andric                                    : 0);
13470b57cec5SDimitry Andric     if (GV.isThreadLocal() ||
13480b57cec5SDimitry Andric         GV.getVisibility() != GlobalValue::DefaultVisibility ||
13490b57cec5SDimitry Andric         GV.getUnnamedAddr() != GlobalValue::UnnamedAddr::None ||
13500b57cec5SDimitry Andric         GV.isExternallyInitialized() ||
13510b57cec5SDimitry Andric         GV.getDLLStorageClass() != GlobalValue::DefaultStorageClass ||
13520b57cec5SDimitry Andric         GV.hasComdat() ||
13530b57cec5SDimitry Andric         GV.hasAttributes() ||
13540b57cec5SDimitry Andric         GV.isDSOLocal() ||
13550b57cec5SDimitry Andric         GV.hasPartition()) {
13560b57cec5SDimitry Andric       Vals.push_back(getEncodedVisibility(GV));
13570b57cec5SDimitry Andric       Vals.push_back(getEncodedThreadLocalMode(GV));
13580b57cec5SDimitry Andric       Vals.push_back(getEncodedUnnamedAddr(GV));
13590b57cec5SDimitry Andric       Vals.push_back(GV.isExternallyInitialized());
13600b57cec5SDimitry Andric       Vals.push_back(getEncodedDLLStorageClass(GV));
13610b57cec5SDimitry Andric       Vals.push_back(GV.hasComdat() ? VE.getComdatID(GV.getComdat()) : 0);
13620b57cec5SDimitry Andric 
13630b57cec5SDimitry Andric       auto AL = GV.getAttributesAsList(AttributeList::FunctionIndex);
13640b57cec5SDimitry Andric       Vals.push_back(VE.getAttributeListID(AL));
13650b57cec5SDimitry Andric 
13660b57cec5SDimitry Andric       Vals.push_back(GV.isDSOLocal());
13670b57cec5SDimitry Andric       Vals.push_back(addToStrtab(GV.getPartition()));
13680b57cec5SDimitry Andric       Vals.push_back(GV.getPartition().size());
13690b57cec5SDimitry Andric     } else {
13700b57cec5SDimitry Andric       AbbrevToUse = SimpleGVarAbbrev;
13710b57cec5SDimitry Andric     }
13720b57cec5SDimitry Andric 
13730b57cec5SDimitry Andric     Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse);
13740b57cec5SDimitry Andric     Vals.clear();
13750b57cec5SDimitry Andric   }
13760b57cec5SDimitry Andric 
13770b57cec5SDimitry Andric   // Emit the function proto information.
13780b57cec5SDimitry Andric   for (const Function &F : M) {
13790b57cec5SDimitry Andric     // FUNCTION:  [strtab offset, strtab size, type, callingconv, isproto,
13800b57cec5SDimitry Andric     //             linkage, paramattrs, alignment, section, visibility, gc,
13810b57cec5SDimitry Andric     //             unnamed_addr, prologuedata, dllstorageclass, comdat,
13820b57cec5SDimitry Andric     //             prefixdata, personalityfn, DSO_Local, addrspace]
13830b57cec5SDimitry Andric     Vals.push_back(addToStrtab(F.getName()));
13840b57cec5SDimitry Andric     Vals.push_back(F.getName().size());
13850b57cec5SDimitry Andric     Vals.push_back(VE.getTypeID(F.getFunctionType()));
13860b57cec5SDimitry Andric     Vals.push_back(F.getCallingConv());
13870b57cec5SDimitry Andric     Vals.push_back(F.isDeclaration());
13880b57cec5SDimitry Andric     Vals.push_back(getEncodedLinkage(F));
13890b57cec5SDimitry Andric     Vals.push_back(VE.getAttributeListID(F.getAttributes()));
1390af732203SDimitry Andric     Vals.push_back(getEncodedAlign(F.getAlign()));
13915ffd83dbSDimitry Andric     Vals.push_back(F.hasSection() ? SectionMap[std::string(F.getSection())]
13925ffd83dbSDimitry Andric                                   : 0);
13930b57cec5SDimitry Andric     Vals.push_back(getEncodedVisibility(F));
13940b57cec5SDimitry Andric     Vals.push_back(F.hasGC() ? GCMap[F.getGC()] : 0);
13950b57cec5SDimitry Andric     Vals.push_back(getEncodedUnnamedAddr(F));
13960b57cec5SDimitry Andric     Vals.push_back(F.hasPrologueData() ? (VE.getValueID(F.getPrologueData()) + 1)
13970b57cec5SDimitry Andric                                        : 0);
13980b57cec5SDimitry Andric     Vals.push_back(getEncodedDLLStorageClass(F));
13990b57cec5SDimitry Andric     Vals.push_back(F.hasComdat() ? VE.getComdatID(F.getComdat()) : 0);
14000b57cec5SDimitry Andric     Vals.push_back(F.hasPrefixData() ? (VE.getValueID(F.getPrefixData()) + 1)
14010b57cec5SDimitry Andric                                      : 0);
14020b57cec5SDimitry Andric     Vals.push_back(
14030b57cec5SDimitry Andric         F.hasPersonalityFn() ? (VE.getValueID(F.getPersonalityFn()) + 1) : 0);
14040b57cec5SDimitry Andric 
14050b57cec5SDimitry Andric     Vals.push_back(F.isDSOLocal());
14060b57cec5SDimitry Andric     Vals.push_back(F.getAddressSpace());
14070b57cec5SDimitry Andric     Vals.push_back(addToStrtab(F.getPartition()));
14080b57cec5SDimitry Andric     Vals.push_back(F.getPartition().size());
14090b57cec5SDimitry Andric 
14100b57cec5SDimitry Andric     unsigned AbbrevToUse = 0;
14110b57cec5SDimitry Andric     Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse);
14120b57cec5SDimitry Andric     Vals.clear();
14130b57cec5SDimitry Andric   }
14140b57cec5SDimitry Andric 
14150b57cec5SDimitry Andric   // Emit the alias information.
14160b57cec5SDimitry Andric   for (const GlobalAlias &A : M.aliases()) {
14170b57cec5SDimitry Andric     // ALIAS: [strtab offset, strtab size, alias type, aliasee val#, linkage,
14180b57cec5SDimitry Andric     //         visibility, dllstorageclass, threadlocal, unnamed_addr,
14190b57cec5SDimitry Andric     //         DSO_Local]
14200b57cec5SDimitry Andric     Vals.push_back(addToStrtab(A.getName()));
14210b57cec5SDimitry Andric     Vals.push_back(A.getName().size());
14220b57cec5SDimitry Andric     Vals.push_back(VE.getTypeID(A.getValueType()));
14230b57cec5SDimitry Andric     Vals.push_back(A.getType()->getAddressSpace());
14240b57cec5SDimitry Andric     Vals.push_back(VE.getValueID(A.getAliasee()));
14250b57cec5SDimitry Andric     Vals.push_back(getEncodedLinkage(A));
14260b57cec5SDimitry Andric     Vals.push_back(getEncodedVisibility(A));
14270b57cec5SDimitry Andric     Vals.push_back(getEncodedDLLStorageClass(A));
14280b57cec5SDimitry Andric     Vals.push_back(getEncodedThreadLocalMode(A));
14290b57cec5SDimitry Andric     Vals.push_back(getEncodedUnnamedAddr(A));
14300b57cec5SDimitry Andric     Vals.push_back(A.isDSOLocal());
14310b57cec5SDimitry Andric     Vals.push_back(addToStrtab(A.getPartition()));
14320b57cec5SDimitry Andric     Vals.push_back(A.getPartition().size());
14330b57cec5SDimitry Andric 
14340b57cec5SDimitry Andric     unsigned AbbrevToUse = 0;
14350b57cec5SDimitry Andric     Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse);
14360b57cec5SDimitry Andric     Vals.clear();
14370b57cec5SDimitry Andric   }
14380b57cec5SDimitry Andric 
14390b57cec5SDimitry Andric   // Emit the ifunc information.
14400b57cec5SDimitry Andric   for (const GlobalIFunc &I : M.ifuncs()) {
14410b57cec5SDimitry Andric     // IFUNC: [strtab offset, strtab size, ifunc type, address space, resolver
14420b57cec5SDimitry Andric     //         val#, linkage, visibility, DSO_Local]
14430b57cec5SDimitry Andric     Vals.push_back(addToStrtab(I.getName()));
14440b57cec5SDimitry Andric     Vals.push_back(I.getName().size());
14450b57cec5SDimitry Andric     Vals.push_back(VE.getTypeID(I.getValueType()));
14460b57cec5SDimitry Andric     Vals.push_back(I.getType()->getAddressSpace());
14470b57cec5SDimitry Andric     Vals.push_back(VE.getValueID(I.getResolver()));
14480b57cec5SDimitry Andric     Vals.push_back(getEncodedLinkage(I));
14490b57cec5SDimitry Andric     Vals.push_back(getEncodedVisibility(I));
14500b57cec5SDimitry Andric     Vals.push_back(I.isDSOLocal());
14510b57cec5SDimitry Andric     Vals.push_back(addToStrtab(I.getPartition()));
14520b57cec5SDimitry Andric     Vals.push_back(I.getPartition().size());
14530b57cec5SDimitry Andric     Stream.EmitRecord(bitc::MODULE_CODE_IFUNC, Vals);
14540b57cec5SDimitry Andric     Vals.clear();
14550b57cec5SDimitry Andric   }
14560b57cec5SDimitry Andric 
14570b57cec5SDimitry Andric   writeValueSymbolTableForwardDecl();
14580b57cec5SDimitry Andric }
14590b57cec5SDimitry Andric 
getOptimizationFlags(const Value * V)14600b57cec5SDimitry Andric static uint64_t getOptimizationFlags(const Value *V) {
14610b57cec5SDimitry Andric   uint64_t Flags = 0;
14620b57cec5SDimitry Andric 
14630b57cec5SDimitry Andric   if (const auto *OBO = dyn_cast<OverflowingBinaryOperator>(V)) {
14640b57cec5SDimitry Andric     if (OBO->hasNoSignedWrap())
14650b57cec5SDimitry Andric       Flags |= 1 << bitc::OBO_NO_SIGNED_WRAP;
14660b57cec5SDimitry Andric     if (OBO->hasNoUnsignedWrap())
14670b57cec5SDimitry Andric       Flags |= 1 << bitc::OBO_NO_UNSIGNED_WRAP;
14680b57cec5SDimitry Andric   } else if (const auto *PEO = dyn_cast<PossiblyExactOperator>(V)) {
14690b57cec5SDimitry Andric     if (PEO->isExact())
14700b57cec5SDimitry Andric       Flags |= 1 << bitc::PEO_EXACT;
14710b57cec5SDimitry Andric   } else if (const auto *FPMO = dyn_cast<FPMathOperator>(V)) {
14720b57cec5SDimitry Andric     if (FPMO->hasAllowReassoc())
14730b57cec5SDimitry Andric       Flags |= bitc::AllowReassoc;
14740b57cec5SDimitry Andric     if (FPMO->hasNoNaNs())
14750b57cec5SDimitry Andric       Flags |= bitc::NoNaNs;
14760b57cec5SDimitry Andric     if (FPMO->hasNoInfs())
14770b57cec5SDimitry Andric       Flags |= bitc::NoInfs;
14780b57cec5SDimitry Andric     if (FPMO->hasNoSignedZeros())
14790b57cec5SDimitry Andric       Flags |= bitc::NoSignedZeros;
14800b57cec5SDimitry Andric     if (FPMO->hasAllowReciprocal())
14810b57cec5SDimitry Andric       Flags |= bitc::AllowReciprocal;
14820b57cec5SDimitry Andric     if (FPMO->hasAllowContract())
14830b57cec5SDimitry Andric       Flags |= bitc::AllowContract;
14840b57cec5SDimitry Andric     if (FPMO->hasApproxFunc())
14850b57cec5SDimitry Andric       Flags |= bitc::ApproxFunc;
14860b57cec5SDimitry Andric   }
14870b57cec5SDimitry Andric 
14880b57cec5SDimitry Andric   return Flags;
14890b57cec5SDimitry Andric }
14900b57cec5SDimitry Andric 
writeValueAsMetadata(const ValueAsMetadata * MD,SmallVectorImpl<uint64_t> & Record)14910b57cec5SDimitry Andric void ModuleBitcodeWriter::writeValueAsMetadata(
14920b57cec5SDimitry Andric     const ValueAsMetadata *MD, SmallVectorImpl<uint64_t> &Record) {
14930b57cec5SDimitry Andric   // Mimic an MDNode with a value as one operand.
14940b57cec5SDimitry Andric   Value *V = MD->getValue();
14950b57cec5SDimitry Andric   Record.push_back(VE.getTypeID(V->getType()));
14960b57cec5SDimitry Andric   Record.push_back(VE.getValueID(V));
14970b57cec5SDimitry Andric   Stream.EmitRecord(bitc::METADATA_VALUE, Record, 0);
14980b57cec5SDimitry Andric   Record.clear();
14990b57cec5SDimitry Andric }
15000b57cec5SDimitry Andric 
writeMDTuple(const MDTuple * N,SmallVectorImpl<uint64_t> & Record,unsigned Abbrev)15010b57cec5SDimitry Andric void ModuleBitcodeWriter::writeMDTuple(const MDTuple *N,
15020b57cec5SDimitry Andric                                        SmallVectorImpl<uint64_t> &Record,
15030b57cec5SDimitry Andric                                        unsigned Abbrev) {
15040b57cec5SDimitry Andric   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
15050b57cec5SDimitry Andric     Metadata *MD = N->getOperand(i);
15060b57cec5SDimitry Andric     assert(!(MD && isa<LocalAsMetadata>(MD)) &&
15070b57cec5SDimitry Andric            "Unexpected function-local metadata");
15080b57cec5SDimitry Andric     Record.push_back(VE.getMetadataOrNullID(MD));
15090b57cec5SDimitry Andric   }
15100b57cec5SDimitry Andric   Stream.EmitRecord(N->isDistinct() ? bitc::METADATA_DISTINCT_NODE
15110b57cec5SDimitry Andric                                     : bitc::METADATA_NODE,
15120b57cec5SDimitry Andric                     Record, Abbrev);
15130b57cec5SDimitry Andric   Record.clear();
15140b57cec5SDimitry Andric }
15150b57cec5SDimitry Andric 
createDILocationAbbrev()15160b57cec5SDimitry Andric unsigned ModuleBitcodeWriter::createDILocationAbbrev() {
15170b57cec5SDimitry Andric   // Assume the column is usually under 128, and always output the inlined-at
15180b57cec5SDimitry Andric   // location (it's never more expensive than building an array size 1).
15190b57cec5SDimitry Andric   auto Abbv = std::make_shared<BitCodeAbbrev>();
15200b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_LOCATION));
15210b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
15220b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
15230b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
15240b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
15250b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
15260b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
15270b57cec5SDimitry Andric   return Stream.EmitAbbrev(std::move(Abbv));
15280b57cec5SDimitry Andric }
15290b57cec5SDimitry Andric 
writeDILocation(const DILocation * N,SmallVectorImpl<uint64_t> & Record,unsigned & Abbrev)15300b57cec5SDimitry Andric void ModuleBitcodeWriter::writeDILocation(const DILocation *N,
15310b57cec5SDimitry Andric                                           SmallVectorImpl<uint64_t> &Record,
15320b57cec5SDimitry Andric                                           unsigned &Abbrev) {
15330b57cec5SDimitry Andric   if (!Abbrev)
15340b57cec5SDimitry Andric     Abbrev = createDILocationAbbrev();
15350b57cec5SDimitry Andric 
15360b57cec5SDimitry Andric   Record.push_back(N->isDistinct());
15370b57cec5SDimitry Andric   Record.push_back(N->getLine());
15380b57cec5SDimitry Andric   Record.push_back(N->getColumn());
15390b57cec5SDimitry Andric   Record.push_back(VE.getMetadataID(N->getScope()));
15400b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getInlinedAt()));
15410b57cec5SDimitry Andric   Record.push_back(N->isImplicitCode());
15420b57cec5SDimitry Andric 
15430b57cec5SDimitry Andric   Stream.EmitRecord(bitc::METADATA_LOCATION, Record, Abbrev);
15440b57cec5SDimitry Andric   Record.clear();
15450b57cec5SDimitry Andric }
15460b57cec5SDimitry Andric 
createGenericDINodeAbbrev()15470b57cec5SDimitry Andric unsigned ModuleBitcodeWriter::createGenericDINodeAbbrev() {
15480b57cec5SDimitry Andric   // Assume the column is usually under 128, and always output the inlined-at
15490b57cec5SDimitry Andric   // location (it's never more expensive than building an array size 1).
15500b57cec5SDimitry Andric   auto Abbv = std::make_shared<BitCodeAbbrev>();
15510b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_GENERIC_DEBUG));
15520b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
15530b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
15540b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
15550b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
15560b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
15570b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
15580b57cec5SDimitry Andric   return Stream.EmitAbbrev(std::move(Abbv));
15590b57cec5SDimitry Andric }
15600b57cec5SDimitry Andric 
writeGenericDINode(const GenericDINode * N,SmallVectorImpl<uint64_t> & Record,unsigned & Abbrev)15610b57cec5SDimitry Andric void ModuleBitcodeWriter::writeGenericDINode(const GenericDINode *N,
15620b57cec5SDimitry Andric                                              SmallVectorImpl<uint64_t> &Record,
15630b57cec5SDimitry Andric                                              unsigned &Abbrev) {
15640b57cec5SDimitry Andric   if (!Abbrev)
15650b57cec5SDimitry Andric     Abbrev = createGenericDINodeAbbrev();
15660b57cec5SDimitry Andric 
15670b57cec5SDimitry Andric   Record.push_back(N->isDistinct());
15680b57cec5SDimitry Andric   Record.push_back(N->getTag());
15690b57cec5SDimitry Andric   Record.push_back(0); // Per-tag version field; unused for now.
15700b57cec5SDimitry Andric 
15710b57cec5SDimitry Andric   for (auto &I : N->operands())
15720b57cec5SDimitry Andric     Record.push_back(VE.getMetadataOrNullID(I));
15730b57cec5SDimitry Andric 
15740b57cec5SDimitry Andric   Stream.EmitRecord(bitc::METADATA_GENERIC_DEBUG, Record, Abbrev);
15750b57cec5SDimitry Andric   Record.clear();
15760b57cec5SDimitry Andric }
15770b57cec5SDimitry Andric 
writeDISubrange(const DISubrange * N,SmallVectorImpl<uint64_t> & Record,unsigned Abbrev)15780b57cec5SDimitry Andric void ModuleBitcodeWriter::writeDISubrange(const DISubrange *N,
15790b57cec5SDimitry Andric                                           SmallVectorImpl<uint64_t> &Record,
15800b57cec5SDimitry Andric                                           unsigned Abbrev) {
15815ffd83dbSDimitry Andric   const uint64_t Version = 2 << 1;
15820b57cec5SDimitry Andric   Record.push_back((uint64_t)N->isDistinct() | Version);
15830b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawCountNode()));
15845ffd83dbSDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawLowerBound()));
15855ffd83dbSDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawUpperBound()));
15865ffd83dbSDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawStride()));
15870b57cec5SDimitry Andric 
15880b57cec5SDimitry Andric   Stream.EmitRecord(bitc::METADATA_SUBRANGE, Record, Abbrev);
15890b57cec5SDimitry Andric   Record.clear();
15900b57cec5SDimitry Andric }
15910b57cec5SDimitry Andric 
writeDIGenericSubrange(const DIGenericSubrange * N,SmallVectorImpl<uint64_t> & Record,unsigned Abbrev)1592af732203SDimitry Andric void ModuleBitcodeWriter::writeDIGenericSubrange(
1593af732203SDimitry Andric     const DIGenericSubrange *N, SmallVectorImpl<uint64_t> &Record,
1594af732203SDimitry Andric     unsigned Abbrev) {
1595af732203SDimitry Andric   Record.push_back((uint64_t)N->isDistinct());
1596af732203SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawCountNode()));
1597af732203SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawLowerBound()));
1598af732203SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawUpperBound()));
1599af732203SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawStride()));
1600af732203SDimitry Andric 
1601af732203SDimitry Andric   Stream.EmitRecord(bitc::METADATA_GENERIC_SUBRANGE, Record, Abbrev);
1602af732203SDimitry Andric   Record.clear();
1603af732203SDimitry Andric }
1604af732203SDimitry Andric 
emitSignedInt64(SmallVectorImpl<uint64_t> & Vals,uint64_t V)16055ffd83dbSDimitry Andric static void emitSignedInt64(SmallVectorImpl<uint64_t> &Vals, uint64_t V) {
16065ffd83dbSDimitry Andric   if ((int64_t)V >= 0)
16075ffd83dbSDimitry Andric     Vals.push_back(V << 1);
16085ffd83dbSDimitry Andric   else
16095ffd83dbSDimitry Andric     Vals.push_back((-V << 1) | 1);
16105ffd83dbSDimitry Andric }
16115ffd83dbSDimitry Andric 
emitWideAPInt(SmallVectorImpl<uint64_t> & Vals,const APInt & A)16125ffd83dbSDimitry Andric static void emitWideAPInt(SmallVectorImpl<uint64_t> &Vals, const APInt &A) {
16135ffd83dbSDimitry Andric   // We have an arbitrary precision integer value to write whose
16145ffd83dbSDimitry Andric   // bit width is > 64. However, in canonical unsigned integer
16155ffd83dbSDimitry Andric   // format it is likely that the high bits are going to be zero.
16165ffd83dbSDimitry Andric   // So, we only write the number of active words.
16175ffd83dbSDimitry Andric   unsigned NumWords = A.getActiveWords();
16185ffd83dbSDimitry Andric   const uint64_t *RawData = A.getRawData();
16195ffd83dbSDimitry Andric   for (unsigned i = 0; i < NumWords; i++)
16205ffd83dbSDimitry Andric     emitSignedInt64(Vals, RawData[i]);
16215ffd83dbSDimitry Andric }
16225ffd83dbSDimitry Andric 
writeDIEnumerator(const DIEnumerator * N,SmallVectorImpl<uint64_t> & Record,unsigned Abbrev)16230b57cec5SDimitry Andric void ModuleBitcodeWriter::writeDIEnumerator(const DIEnumerator *N,
16240b57cec5SDimitry Andric                                             SmallVectorImpl<uint64_t> &Record,
16250b57cec5SDimitry Andric                                             unsigned Abbrev) {
16265ffd83dbSDimitry Andric   const uint64_t IsBigInt = 1 << 2;
16275ffd83dbSDimitry Andric   Record.push_back(IsBigInt | (N->isUnsigned() << 1) | N->isDistinct());
16285ffd83dbSDimitry Andric   Record.push_back(N->getValue().getBitWidth());
16290b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
16305ffd83dbSDimitry Andric   emitWideAPInt(Record, N->getValue());
16310b57cec5SDimitry Andric 
16320b57cec5SDimitry Andric   Stream.EmitRecord(bitc::METADATA_ENUMERATOR, Record, Abbrev);
16330b57cec5SDimitry Andric   Record.clear();
16340b57cec5SDimitry Andric }
16350b57cec5SDimitry Andric 
writeDIBasicType(const DIBasicType * N,SmallVectorImpl<uint64_t> & Record,unsigned Abbrev)16360b57cec5SDimitry Andric void ModuleBitcodeWriter::writeDIBasicType(const DIBasicType *N,
16370b57cec5SDimitry Andric                                            SmallVectorImpl<uint64_t> &Record,
16380b57cec5SDimitry Andric                                            unsigned Abbrev) {
16390b57cec5SDimitry Andric   Record.push_back(N->isDistinct());
16400b57cec5SDimitry Andric   Record.push_back(N->getTag());
16410b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
16420b57cec5SDimitry Andric   Record.push_back(N->getSizeInBits());
16430b57cec5SDimitry Andric   Record.push_back(N->getAlignInBits());
16440b57cec5SDimitry Andric   Record.push_back(N->getEncoding());
16450b57cec5SDimitry Andric   Record.push_back(N->getFlags());
16460b57cec5SDimitry Andric 
16470b57cec5SDimitry Andric   Stream.EmitRecord(bitc::METADATA_BASIC_TYPE, Record, Abbrev);
16480b57cec5SDimitry Andric   Record.clear();
16490b57cec5SDimitry Andric }
16500b57cec5SDimitry Andric 
writeDIStringType(const DIStringType * N,SmallVectorImpl<uint64_t> & Record,unsigned Abbrev)1651af732203SDimitry Andric void ModuleBitcodeWriter::writeDIStringType(const DIStringType *N,
1652af732203SDimitry Andric                                             SmallVectorImpl<uint64_t> &Record,
1653af732203SDimitry Andric                                             unsigned Abbrev) {
1654af732203SDimitry Andric   Record.push_back(N->isDistinct());
1655af732203SDimitry Andric   Record.push_back(N->getTag());
1656af732203SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1657af732203SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getStringLength()));
1658af732203SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getStringLengthExp()));
1659af732203SDimitry Andric   Record.push_back(N->getSizeInBits());
1660af732203SDimitry Andric   Record.push_back(N->getAlignInBits());
1661af732203SDimitry Andric   Record.push_back(N->getEncoding());
1662af732203SDimitry Andric 
1663af732203SDimitry Andric   Stream.EmitRecord(bitc::METADATA_STRING_TYPE, Record, Abbrev);
1664af732203SDimitry Andric   Record.clear();
1665af732203SDimitry Andric }
1666af732203SDimitry Andric 
writeDIDerivedType(const DIDerivedType * N,SmallVectorImpl<uint64_t> & Record,unsigned Abbrev)16670b57cec5SDimitry Andric void ModuleBitcodeWriter::writeDIDerivedType(const DIDerivedType *N,
16680b57cec5SDimitry Andric                                              SmallVectorImpl<uint64_t> &Record,
16690b57cec5SDimitry Andric                                              unsigned Abbrev) {
16700b57cec5SDimitry Andric   Record.push_back(N->isDistinct());
16710b57cec5SDimitry Andric   Record.push_back(N->getTag());
16720b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
16730b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
16740b57cec5SDimitry Andric   Record.push_back(N->getLine());
16750b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
16760b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
16770b57cec5SDimitry Andric   Record.push_back(N->getSizeInBits());
16780b57cec5SDimitry Andric   Record.push_back(N->getAlignInBits());
16790b57cec5SDimitry Andric   Record.push_back(N->getOffsetInBits());
16800b57cec5SDimitry Andric   Record.push_back(N->getFlags());
16810b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getExtraData()));
16820b57cec5SDimitry Andric 
16830b57cec5SDimitry Andric   // DWARF address space is encoded as N->getDWARFAddressSpace() + 1. 0 means
16840b57cec5SDimitry Andric   // that there is no DWARF address space associated with DIDerivedType.
16850b57cec5SDimitry Andric   if (const auto &DWARFAddressSpace = N->getDWARFAddressSpace())
16860b57cec5SDimitry Andric     Record.push_back(*DWARFAddressSpace + 1);
16870b57cec5SDimitry Andric   else
16880b57cec5SDimitry Andric     Record.push_back(0);
16890b57cec5SDimitry Andric 
16900b57cec5SDimitry Andric   Stream.EmitRecord(bitc::METADATA_DERIVED_TYPE, Record, Abbrev);
16910b57cec5SDimitry Andric   Record.clear();
16920b57cec5SDimitry Andric }
16930b57cec5SDimitry Andric 
writeDICompositeType(const DICompositeType * N,SmallVectorImpl<uint64_t> & Record,unsigned Abbrev)16940b57cec5SDimitry Andric void ModuleBitcodeWriter::writeDICompositeType(
16950b57cec5SDimitry Andric     const DICompositeType *N, SmallVectorImpl<uint64_t> &Record,
16960b57cec5SDimitry Andric     unsigned Abbrev) {
16970b57cec5SDimitry Andric   const unsigned IsNotUsedInOldTypeRef = 0x2;
16980b57cec5SDimitry Andric   Record.push_back(IsNotUsedInOldTypeRef | (unsigned)N->isDistinct());
16990b57cec5SDimitry Andric   Record.push_back(N->getTag());
17000b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
17010b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
17020b57cec5SDimitry Andric   Record.push_back(N->getLine());
17030b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
17040b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
17050b57cec5SDimitry Andric   Record.push_back(N->getSizeInBits());
17060b57cec5SDimitry Andric   Record.push_back(N->getAlignInBits());
17070b57cec5SDimitry Andric   Record.push_back(N->getOffsetInBits());
17080b57cec5SDimitry Andric   Record.push_back(N->getFlags());
17090b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
17100b57cec5SDimitry Andric   Record.push_back(N->getRuntimeLang());
17110b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getVTableHolder()));
17120b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
17130b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawIdentifier()));
17140b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getDiscriminator()));
17155ffd83dbSDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawDataLocation()));
1716af732203SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawAssociated()));
1717af732203SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawAllocated()));
1718af732203SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawRank()));
17190b57cec5SDimitry Andric 
17200b57cec5SDimitry Andric   Stream.EmitRecord(bitc::METADATA_COMPOSITE_TYPE, Record, Abbrev);
17210b57cec5SDimitry Andric   Record.clear();
17220b57cec5SDimitry Andric }
17230b57cec5SDimitry Andric 
writeDISubroutineType(const DISubroutineType * N,SmallVectorImpl<uint64_t> & Record,unsigned Abbrev)17240b57cec5SDimitry Andric void ModuleBitcodeWriter::writeDISubroutineType(
17250b57cec5SDimitry Andric     const DISubroutineType *N, SmallVectorImpl<uint64_t> &Record,
17260b57cec5SDimitry Andric     unsigned Abbrev) {
17270b57cec5SDimitry Andric   const unsigned HasNoOldTypeRefs = 0x2;
17280b57cec5SDimitry Andric   Record.push_back(HasNoOldTypeRefs | (unsigned)N->isDistinct());
17290b57cec5SDimitry Andric   Record.push_back(N->getFlags());
17300b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getTypeArray().get()));
17310b57cec5SDimitry Andric   Record.push_back(N->getCC());
17320b57cec5SDimitry Andric 
17330b57cec5SDimitry Andric   Stream.EmitRecord(bitc::METADATA_SUBROUTINE_TYPE, Record, Abbrev);
17340b57cec5SDimitry Andric   Record.clear();
17350b57cec5SDimitry Andric }
17360b57cec5SDimitry Andric 
writeDIFile(const DIFile * N,SmallVectorImpl<uint64_t> & Record,unsigned Abbrev)17370b57cec5SDimitry Andric void ModuleBitcodeWriter::writeDIFile(const DIFile *N,
17380b57cec5SDimitry Andric                                       SmallVectorImpl<uint64_t> &Record,
17390b57cec5SDimitry Andric                                       unsigned Abbrev) {
17400b57cec5SDimitry Andric   Record.push_back(N->isDistinct());
17410b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawFilename()));
17420b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawDirectory()));
17430b57cec5SDimitry Andric   if (N->getRawChecksum()) {
17440b57cec5SDimitry Andric     Record.push_back(N->getRawChecksum()->Kind);
17450b57cec5SDimitry Andric     Record.push_back(VE.getMetadataOrNullID(N->getRawChecksum()->Value));
17460b57cec5SDimitry Andric   } else {
17470b57cec5SDimitry Andric     // Maintain backwards compatibility with the old internal representation of
17480b57cec5SDimitry Andric     // CSK_None in ChecksumKind by writing nulls here when Checksum is None.
17490b57cec5SDimitry Andric     Record.push_back(0);
17500b57cec5SDimitry Andric     Record.push_back(VE.getMetadataOrNullID(nullptr));
17510b57cec5SDimitry Andric   }
17520b57cec5SDimitry Andric   auto Source = N->getRawSource();
17530b57cec5SDimitry Andric   if (Source)
17540b57cec5SDimitry Andric     Record.push_back(VE.getMetadataOrNullID(*Source));
17550b57cec5SDimitry Andric 
17560b57cec5SDimitry Andric   Stream.EmitRecord(bitc::METADATA_FILE, Record, Abbrev);
17570b57cec5SDimitry Andric   Record.clear();
17580b57cec5SDimitry Andric }
17590b57cec5SDimitry Andric 
writeDICompileUnit(const DICompileUnit * N,SmallVectorImpl<uint64_t> & Record,unsigned Abbrev)17600b57cec5SDimitry Andric void ModuleBitcodeWriter::writeDICompileUnit(const DICompileUnit *N,
17610b57cec5SDimitry Andric                                              SmallVectorImpl<uint64_t> &Record,
17620b57cec5SDimitry Andric                                              unsigned Abbrev) {
17630b57cec5SDimitry Andric   assert(N->isDistinct() && "Expected distinct compile units");
17640b57cec5SDimitry Andric   Record.push_back(/* IsDistinct */ true);
17650b57cec5SDimitry Andric   Record.push_back(N->getSourceLanguage());
17660b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
17670b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawProducer()));
17680b57cec5SDimitry Andric   Record.push_back(N->isOptimized());
17690b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawFlags()));
17700b57cec5SDimitry Andric   Record.push_back(N->getRuntimeVersion());
17710b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawSplitDebugFilename()));
17720b57cec5SDimitry Andric   Record.push_back(N->getEmissionKind());
17730b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getEnumTypes().get()));
17740b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRetainedTypes().get()));
17750b57cec5SDimitry Andric   Record.push_back(/* subprograms */ 0);
17760b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getGlobalVariables().get()));
17770b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getImportedEntities().get()));
17780b57cec5SDimitry Andric   Record.push_back(N->getDWOId());
17790b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getMacros().get()));
17800b57cec5SDimitry Andric   Record.push_back(N->getSplitDebugInlining());
17810b57cec5SDimitry Andric   Record.push_back(N->getDebugInfoForProfiling());
17820b57cec5SDimitry Andric   Record.push_back((unsigned)N->getNameTableKind());
17835ffd83dbSDimitry Andric   Record.push_back(N->getRangesBaseAddress());
17845ffd83dbSDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawSysRoot()));
17855ffd83dbSDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawSDK()));
17860b57cec5SDimitry Andric 
17870b57cec5SDimitry Andric   Stream.EmitRecord(bitc::METADATA_COMPILE_UNIT, Record, Abbrev);
17880b57cec5SDimitry Andric   Record.clear();
17890b57cec5SDimitry Andric }
17900b57cec5SDimitry Andric 
writeDISubprogram(const DISubprogram * N,SmallVectorImpl<uint64_t> & Record,unsigned Abbrev)17910b57cec5SDimitry Andric void ModuleBitcodeWriter::writeDISubprogram(const DISubprogram *N,
17920b57cec5SDimitry Andric                                             SmallVectorImpl<uint64_t> &Record,
17930b57cec5SDimitry Andric                                             unsigned Abbrev) {
17940b57cec5SDimitry Andric   const uint64_t HasUnitFlag = 1 << 1;
17950b57cec5SDimitry Andric   const uint64_t HasSPFlagsFlag = 1 << 2;
17960b57cec5SDimitry Andric   Record.push_back(uint64_t(N->isDistinct()) | HasUnitFlag | HasSPFlagsFlag);
17970b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
17980b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
17990b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
18000b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
18010b57cec5SDimitry Andric   Record.push_back(N->getLine());
18020b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getType()));
18030b57cec5SDimitry Andric   Record.push_back(N->getScopeLine());
18040b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getContainingType()));
18050b57cec5SDimitry Andric   Record.push_back(N->getSPFlags());
18060b57cec5SDimitry Andric   Record.push_back(N->getVirtualIndex());
18070b57cec5SDimitry Andric   Record.push_back(N->getFlags());
18080b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawUnit()));
18090b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
18100b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getDeclaration()));
18110b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRetainedNodes().get()));
18120b57cec5SDimitry Andric   Record.push_back(N->getThisAdjustment());
18130b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getThrownTypes().get()));
18140b57cec5SDimitry Andric 
18150b57cec5SDimitry Andric   Stream.EmitRecord(bitc::METADATA_SUBPROGRAM, Record, Abbrev);
18160b57cec5SDimitry Andric   Record.clear();
18170b57cec5SDimitry Andric }
18180b57cec5SDimitry Andric 
writeDILexicalBlock(const DILexicalBlock * N,SmallVectorImpl<uint64_t> & Record,unsigned Abbrev)18190b57cec5SDimitry Andric void ModuleBitcodeWriter::writeDILexicalBlock(const DILexicalBlock *N,
18200b57cec5SDimitry Andric                                               SmallVectorImpl<uint64_t> &Record,
18210b57cec5SDimitry Andric                                               unsigned Abbrev) {
18220b57cec5SDimitry Andric   Record.push_back(N->isDistinct());
18230b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
18240b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
18250b57cec5SDimitry Andric   Record.push_back(N->getLine());
18260b57cec5SDimitry Andric   Record.push_back(N->getColumn());
18270b57cec5SDimitry Andric 
18280b57cec5SDimitry Andric   Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK, Record, Abbrev);
18290b57cec5SDimitry Andric   Record.clear();
18300b57cec5SDimitry Andric }
18310b57cec5SDimitry Andric 
writeDILexicalBlockFile(const DILexicalBlockFile * N,SmallVectorImpl<uint64_t> & Record,unsigned Abbrev)18320b57cec5SDimitry Andric void ModuleBitcodeWriter::writeDILexicalBlockFile(
18330b57cec5SDimitry Andric     const DILexicalBlockFile *N, SmallVectorImpl<uint64_t> &Record,
18340b57cec5SDimitry Andric     unsigned Abbrev) {
18350b57cec5SDimitry Andric   Record.push_back(N->isDistinct());
18360b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
18370b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
18380b57cec5SDimitry Andric   Record.push_back(N->getDiscriminator());
18390b57cec5SDimitry Andric 
18400b57cec5SDimitry Andric   Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK_FILE, Record, Abbrev);
18410b57cec5SDimitry Andric   Record.clear();
18420b57cec5SDimitry Andric }
18430b57cec5SDimitry Andric 
writeDICommonBlock(const DICommonBlock * N,SmallVectorImpl<uint64_t> & Record,unsigned Abbrev)18440b57cec5SDimitry Andric void ModuleBitcodeWriter::writeDICommonBlock(const DICommonBlock *N,
18450b57cec5SDimitry Andric                                              SmallVectorImpl<uint64_t> &Record,
18460b57cec5SDimitry Andric                                              unsigned Abbrev) {
18470b57cec5SDimitry Andric   Record.push_back(N->isDistinct());
18480b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
18490b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getDecl()));
18500b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
18510b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
18520b57cec5SDimitry Andric   Record.push_back(N->getLineNo());
18530b57cec5SDimitry Andric 
18540b57cec5SDimitry Andric   Stream.EmitRecord(bitc::METADATA_COMMON_BLOCK, Record, Abbrev);
18550b57cec5SDimitry Andric   Record.clear();
18560b57cec5SDimitry Andric }
18570b57cec5SDimitry Andric 
writeDINamespace(const DINamespace * N,SmallVectorImpl<uint64_t> & Record,unsigned Abbrev)18580b57cec5SDimitry Andric void ModuleBitcodeWriter::writeDINamespace(const DINamespace *N,
18590b57cec5SDimitry Andric                                            SmallVectorImpl<uint64_t> &Record,
18600b57cec5SDimitry Andric                                            unsigned Abbrev) {
18610b57cec5SDimitry Andric   Record.push_back(N->isDistinct() | N->getExportSymbols() << 1);
18620b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
18630b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
18640b57cec5SDimitry Andric 
18650b57cec5SDimitry Andric   Stream.EmitRecord(bitc::METADATA_NAMESPACE, Record, Abbrev);
18660b57cec5SDimitry Andric   Record.clear();
18670b57cec5SDimitry Andric }
18680b57cec5SDimitry Andric 
writeDIMacro(const DIMacro * N,SmallVectorImpl<uint64_t> & Record,unsigned Abbrev)18690b57cec5SDimitry Andric void ModuleBitcodeWriter::writeDIMacro(const DIMacro *N,
18700b57cec5SDimitry Andric                                        SmallVectorImpl<uint64_t> &Record,
18710b57cec5SDimitry Andric                                        unsigned Abbrev) {
18720b57cec5SDimitry Andric   Record.push_back(N->isDistinct());
18730b57cec5SDimitry Andric   Record.push_back(N->getMacinfoType());
18740b57cec5SDimitry Andric   Record.push_back(N->getLine());
18750b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
18760b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawValue()));
18770b57cec5SDimitry Andric 
18780b57cec5SDimitry Andric   Stream.EmitRecord(bitc::METADATA_MACRO, Record, Abbrev);
18790b57cec5SDimitry Andric   Record.clear();
18800b57cec5SDimitry Andric }
18810b57cec5SDimitry Andric 
writeDIMacroFile(const DIMacroFile * N,SmallVectorImpl<uint64_t> & Record,unsigned Abbrev)18820b57cec5SDimitry Andric void ModuleBitcodeWriter::writeDIMacroFile(const DIMacroFile *N,
18830b57cec5SDimitry Andric                                            SmallVectorImpl<uint64_t> &Record,
18840b57cec5SDimitry Andric                                            unsigned Abbrev) {
18850b57cec5SDimitry Andric   Record.push_back(N->isDistinct());
18860b57cec5SDimitry Andric   Record.push_back(N->getMacinfoType());
18870b57cec5SDimitry Andric   Record.push_back(N->getLine());
18880b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
18890b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
18900b57cec5SDimitry Andric 
18910b57cec5SDimitry Andric   Stream.EmitRecord(bitc::METADATA_MACRO_FILE, Record, Abbrev);
18920b57cec5SDimitry Andric   Record.clear();
18930b57cec5SDimitry Andric }
18940b57cec5SDimitry Andric 
writeDIArgList(const DIArgList * N,SmallVectorImpl<uint64_t> & Record,unsigned Abbrev)1895*5f7ddb14SDimitry Andric void ModuleBitcodeWriter::writeDIArgList(const DIArgList *N,
1896*5f7ddb14SDimitry Andric                                          SmallVectorImpl<uint64_t> &Record,
1897*5f7ddb14SDimitry Andric                                          unsigned Abbrev) {
1898*5f7ddb14SDimitry Andric   Record.reserve(N->getArgs().size());
1899*5f7ddb14SDimitry Andric   for (ValueAsMetadata *MD : N->getArgs())
1900*5f7ddb14SDimitry Andric     Record.push_back(VE.getMetadataID(MD));
1901*5f7ddb14SDimitry Andric 
1902*5f7ddb14SDimitry Andric   Stream.EmitRecord(bitc::METADATA_ARG_LIST, Record, Abbrev);
1903*5f7ddb14SDimitry Andric   Record.clear();
1904*5f7ddb14SDimitry Andric }
1905*5f7ddb14SDimitry Andric 
writeDIModule(const DIModule * N,SmallVectorImpl<uint64_t> & Record,unsigned Abbrev)19060b57cec5SDimitry Andric void ModuleBitcodeWriter::writeDIModule(const DIModule *N,
19070b57cec5SDimitry Andric                                         SmallVectorImpl<uint64_t> &Record,
19080b57cec5SDimitry Andric                                         unsigned Abbrev) {
19090b57cec5SDimitry Andric   Record.push_back(N->isDistinct());
19100b57cec5SDimitry Andric   for (auto &I : N->operands())
19110b57cec5SDimitry Andric     Record.push_back(VE.getMetadataOrNullID(I));
19125ffd83dbSDimitry Andric   Record.push_back(N->getLineNo());
1913af732203SDimitry Andric   Record.push_back(N->getIsDecl());
19140b57cec5SDimitry Andric 
19150b57cec5SDimitry Andric   Stream.EmitRecord(bitc::METADATA_MODULE, Record, Abbrev);
19160b57cec5SDimitry Andric   Record.clear();
19170b57cec5SDimitry Andric }
19180b57cec5SDimitry Andric 
writeDITemplateTypeParameter(const DITemplateTypeParameter * N,SmallVectorImpl<uint64_t> & Record,unsigned Abbrev)19190b57cec5SDimitry Andric void ModuleBitcodeWriter::writeDITemplateTypeParameter(
19200b57cec5SDimitry Andric     const DITemplateTypeParameter *N, SmallVectorImpl<uint64_t> &Record,
19210b57cec5SDimitry Andric     unsigned Abbrev) {
19220b57cec5SDimitry Andric   Record.push_back(N->isDistinct());
19230b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
19240b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getType()));
19255ffd83dbSDimitry Andric   Record.push_back(N->isDefault());
19260b57cec5SDimitry Andric 
19270b57cec5SDimitry Andric   Stream.EmitRecord(bitc::METADATA_TEMPLATE_TYPE, Record, Abbrev);
19280b57cec5SDimitry Andric   Record.clear();
19290b57cec5SDimitry Andric }
19300b57cec5SDimitry Andric 
writeDITemplateValueParameter(const DITemplateValueParameter * N,SmallVectorImpl<uint64_t> & Record,unsigned Abbrev)19310b57cec5SDimitry Andric void ModuleBitcodeWriter::writeDITemplateValueParameter(
19320b57cec5SDimitry Andric     const DITemplateValueParameter *N, SmallVectorImpl<uint64_t> &Record,
19330b57cec5SDimitry Andric     unsigned Abbrev) {
19340b57cec5SDimitry Andric   Record.push_back(N->isDistinct());
19350b57cec5SDimitry Andric   Record.push_back(N->getTag());
19360b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
19370b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getType()));
19385ffd83dbSDimitry Andric   Record.push_back(N->isDefault());
19390b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getValue()));
19400b57cec5SDimitry Andric 
19410b57cec5SDimitry Andric   Stream.EmitRecord(bitc::METADATA_TEMPLATE_VALUE, Record, Abbrev);
19420b57cec5SDimitry Andric   Record.clear();
19430b57cec5SDimitry Andric }
19440b57cec5SDimitry Andric 
writeDIGlobalVariable(const DIGlobalVariable * N,SmallVectorImpl<uint64_t> & Record,unsigned Abbrev)19450b57cec5SDimitry Andric void ModuleBitcodeWriter::writeDIGlobalVariable(
19460b57cec5SDimitry Andric     const DIGlobalVariable *N, SmallVectorImpl<uint64_t> &Record,
19470b57cec5SDimitry Andric     unsigned Abbrev) {
19480b57cec5SDimitry Andric   const uint64_t Version = 2 << 1;
19490b57cec5SDimitry Andric   Record.push_back((uint64_t)N->isDistinct() | Version);
19500b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
19510b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
19520b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
19530b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
19540b57cec5SDimitry Andric   Record.push_back(N->getLine());
19550b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getType()));
19560b57cec5SDimitry Andric   Record.push_back(N->isLocalToUnit());
19570b57cec5SDimitry Andric   Record.push_back(N->isDefinition());
19580b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getStaticDataMemberDeclaration()));
19590b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams()));
19600b57cec5SDimitry Andric   Record.push_back(N->getAlignInBits());
19610b57cec5SDimitry Andric 
19620b57cec5SDimitry Andric   Stream.EmitRecord(bitc::METADATA_GLOBAL_VAR, Record, Abbrev);
19630b57cec5SDimitry Andric   Record.clear();
19640b57cec5SDimitry Andric }
19650b57cec5SDimitry Andric 
writeDILocalVariable(const DILocalVariable * N,SmallVectorImpl<uint64_t> & Record,unsigned Abbrev)19660b57cec5SDimitry Andric void ModuleBitcodeWriter::writeDILocalVariable(
19670b57cec5SDimitry Andric     const DILocalVariable *N, SmallVectorImpl<uint64_t> &Record,
19680b57cec5SDimitry Andric     unsigned Abbrev) {
19690b57cec5SDimitry Andric   // In order to support all possible bitcode formats in BitcodeReader we need
19700b57cec5SDimitry Andric   // to distinguish the following cases:
19710b57cec5SDimitry Andric   // 1) Record has no artificial tag (Record[1]),
19720b57cec5SDimitry Andric   //   has no obsolete inlinedAt field (Record[9]).
19730b57cec5SDimitry Andric   //   In this case Record size will be 8, HasAlignment flag is false.
19740b57cec5SDimitry Andric   // 2) Record has artificial tag (Record[1]),
19750b57cec5SDimitry Andric   //   has no obsolete inlignedAt field (Record[9]).
19760b57cec5SDimitry Andric   //   In this case Record size will be 9, HasAlignment flag is false.
19770b57cec5SDimitry Andric   // 3) Record has both artificial tag (Record[1]) and
19780b57cec5SDimitry Andric   //   obsolete inlignedAt field (Record[9]).
19790b57cec5SDimitry Andric   //   In this case Record size will be 10, HasAlignment flag is false.
19800b57cec5SDimitry Andric   // 4) Record has neither artificial tag, nor inlignedAt field, but
19810b57cec5SDimitry Andric   //   HasAlignment flag is true and Record[8] contains alignment value.
19820b57cec5SDimitry Andric   const uint64_t HasAlignmentFlag = 1 << 1;
19830b57cec5SDimitry Andric   Record.push_back((uint64_t)N->isDistinct() | HasAlignmentFlag);
19840b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
19850b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
19860b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
19870b57cec5SDimitry Andric   Record.push_back(N->getLine());
19880b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getType()));
19890b57cec5SDimitry Andric   Record.push_back(N->getArg());
19900b57cec5SDimitry Andric   Record.push_back(N->getFlags());
19910b57cec5SDimitry Andric   Record.push_back(N->getAlignInBits());
19920b57cec5SDimitry Andric 
19930b57cec5SDimitry Andric   Stream.EmitRecord(bitc::METADATA_LOCAL_VAR, Record, Abbrev);
19940b57cec5SDimitry Andric   Record.clear();
19950b57cec5SDimitry Andric }
19960b57cec5SDimitry Andric 
writeDILabel(const DILabel * N,SmallVectorImpl<uint64_t> & Record,unsigned Abbrev)19970b57cec5SDimitry Andric void ModuleBitcodeWriter::writeDILabel(
19980b57cec5SDimitry Andric     const DILabel *N, SmallVectorImpl<uint64_t> &Record,
19990b57cec5SDimitry Andric     unsigned Abbrev) {
20000b57cec5SDimitry Andric   Record.push_back((uint64_t)N->isDistinct());
20010b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
20020b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
20030b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
20040b57cec5SDimitry Andric   Record.push_back(N->getLine());
20050b57cec5SDimitry Andric 
20060b57cec5SDimitry Andric   Stream.EmitRecord(bitc::METADATA_LABEL, Record, Abbrev);
20070b57cec5SDimitry Andric   Record.clear();
20080b57cec5SDimitry Andric }
20090b57cec5SDimitry Andric 
writeDIExpression(const DIExpression * N,SmallVectorImpl<uint64_t> & Record,unsigned Abbrev)20100b57cec5SDimitry Andric void ModuleBitcodeWriter::writeDIExpression(const DIExpression *N,
20110b57cec5SDimitry Andric                                             SmallVectorImpl<uint64_t> &Record,
20120b57cec5SDimitry Andric                                             unsigned Abbrev) {
20130b57cec5SDimitry Andric   Record.reserve(N->getElements().size() + 1);
20140b57cec5SDimitry Andric   const uint64_t Version = 3 << 1;
20150b57cec5SDimitry Andric   Record.push_back((uint64_t)N->isDistinct() | Version);
20160b57cec5SDimitry Andric   Record.append(N->elements_begin(), N->elements_end());
20170b57cec5SDimitry Andric 
20180b57cec5SDimitry Andric   Stream.EmitRecord(bitc::METADATA_EXPRESSION, Record, Abbrev);
20190b57cec5SDimitry Andric   Record.clear();
20200b57cec5SDimitry Andric }
20210b57cec5SDimitry Andric 
writeDIGlobalVariableExpression(const DIGlobalVariableExpression * N,SmallVectorImpl<uint64_t> & Record,unsigned Abbrev)20220b57cec5SDimitry Andric void ModuleBitcodeWriter::writeDIGlobalVariableExpression(
20230b57cec5SDimitry Andric     const DIGlobalVariableExpression *N, SmallVectorImpl<uint64_t> &Record,
20240b57cec5SDimitry Andric     unsigned Abbrev) {
20250b57cec5SDimitry Andric   Record.push_back(N->isDistinct());
20260b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getVariable()));
20270b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getExpression()));
20280b57cec5SDimitry Andric 
20290b57cec5SDimitry Andric   Stream.EmitRecord(bitc::METADATA_GLOBAL_VAR_EXPR, Record, Abbrev);
20300b57cec5SDimitry Andric   Record.clear();
20310b57cec5SDimitry Andric }
20320b57cec5SDimitry Andric 
writeDIObjCProperty(const DIObjCProperty * N,SmallVectorImpl<uint64_t> & Record,unsigned Abbrev)20330b57cec5SDimitry Andric void ModuleBitcodeWriter::writeDIObjCProperty(const DIObjCProperty *N,
20340b57cec5SDimitry Andric                                               SmallVectorImpl<uint64_t> &Record,
20350b57cec5SDimitry Andric                                               unsigned Abbrev) {
20360b57cec5SDimitry Andric   Record.push_back(N->isDistinct());
20370b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
20380b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
20390b57cec5SDimitry Andric   Record.push_back(N->getLine());
20400b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawSetterName()));
20410b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawGetterName()));
20420b57cec5SDimitry Andric   Record.push_back(N->getAttributes());
20430b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getType()));
20440b57cec5SDimitry Andric 
20450b57cec5SDimitry Andric   Stream.EmitRecord(bitc::METADATA_OBJC_PROPERTY, Record, Abbrev);
20460b57cec5SDimitry Andric   Record.clear();
20470b57cec5SDimitry Andric }
20480b57cec5SDimitry Andric 
writeDIImportedEntity(const DIImportedEntity * N,SmallVectorImpl<uint64_t> & Record,unsigned Abbrev)20490b57cec5SDimitry Andric void ModuleBitcodeWriter::writeDIImportedEntity(
20500b57cec5SDimitry Andric     const DIImportedEntity *N, SmallVectorImpl<uint64_t> &Record,
20510b57cec5SDimitry Andric     unsigned Abbrev) {
20520b57cec5SDimitry Andric   Record.push_back(N->isDistinct());
20530b57cec5SDimitry Andric   Record.push_back(N->getTag());
20540b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
20550b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getEntity()));
20560b57cec5SDimitry Andric   Record.push_back(N->getLine());
20570b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
20580b57cec5SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawFile()));
20590b57cec5SDimitry Andric 
20600b57cec5SDimitry Andric   Stream.EmitRecord(bitc::METADATA_IMPORTED_ENTITY, Record, Abbrev);
20610b57cec5SDimitry Andric   Record.clear();
20620b57cec5SDimitry Andric }
20630b57cec5SDimitry Andric 
createNamedMetadataAbbrev()20640b57cec5SDimitry Andric unsigned ModuleBitcodeWriter::createNamedMetadataAbbrev() {
20650b57cec5SDimitry Andric   auto Abbv = std::make_shared<BitCodeAbbrev>();
20660b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_NAME));
20670b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
20680b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
20690b57cec5SDimitry Andric   return Stream.EmitAbbrev(std::move(Abbv));
20700b57cec5SDimitry Andric }
20710b57cec5SDimitry Andric 
writeNamedMetadata(SmallVectorImpl<uint64_t> & Record)20720b57cec5SDimitry Andric void ModuleBitcodeWriter::writeNamedMetadata(
20730b57cec5SDimitry Andric     SmallVectorImpl<uint64_t> &Record) {
20740b57cec5SDimitry Andric   if (M.named_metadata_empty())
20750b57cec5SDimitry Andric     return;
20760b57cec5SDimitry Andric 
20770b57cec5SDimitry Andric   unsigned Abbrev = createNamedMetadataAbbrev();
20780b57cec5SDimitry Andric   for (const NamedMDNode &NMD : M.named_metadata()) {
20790b57cec5SDimitry Andric     // Write name.
20800b57cec5SDimitry Andric     StringRef Str = NMD.getName();
20810b57cec5SDimitry Andric     Record.append(Str.bytes_begin(), Str.bytes_end());
20820b57cec5SDimitry Andric     Stream.EmitRecord(bitc::METADATA_NAME, Record, Abbrev);
20830b57cec5SDimitry Andric     Record.clear();
20840b57cec5SDimitry Andric 
20850b57cec5SDimitry Andric     // Write named metadata operands.
20860b57cec5SDimitry Andric     for (const MDNode *N : NMD.operands())
20870b57cec5SDimitry Andric       Record.push_back(VE.getMetadataID(N));
20880b57cec5SDimitry Andric     Stream.EmitRecord(bitc::METADATA_NAMED_NODE, Record, 0);
20890b57cec5SDimitry Andric     Record.clear();
20900b57cec5SDimitry Andric   }
20910b57cec5SDimitry Andric }
20920b57cec5SDimitry Andric 
createMetadataStringsAbbrev()20930b57cec5SDimitry Andric unsigned ModuleBitcodeWriter::createMetadataStringsAbbrev() {
20940b57cec5SDimitry Andric   auto Abbv = std::make_shared<BitCodeAbbrev>();
20950b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_STRINGS));
20960b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of strings
20970b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // offset to chars
20980b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
20990b57cec5SDimitry Andric   return Stream.EmitAbbrev(std::move(Abbv));
21000b57cec5SDimitry Andric }
21010b57cec5SDimitry Andric 
21020b57cec5SDimitry Andric /// Write out a record for MDString.
21030b57cec5SDimitry Andric ///
21040b57cec5SDimitry Andric /// All the metadata strings in a metadata block are emitted in a single
21050b57cec5SDimitry Andric /// record.  The sizes and strings themselves are shoved into a blob.
writeMetadataStrings(ArrayRef<const Metadata * > Strings,SmallVectorImpl<uint64_t> & Record)21060b57cec5SDimitry Andric void ModuleBitcodeWriter::writeMetadataStrings(
21070b57cec5SDimitry Andric     ArrayRef<const Metadata *> Strings, SmallVectorImpl<uint64_t> &Record) {
21080b57cec5SDimitry Andric   if (Strings.empty())
21090b57cec5SDimitry Andric     return;
21100b57cec5SDimitry Andric 
21110b57cec5SDimitry Andric   // Start the record with the number of strings.
21120b57cec5SDimitry Andric   Record.push_back(bitc::METADATA_STRINGS);
21130b57cec5SDimitry Andric   Record.push_back(Strings.size());
21140b57cec5SDimitry Andric 
21150b57cec5SDimitry Andric   // Emit the sizes of the strings in the blob.
21160b57cec5SDimitry Andric   SmallString<256> Blob;
21170b57cec5SDimitry Andric   {
21180b57cec5SDimitry Andric     BitstreamWriter W(Blob);
21190b57cec5SDimitry Andric     for (const Metadata *MD : Strings)
21200b57cec5SDimitry Andric       W.EmitVBR(cast<MDString>(MD)->getLength(), 6);
21210b57cec5SDimitry Andric     W.FlushToWord();
21220b57cec5SDimitry Andric   }
21230b57cec5SDimitry Andric 
21240b57cec5SDimitry Andric   // Add the offset to the strings to the record.
21250b57cec5SDimitry Andric   Record.push_back(Blob.size());
21260b57cec5SDimitry Andric 
21270b57cec5SDimitry Andric   // Add the strings to the blob.
21280b57cec5SDimitry Andric   for (const Metadata *MD : Strings)
21290b57cec5SDimitry Andric     Blob.append(cast<MDString>(MD)->getString());
21300b57cec5SDimitry Andric 
21310b57cec5SDimitry Andric   // Emit the final record.
21320b57cec5SDimitry Andric   Stream.EmitRecordWithBlob(createMetadataStringsAbbrev(), Record, Blob);
21330b57cec5SDimitry Andric   Record.clear();
21340b57cec5SDimitry Andric }
21350b57cec5SDimitry Andric 
21360b57cec5SDimitry Andric // Generates an enum to use as an index in the Abbrev array of Metadata record.
21370b57cec5SDimitry Andric enum MetadataAbbrev : unsigned {
21380b57cec5SDimitry Andric #define HANDLE_MDNODE_LEAF(CLASS) CLASS##AbbrevID,
21390b57cec5SDimitry Andric #include "llvm/IR/Metadata.def"
21400b57cec5SDimitry Andric   LastPlusOne
21410b57cec5SDimitry Andric };
21420b57cec5SDimitry Andric 
writeMetadataRecords(ArrayRef<const Metadata * > MDs,SmallVectorImpl<uint64_t> & Record,std::vector<unsigned> * MDAbbrevs,std::vector<uint64_t> * IndexPos)21430b57cec5SDimitry Andric void ModuleBitcodeWriter::writeMetadataRecords(
21440b57cec5SDimitry Andric     ArrayRef<const Metadata *> MDs, SmallVectorImpl<uint64_t> &Record,
21450b57cec5SDimitry Andric     std::vector<unsigned> *MDAbbrevs, std::vector<uint64_t> *IndexPos) {
21460b57cec5SDimitry Andric   if (MDs.empty())
21470b57cec5SDimitry Andric     return;
21480b57cec5SDimitry Andric 
21490b57cec5SDimitry Andric   // Initialize MDNode abbreviations.
21500b57cec5SDimitry Andric #define HANDLE_MDNODE_LEAF(CLASS) unsigned CLASS##Abbrev = 0;
21510b57cec5SDimitry Andric #include "llvm/IR/Metadata.def"
21520b57cec5SDimitry Andric 
21530b57cec5SDimitry Andric   for (const Metadata *MD : MDs) {
21540b57cec5SDimitry Andric     if (IndexPos)
21550b57cec5SDimitry Andric       IndexPos->push_back(Stream.GetCurrentBitNo());
21560b57cec5SDimitry Andric     if (const MDNode *N = dyn_cast<MDNode>(MD)) {
21570b57cec5SDimitry Andric       assert(N->isResolved() && "Expected forward references to be resolved");
21580b57cec5SDimitry Andric 
21590b57cec5SDimitry Andric       switch (N->getMetadataID()) {
21600b57cec5SDimitry Andric       default:
21610b57cec5SDimitry Andric         llvm_unreachable("Invalid MDNode subclass");
21620b57cec5SDimitry Andric #define HANDLE_MDNODE_LEAF(CLASS)                                              \
21630b57cec5SDimitry Andric   case Metadata::CLASS##Kind:                                                  \
21640b57cec5SDimitry Andric     if (MDAbbrevs)                                                             \
21650b57cec5SDimitry Andric       write##CLASS(cast<CLASS>(N), Record,                                     \
21660b57cec5SDimitry Andric                    (*MDAbbrevs)[MetadataAbbrev::CLASS##AbbrevID]);             \
21670b57cec5SDimitry Andric     else                                                                       \
21680b57cec5SDimitry Andric       write##CLASS(cast<CLASS>(N), Record, CLASS##Abbrev);                     \
21690b57cec5SDimitry Andric     continue;
21700b57cec5SDimitry Andric #include "llvm/IR/Metadata.def"
21710b57cec5SDimitry Andric       }
21720b57cec5SDimitry Andric     }
21730b57cec5SDimitry Andric     writeValueAsMetadata(cast<ValueAsMetadata>(MD), Record);
21740b57cec5SDimitry Andric   }
21750b57cec5SDimitry Andric }
21760b57cec5SDimitry Andric 
writeModuleMetadata()21770b57cec5SDimitry Andric void ModuleBitcodeWriter::writeModuleMetadata() {
21780b57cec5SDimitry Andric   if (!VE.hasMDs() && M.named_metadata_empty())
21790b57cec5SDimitry Andric     return;
21800b57cec5SDimitry Andric 
21810b57cec5SDimitry Andric   Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 4);
21820b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
21830b57cec5SDimitry Andric 
21840b57cec5SDimitry Andric   // Emit all abbrevs upfront, so that the reader can jump in the middle of the
21850b57cec5SDimitry Andric   // block and load any metadata.
21860b57cec5SDimitry Andric   std::vector<unsigned> MDAbbrevs;
21870b57cec5SDimitry Andric 
21880b57cec5SDimitry Andric   MDAbbrevs.resize(MetadataAbbrev::LastPlusOne);
21890b57cec5SDimitry Andric   MDAbbrevs[MetadataAbbrev::DILocationAbbrevID] = createDILocationAbbrev();
21900b57cec5SDimitry Andric   MDAbbrevs[MetadataAbbrev::GenericDINodeAbbrevID] =
21910b57cec5SDimitry Andric       createGenericDINodeAbbrev();
21920b57cec5SDimitry Andric 
21930b57cec5SDimitry Andric   auto Abbv = std::make_shared<BitCodeAbbrev>();
21940b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_INDEX_OFFSET));
21950b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
21960b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
21970b57cec5SDimitry Andric   unsigned OffsetAbbrev = Stream.EmitAbbrev(std::move(Abbv));
21980b57cec5SDimitry Andric 
21990b57cec5SDimitry Andric   Abbv = std::make_shared<BitCodeAbbrev>();
22000b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_INDEX));
22010b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
22020b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
22030b57cec5SDimitry Andric   unsigned IndexAbbrev = Stream.EmitAbbrev(std::move(Abbv));
22040b57cec5SDimitry Andric 
22050b57cec5SDimitry Andric   // Emit MDStrings together upfront.
22060b57cec5SDimitry Andric   writeMetadataStrings(VE.getMDStrings(), Record);
22070b57cec5SDimitry Andric 
22080b57cec5SDimitry Andric   // We only emit an index for the metadata record if we have more than a given
22090b57cec5SDimitry Andric   // (naive) threshold of metadatas, otherwise it is not worth it.
22100b57cec5SDimitry Andric   if (VE.getNonMDStrings().size() > IndexThreshold) {
22110b57cec5SDimitry Andric     // Write a placeholder value in for the offset of the metadata index,
22120b57cec5SDimitry Andric     // which is written after the records, so that it can include
22130b57cec5SDimitry Andric     // the offset of each entry. The placeholder offset will be
22140b57cec5SDimitry Andric     // updated after all records are emitted.
22150b57cec5SDimitry Andric     uint64_t Vals[] = {0, 0};
22160b57cec5SDimitry Andric     Stream.EmitRecord(bitc::METADATA_INDEX_OFFSET, Vals, OffsetAbbrev);
22170b57cec5SDimitry Andric   }
22180b57cec5SDimitry Andric 
22190b57cec5SDimitry Andric   // Compute and save the bit offset to the current position, which will be
22200b57cec5SDimitry Andric   // patched when we emit the index later. We can simply subtract the 64-bit
22210b57cec5SDimitry Andric   // fixed size from the current bit number to get the location to backpatch.
22220b57cec5SDimitry Andric   uint64_t IndexOffsetRecordBitPos = Stream.GetCurrentBitNo();
22230b57cec5SDimitry Andric 
22240b57cec5SDimitry Andric   // This index will contain the bitpos for each individual record.
22250b57cec5SDimitry Andric   std::vector<uint64_t> IndexPos;
22260b57cec5SDimitry Andric   IndexPos.reserve(VE.getNonMDStrings().size());
22270b57cec5SDimitry Andric 
22280b57cec5SDimitry Andric   // Write all the records
22290b57cec5SDimitry Andric   writeMetadataRecords(VE.getNonMDStrings(), Record, &MDAbbrevs, &IndexPos);
22300b57cec5SDimitry Andric 
22310b57cec5SDimitry Andric   if (VE.getNonMDStrings().size() > IndexThreshold) {
22320b57cec5SDimitry Andric     // Now that we have emitted all the records we will emit the index. But
22330b57cec5SDimitry Andric     // first
22340b57cec5SDimitry Andric     // backpatch the forward reference so that the reader can skip the records
22350b57cec5SDimitry Andric     // efficiently.
22360b57cec5SDimitry Andric     Stream.BackpatchWord64(IndexOffsetRecordBitPos - 64,
22370b57cec5SDimitry Andric                            Stream.GetCurrentBitNo() - IndexOffsetRecordBitPos);
22380b57cec5SDimitry Andric 
22390b57cec5SDimitry Andric     // Delta encode the index.
22400b57cec5SDimitry Andric     uint64_t PreviousValue = IndexOffsetRecordBitPos;
22410b57cec5SDimitry Andric     for (auto &Elt : IndexPos) {
22420b57cec5SDimitry Andric       auto EltDelta = Elt - PreviousValue;
22430b57cec5SDimitry Andric       PreviousValue = Elt;
22440b57cec5SDimitry Andric       Elt = EltDelta;
22450b57cec5SDimitry Andric     }
22460b57cec5SDimitry Andric     // Emit the index record.
22470b57cec5SDimitry Andric     Stream.EmitRecord(bitc::METADATA_INDEX, IndexPos, IndexAbbrev);
22480b57cec5SDimitry Andric     IndexPos.clear();
22490b57cec5SDimitry Andric   }
22500b57cec5SDimitry Andric 
22510b57cec5SDimitry Andric   // Write the named metadata now.
22520b57cec5SDimitry Andric   writeNamedMetadata(Record);
22530b57cec5SDimitry Andric 
22540b57cec5SDimitry Andric   auto AddDeclAttachedMetadata = [&](const GlobalObject &GO) {
22550b57cec5SDimitry Andric     SmallVector<uint64_t, 4> Record;
22560b57cec5SDimitry Andric     Record.push_back(VE.getValueID(&GO));
22570b57cec5SDimitry Andric     pushGlobalMetadataAttachment(Record, GO);
22580b57cec5SDimitry Andric     Stream.EmitRecord(bitc::METADATA_GLOBAL_DECL_ATTACHMENT, Record);
22590b57cec5SDimitry Andric   };
22600b57cec5SDimitry Andric   for (const Function &F : M)
22610b57cec5SDimitry Andric     if (F.isDeclaration() && F.hasMetadata())
22620b57cec5SDimitry Andric       AddDeclAttachedMetadata(F);
22630b57cec5SDimitry Andric   // FIXME: Only store metadata for declarations here, and move data for global
22640b57cec5SDimitry Andric   // variable definitions to a separate block (PR28134).
22650b57cec5SDimitry Andric   for (const GlobalVariable &GV : M.globals())
22660b57cec5SDimitry Andric     if (GV.hasMetadata())
22670b57cec5SDimitry Andric       AddDeclAttachedMetadata(GV);
22680b57cec5SDimitry Andric 
22690b57cec5SDimitry Andric   Stream.ExitBlock();
22700b57cec5SDimitry Andric }
22710b57cec5SDimitry Andric 
writeFunctionMetadata(const Function & F)22720b57cec5SDimitry Andric void ModuleBitcodeWriter::writeFunctionMetadata(const Function &F) {
22730b57cec5SDimitry Andric   if (!VE.hasMDs())
22740b57cec5SDimitry Andric     return;
22750b57cec5SDimitry Andric 
22760b57cec5SDimitry Andric   Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
22770b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
22780b57cec5SDimitry Andric   writeMetadataStrings(VE.getMDStrings(), Record);
22790b57cec5SDimitry Andric   writeMetadataRecords(VE.getNonMDStrings(), Record);
22800b57cec5SDimitry Andric   Stream.ExitBlock();
22810b57cec5SDimitry Andric }
22820b57cec5SDimitry Andric 
pushGlobalMetadataAttachment(SmallVectorImpl<uint64_t> & Record,const GlobalObject & GO)22830b57cec5SDimitry Andric void ModuleBitcodeWriter::pushGlobalMetadataAttachment(
22840b57cec5SDimitry Andric     SmallVectorImpl<uint64_t> &Record, const GlobalObject &GO) {
22850b57cec5SDimitry Andric   // [n x [id, mdnode]]
22860b57cec5SDimitry Andric   SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
22870b57cec5SDimitry Andric   GO.getAllMetadata(MDs);
22880b57cec5SDimitry Andric   for (const auto &I : MDs) {
22890b57cec5SDimitry Andric     Record.push_back(I.first);
22900b57cec5SDimitry Andric     Record.push_back(VE.getMetadataID(I.second));
22910b57cec5SDimitry Andric   }
22920b57cec5SDimitry Andric }
22930b57cec5SDimitry Andric 
writeFunctionMetadataAttachment(const Function & F)22940b57cec5SDimitry Andric void ModuleBitcodeWriter::writeFunctionMetadataAttachment(const Function &F) {
22950b57cec5SDimitry Andric   Stream.EnterSubblock(bitc::METADATA_ATTACHMENT_ID, 3);
22960b57cec5SDimitry Andric 
22970b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
22980b57cec5SDimitry Andric 
22990b57cec5SDimitry Andric   if (F.hasMetadata()) {
23000b57cec5SDimitry Andric     pushGlobalMetadataAttachment(Record, F);
23010b57cec5SDimitry Andric     Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
23020b57cec5SDimitry Andric     Record.clear();
23030b57cec5SDimitry Andric   }
23040b57cec5SDimitry Andric 
23050b57cec5SDimitry Andric   // Write metadata attachments
23060b57cec5SDimitry Andric   // METADATA_ATTACHMENT - [m x [value, [n x [id, mdnode]]]
23070b57cec5SDimitry Andric   SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
23080b57cec5SDimitry Andric   for (const BasicBlock &BB : F)
23090b57cec5SDimitry Andric     for (const Instruction &I : BB) {
23100b57cec5SDimitry Andric       MDs.clear();
23110b57cec5SDimitry Andric       I.getAllMetadataOtherThanDebugLoc(MDs);
23120b57cec5SDimitry Andric 
23130b57cec5SDimitry Andric       // If no metadata, ignore instruction.
23140b57cec5SDimitry Andric       if (MDs.empty()) continue;
23150b57cec5SDimitry Andric 
23160b57cec5SDimitry Andric       Record.push_back(VE.getInstructionID(&I));
23170b57cec5SDimitry Andric 
23180b57cec5SDimitry Andric       for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
23190b57cec5SDimitry Andric         Record.push_back(MDs[i].first);
23200b57cec5SDimitry Andric         Record.push_back(VE.getMetadataID(MDs[i].second));
23210b57cec5SDimitry Andric       }
23220b57cec5SDimitry Andric       Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
23230b57cec5SDimitry Andric       Record.clear();
23240b57cec5SDimitry Andric     }
23250b57cec5SDimitry Andric 
23260b57cec5SDimitry Andric   Stream.ExitBlock();
23270b57cec5SDimitry Andric }
23280b57cec5SDimitry Andric 
writeModuleMetadataKinds()23290b57cec5SDimitry Andric void ModuleBitcodeWriter::writeModuleMetadataKinds() {
23300b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
23310b57cec5SDimitry Andric 
23320b57cec5SDimitry Andric   // Write metadata kinds
23330b57cec5SDimitry Andric   // METADATA_KIND - [n x [id, name]]
23340b57cec5SDimitry Andric   SmallVector<StringRef, 8> Names;
23350b57cec5SDimitry Andric   M.getMDKindNames(Names);
23360b57cec5SDimitry Andric 
23370b57cec5SDimitry Andric   if (Names.empty()) return;
23380b57cec5SDimitry Andric 
23390b57cec5SDimitry Andric   Stream.EnterSubblock(bitc::METADATA_KIND_BLOCK_ID, 3);
23400b57cec5SDimitry Andric 
23410b57cec5SDimitry Andric   for (unsigned MDKindID = 0, e = Names.size(); MDKindID != e; ++MDKindID) {
23420b57cec5SDimitry Andric     Record.push_back(MDKindID);
23430b57cec5SDimitry Andric     StringRef KName = Names[MDKindID];
23440b57cec5SDimitry Andric     Record.append(KName.begin(), KName.end());
23450b57cec5SDimitry Andric 
23460b57cec5SDimitry Andric     Stream.EmitRecord(bitc::METADATA_KIND, Record, 0);
23470b57cec5SDimitry Andric     Record.clear();
23480b57cec5SDimitry Andric   }
23490b57cec5SDimitry Andric 
23500b57cec5SDimitry Andric   Stream.ExitBlock();
23510b57cec5SDimitry Andric }
23520b57cec5SDimitry Andric 
writeOperandBundleTags()23530b57cec5SDimitry Andric void ModuleBitcodeWriter::writeOperandBundleTags() {
23540b57cec5SDimitry Andric   // Write metadata kinds
23550b57cec5SDimitry Andric   //
23560b57cec5SDimitry Andric   // OPERAND_BUNDLE_TAGS_BLOCK_ID : N x OPERAND_BUNDLE_TAG
23570b57cec5SDimitry Andric   //
23580b57cec5SDimitry Andric   // OPERAND_BUNDLE_TAG - [strchr x N]
23590b57cec5SDimitry Andric 
23600b57cec5SDimitry Andric   SmallVector<StringRef, 8> Tags;
23610b57cec5SDimitry Andric   M.getOperandBundleTags(Tags);
23620b57cec5SDimitry Andric 
23630b57cec5SDimitry Andric   if (Tags.empty())
23640b57cec5SDimitry Andric     return;
23650b57cec5SDimitry Andric 
23660b57cec5SDimitry Andric   Stream.EnterSubblock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID, 3);
23670b57cec5SDimitry Andric 
23680b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
23690b57cec5SDimitry Andric 
23700b57cec5SDimitry Andric   for (auto Tag : Tags) {
23710b57cec5SDimitry Andric     Record.append(Tag.begin(), Tag.end());
23720b57cec5SDimitry Andric 
23730b57cec5SDimitry Andric     Stream.EmitRecord(bitc::OPERAND_BUNDLE_TAG, Record, 0);
23740b57cec5SDimitry Andric     Record.clear();
23750b57cec5SDimitry Andric   }
23760b57cec5SDimitry Andric 
23770b57cec5SDimitry Andric   Stream.ExitBlock();
23780b57cec5SDimitry Andric }
23790b57cec5SDimitry Andric 
writeSyncScopeNames()23800b57cec5SDimitry Andric void ModuleBitcodeWriter::writeSyncScopeNames() {
23810b57cec5SDimitry Andric   SmallVector<StringRef, 8> SSNs;
23820b57cec5SDimitry Andric   M.getContext().getSyncScopeNames(SSNs);
23830b57cec5SDimitry Andric   if (SSNs.empty())
23840b57cec5SDimitry Andric     return;
23850b57cec5SDimitry Andric 
23860b57cec5SDimitry Andric   Stream.EnterSubblock(bitc::SYNC_SCOPE_NAMES_BLOCK_ID, 2);
23870b57cec5SDimitry Andric 
23880b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
23890b57cec5SDimitry Andric   for (auto SSN : SSNs) {
23900b57cec5SDimitry Andric     Record.append(SSN.begin(), SSN.end());
23910b57cec5SDimitry Andric     Stream.EmitRecord(bitc::SYNC_SCOPE_NAME, Record, 0);
23920b57cec5SDimitry Andric     Record.clear();
23930b57cec5SDimitry Andric   }
23940b57cec5SDimitry Andric 
23950b57cec5SDimitry Andric   Stream.ExitBlock();
23960b57cec5SDimitry Andric }
23970b57cec5SDimitry Andric 
writeConstants(unsigned FirstVal,unsigned LastVal,bool isGlobal)23980b57cec5SDimitry Andric void ModuleBitcodeWriter::writeConstants(unsigned FirstVal, unsigned LastVal,
23990b57cec5SDimitry Andric                                          bool isGlobal) {
24000b57cec5SDimitry Andric   if (FirstVal == LastVal) return;
24010b57cec5SDimitry Andric 
24020b57cec5SDimitry Andric   Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 4);
24030b57cec5SDimitry Andric 
24040b57cec5SDimitry Andric   unsigned AggregateAbbrev = 0;
24050b57cec5SDimitry Andric   unsigned String8Abbrev = 0;
24060b57cec5SDimitry Andric   unsigned CString7Abbrev = 0;
24070b57cec5SDimitry Andric   unsigned CString6Abbrev = 0;
24080b57cec5SDimitry Andric   // If this is a constant pool for the module, emit module-specific abbrevs.
24090b57cec5SDimitry Andric   if (isGlobal) {
24100b57cec5SDimitry Andric     // Abbrev for CST_CODE_AGGREGATE.
24110b57cec5SDimitry Andric     auto Abbv = std::make_shared<BitCodeAbbrev>();
24120b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_AGGREGATE));
24130b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
24140b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal+1)));
24150b57cec5SDimitry Andric     AggregateAbbrev = Stream.EmitAbbrev(std::move(Abbv));
24160b57cec5SDimitry Andric 
24170b57cec5SDimitry Andric     // Abbrev for CST_CODE_STRING.
24180b57cec5SDimitry Andric     Abbv = std::make_shared<BitCodeAbbrev>();
24190b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_STRING));
24200b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
24210b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
24220b57cec5SDimitry Andric     String8Abbrev = Stream.EmitAbbrev(std::move(Abbv));
24230b57cec5SDimitry Andric     // Abbrev for CST_CODE_CSTRING.
24240b57cec5SDimitry Andric     Abbv = std::make_shared<BitCodeAbbrev>();
24250b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
24260b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
24270b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
24280b57cec5SDimitry Andric     CString7Abbrev = Stream.EmitAbbrev(std::move(Abbv));
24290b57cec5SDimitry Andric     // Abbrev for CST_CODE_CSTRING.
24300b57cec5SDimitry Andric     Abbv = std::make_shared<BitCodeAbbrev>();
24310b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
24320b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
24330b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
24340b57cec5SDimitry Andric     CString6Abbrev = Stream.EmitAbbrev(std::move(Abbv));
24350b57cec5SDimitry Andric   }
24360b57cec5SDimitry Andric 
24370b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
24380b57cec5SDimitry Andric 
24390b57cec5SDimitry Andric   const ValueEnumerator::ValueList &Vals = VE.getValues();
24400b57cec5SDimitry Andric   Type *LastTy = nullptr;
24410b57cec5SDimitry Andric   for (unsigned i = FirstVal; i != LastVal; ++i) {
24420b57cec5SDimitry Andric     const Value *V = Vals[i].first;
24430b57cec5SDimitry Andric     // If we need to switch types, do so now.
24440b57cec5SDimitry Andric     if (V->getType() != LastTy) {
24450b57cec5SDimitry Andric       LastTy = V->getType();
24460b57cec5SDimitry Andric       Record.push_back(VE.getTypeID(LastTy));
24470b57cec5SDimitry Andric       Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record,
24480b57cec5SDimitry Andric                         CONSTANTS_SETTYPE_ABBREV);
24490b57cec5SDimitry Andric       Record.clear();
24500b57cec5SDimitry Andric     }
24510b57cec5SDimitry Andric 
24520b57cec5SDimitry Andric     if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
2453*5f7ddb14SDimitry Andric       Record.push_back(
2454*5f7ddb14SDimitry Andric           unsigned(IA->hasSideEffects()) | unsigned(IA->isAlignStack()) << 1 |
2455*5f7ddb14SDimitry Andric           unsigned(IA->getDialect() & 1) << 2 | unsigned(IA->canThrow()) << 3);
24560b57cec5SDimitry Andric 
24570b57cec5SDimitry Andric       // Add the asm string.
24580b57cec5SDimitry Andric       const std::string &AsmStr = IA->getAsmString();
24590b57cec5SDimitry Andric       Record.push_back(AsmStr.size());
24600b57cec5SDimitry Andric       Record.append(AsmStr.begin(), AsmStr.end());
24610b57cec5SDimitry Andric 
24620b57cec5SDimitry Andric       // Add the constraint string.
24630b57cec5SDimitry Andric       const std::string &ConstraintStr = IA->getConstraintString();
24640b57cec5SDimitry Andric       Record.push_back(ConstraintStr.size());
24650b57cec5SDimitry Andric       Record.append(ConstraintStr.begin(), ConstraintStr.end());
24660b57cec5SDimitry Andric       Stream.EmitRecord(bitc::CST_CODE_INLINEASM, Record);
24670b57cec5SDimitry Andric       Record.clear();
24680b57cec5SDimitry Andric       continue;
24690b57cec5SDimitry Andric     }
24700b57cec5SDimitry Andric     const Constant *C = cast<Constant>(V);
24710b57cec5SDimitry Andric     unsigned Code = -1U;
24720b57cec5SDimitry Andric     unsigned AbbrevToUse = 0;
24730b57cec5SDimitry Andric     if (C->isNullValue()) {
24740b57cec5SDimitry Andric       Code = bitc::CST_CODE_NULL;
2475af732203SDimitry Andric     } else if (isa<PoisonValue>(C)) {
2476af732203SDimitry Andric       Code = bitc::CST_CODE_POISON;
24770b57cec5SDimitry Andric     } else if (isa<UndefValue>(C)) {
24780b57cec5SDimitry Andric       Code = bitc::CST_CODE_UNDEF;
24790b57cec5SDimitry Andric     } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {
24800b57cec5SDimitry Andric       if (IV->getBitWidth() <= 64) {
24810b57cec5SDimitry Andric         uint64_t V = IV->getSExtValue();
24820b57cec5SDimitry Andric         emitSignedInt64(Record, V);
24830b57cec5SDimitry Andric         Code = bitc::CST_CODE_INTEGER;
24840b57cec5SDimitry Andric         AbbrevToUse = CONSTANTS_INTEGER_ABBREV;
24850b57cec5SDimitry Andric       } else {                             // Wide integers, > 64 bits in size.
24865ffd83dbSDimitry Andric         emitWideAPInt(Record, IV->getValue());
24870b57cec5SDimitry Andric         Code = bitc::CST_CODE_WIDE_INTEGER;
24880b57cec5SDimitry Andric       }
24890b57cec5SDimitry Andric     } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
24900b57cec5SDimitry Andric       Code = bitc::CST_CODE_FLOAT;
24910b57cec5SDimitry Andric       Type *Ty = CFP->getType();
24925ffd83dbSDimitry Andric       if (Ty->isHalfTy() || Ty->isBFloatTy() || Ty->isFloatTy() ||
24935ffd83dbSDimitry Andric           Ty->isDoubleTy()) {
24940b57cec5SDimitry Andric         Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
24950b57cec5SDimitry Andric       } else if (Ty->isX86_FP80Ty()) {
24960b57cec5SDimitry Andric         // api needed to prevent premature destruction
24970b57cec5SDimitry Andric         // bits are not in the same order as a normal i80 APInt, compensate.
24980b57cec5SDimitry Andric         APInt api = CFP->getValueAPF().bitcastToAPInt();
24990b57cec5SDimitry Andric         const uint64_t *p = api.getRawData();
25000b57cec5SDimitry Andric         Record.push_back((p[1] << 48) | (p[0] >> 16));
25010b57cec5SDimitry Andric         Record.push_back(p[0] & 0xffffLL);
25020b57cec5SDimitry Andric       } else if (Ty->isFP128Ty() || Ty->isPPC_FP128Ty()) {
25030b57cec5SDimitry Andric         APInt api = CFP->getValueAPF().bitcastToAPInt();
25040b57cec5SDimitry Andric         const uint64_t *p = api.getRawData();
25050b57cec5SDimitry Andric         Record.push_back(p[0]);
25060b57cec5SDimitry Andric         Record.push_back(p[1]);
25070b57cec5SDimitry Andric       } else {
25080b57cec5SDimitry Andric         assert(0 && "Unknown FP type!");
25090b57cec5SDimitry Andric       }
25100b57cec5SDimitry Andric     } else if (isa<ConstantDataSequential>(C) &&
25110b57cec5SDimitry Andric                cast<ConstantDataSequential>(C)->isString()) {
25120b57cec5SDimitry Andric       const ConstantDataSequential *Str = cast<ConstantDataSequential>(C);
25130b57cec5SDimitry Andric       // Emit constant strings specially.
25140b57cec5SDimitry Andric       unsigned NumElts = Str->getNumElements();
25150b57cec5SDimitry Andric       // If this is a null-terminated string, use the denser CSTRING encoding.
25160b57cec5SDimitry Andric       if (Str->isCString()) {
25170b57cec5SDimitry Andric         Code = bitc::CST_CODE_CSTRING;
25180b57cec5SDimitry Andric         --NumElts;  // Don't encode the null, which isn't allowed by char6.
25190b57cec5SDimitry Andric       } else {
25200b57cec5SDimitry Andric         Code = bitc::CST_CODE_STRING;
25210b57cec5SDimitry Andric         AbbrevToUse = String8Abbrev;
25220b57cec5SDimitry Andric       }
25230b57cec5SDimitry Andric       bool isCStr7 = Code == bitc::CST_CODE_CSTRING;
25240b57cec5SDimitry Andric       bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING;
25250b57cec5SDimitry Andric       for (unsigned i = 0; i != NumElts; ++i) {
25260b57cec5SDimitry Andric         unsigned char V = Str->getElementAsInteger(i);
25270b57cec5SDimitry Andric         Record.push_back(V);
25280b57cec5SDimitry Andric         isCStr7 &= (V & 128) == 0;
25290b57cec5SDimitry Andric         if (isCStrChar6)
25300b57cec5SDimitry Andric           isCStrChar6 = BitCodeAbbrevOp::isChar6(V);
25310b57cec5SDimitry Andric       }
25320b57cec5SDimitry Andric 
25330b57cec5SDimitry Andric       if (isCStrChar6)
25340b57cec5SDimitry Andric         AbbrevToUse = CString6Abbrev;
25350b57cec5SDimitry Andric       else if (isCStr7)
25360b57cec5SDimitry Andric         AbbrevToUse = CString7Abbrev;
25370b57cec5SDimitry Andric     } else if (const ConstantDataSequential *CDS =
25380b57cec5SDimitry Andric                   dyn_cast<ConstantDataSequential>(C)) {
25390b57cec5SDimitry Andric       Code = bitc::CST_CODE_DATA;
25405ffd83dbSDimitry Andric       Type *EltTy = CDS->getElementType();
25410b57cec5SDimitry Andric       if (isa<IntegerType>(EltTy)) {
25420b57cec5SDimitry Andric         for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
25430b57cec5SDimitry Andric           Record.push_back(CDS->getElementAsInteger(i));
25440b57cec5SDimitry Andric       } else {
25450b57cec5SDimitry Andric         for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
25460b57cec5SDimitry Andric           Record.push_back(
25470b57cec5SDimitry Andric               CDS->getElementAsAPFloat(i).bitcastToAPInt().getLimitedValue());
25480b57cec5SDimitry Andric       }
25490b57cec5SDimitry Andric     } else if (isa<ConstantAggregate>(C)) {
25500b57cec5SDimitry Andric       Code = bitc::CST_CODE_AGGREGATE;
25510b57cec5SDimitry Andric       for (const Value *Op : C->operands())
25520b57cec5SDimitry Andric         Record.push_back(VE.getValueID(Op));
25530b57cec5SDimitry Andric       AbbrevToUse = AggregateAbbrev;
25540b57cec5SDimitry Andric     } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
25550b57cec5SDimitry Andric       switch (CE->getOpcode()) {
25560b57cec5SDimitry Andric       default:
25570b57cec5SDimitry Andric         if (Instruction::isCast(CE->getOpcode())) {
25580b57cec5SDimitry Andric           Code = bitc::CST_CODE_CE_CAST;
25590b57cec5SDimitry Andric           Record.push_back(getEncodedCastOpcode(CE->getOpcode()));
25600b57cec5SDimitry Andric           Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
25610b57cec5SDimitry Andric           Record.push_back(VE.getValueID(C->getOperand(0)));
25620b57cec5SDimitry Andric           AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;
25630b57cec5SDimitry Andric         } else {
25640b57cec5SDimitry Andric           assert(CE->getNumOperands() == 2 && "Unknown constant expr!");
25650b57cec5SDimitry Andric           Code = bitc::CST_CODE_CE_BINOP;
25660b57cec5SDimitry Andric           Record.push_back(getEncodedBinaryOpcode(CE->getOpcode()));
25670b57cec5SDimitry Andric           Record.push_back(VE.getValueID(C->getOperand(0)));
25680b57cec5SDimitry Andric           Record.push_back(VE.getValueID(C->getOperand(1)));
25690b57cec5SDimitry Andric           uint64_t Flags = getOptimizationFlags(CE);
25700b57cec5SDimitry Andric           if (Flags != 0)
25710b57cec5SDimitry Andric             Record.push_back(Flags);
25720b57cec5SDimitry Andric         }
25730b57cec5SDimitry Andric         break;
25740b57cec5SDimitry Andric       case Instruction::FNeg: {
25750b57cec5SDimitry Andric         assert(CE->getNumOperands() == 1 && "Unknown constant expr!");
25760b57cec5SDimitry Andric         Code = bitc::CST_CODE_CE_UNOP;
25770b57cec5SDimitry Andric         Record.push_back(getEncodedUnaryOpcode(CE->getOpcode()));
25780b57cec5SDimitry Andric         Record.push_back(VE.getValueID(C->getOperand(0)));
25790b57cec5SDimitry Andric         uint64_t Flags = getOptimizationFlags(CE);
25800b57cec5SDimitry Andric         if (Flags != 0)
25810b57cec5SDimitry Andric           Record.push_back(Flags);
25820b57cec5SDimitry Andric         break;
25830b57cec5SDimitry Andric       }
25840b57cec5SDimitry Andric       case Instruction::GetElementPtr: {
25850b57cec5SDimitry Andric         Code = bitc::CST_CODE_CE_GEP;
25860b57cec5SDimitry Andric         const auto *GO = cast<GEPOperator>(C);
25870b57cec5SDimitry Andric         Record.push_back(VE.getTypeID(GO->getSourceElementType()));
25880b57cec5SDimitry Andric         if (Optional<unsigned> Idx = GO->getInRangeIndex()) {
25890b57cec5SDimitry Andric           Code = bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX;
25900b57cec5SDimitry Andric           Record.push_back((*Idx << 1) | GO->isInBounds());
25910b57cec5SDimitry Andric         } else if (GO->isInBounds())
25920b57cec5SDimitry Andric           Code = bitc::CST_CODE_CE_INBOUNDS_GEP;
25930b57cec5SDimitry Andric         for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
25940b57cec5SDimitry Andric           Record.push_back(VE.getTypeID(C->getOperand(i)->getType()));
25950b57cec5SDimitry Andric           Record.push_back(VE.getValueID(C->getOperand(i)));
25960b57cec5SDimitry Andric         }
25970b57cec5SDimitry Andric         break;
25980b57cec5SDimitry Andric       }
25990b57cec5SDimitry Andric       case Instruction::Select:
26000b57cec5SDimitry Andric         Code = bitc::CST_CODE_CE_SELECT;
26010b57cec5SDimitry Andric         Record.push_back(VE.getValueID(C->getOperand(0)));
26020b57cec5SDimitry Andric         Record.push_back(VE.getValueID(C->getOperand(1)));
26030b57cec5SDimitry Andric         Record.push_back(VE.getValueID(C->getOperand(2)));
26040b57cec5SDimitry Andric         break;
26050b57cec5SDimitry Andric       case Instruction::ExtractElement:
26060b57cec5SDimitry Andric         Code = bitc::CST_CODE_CE_EXTRACTELT;
26070b57cec5SDimitry Andric         Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
26080b57cec5SDimitry Andric         Record.push_back(VE.getValueID(C->getOperand(0)));
26090b57cec5SDimitry Andric         Record.push_back(VE.getTypeID(C->getOperand(1)->getType()));
26100b57cec5SDimitry Andric         Record.push_back(VE.getValueID(C->getOperand(1)));
26110b57cec5SDimitry Andric         break;
26120b57cec5SDimitry Andric       case Instruction::InsertElement:
26130b57cec5SDimitry Andric         Code = bitc::CST_CODE_CE_INSERTELT;
26140b57cec5SDimitry Andric         Record.push_back(VE.getValueID(C->getOperand(0)));
26150b57cec5SDimitry Andric         Record.push_back(VE.getValueID(C->getOperand(1)));
26160b57cec5SDimitry Andric         Record.push_back(VE.getTypeID(C->getOperand(2)->getType()));
26170b57cec5SDimitry Andric         Record.push_back(VE.getValueID(C->getOperand(2)));
26180b57cec5SDimitry Andric         break;
26190b57cec5SDimitry Andric       case Instruction::ShuffleVector:
26200b57cec5SDimitry Andric         // If the return type and argument types are the same, this is a
26210b57cec5SDimitry Andric         // standard shufflevector instruction.  If the types are different,
26220b57cec5SDimitry Andric         // then the shuffle is widening or truncating the input vectors, and
26230b57cec5SDimitry Andric         // the argument type must also be encoded.
26240b57cec5SDimitry Andric         if (C->getType() == C->getOperand(0)->getType()) {
26250b57cec5SDimitry Andric           Code = bitc::CST_CODE_CE_SHUFFLEVEC;
26260b57cec5SDimitry Andric         } else {
26270b57cec5SDimitry Andric           Code = bitc::CST_CODE_CE_SHUFVEC_EX;
26280b57cec5SDimitry Andric           Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
26290b57cec5SDimitry Andric         }
26300b57cec5SDimitry Andric         Record.push_back(VE.getValueID(C->getOperand(0)));
26310b57cec5SDimitry Andric         Record.push_back(VE.getValueID(C->getOperand(1)));
26325ffd83dbSDimitry Andric         Record.push_back(VE.getValueID(CE->getShuffleMaskForBitcode()));
26330b57cec5SDimitry Andric         break;
26340b57cec5SDimitry Andric       case Instruction::ICmp:
26350b57cec5SDimitry Andric       case Instruction::FCmp:
26360b57cec5SDimitry Andric         Code = bitc::CST_CODE_CE_CMP;
26370b57cec5SDimitry Andric         Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
26380b57cec5SDimitry Andric         Record.push_back(VE.getValueID(C->getOperand(0)));
26390b57cec5SDimitry Andric         Record.push_back(VE.getValueID(C->getOperand(1)));
26400b57cec5SDimitry Andric         Record.push_back(CE->getPredicate());
26410b57cec5SDimitry Andric         break;
26420b57cec5SDimitry Andric       }
26430b57cec5SDimitry Andric     } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) {
26440b57cec5SDimitry Andric       Code = bitc::CST_CODE_BLOCKADDRESS;
26450b57cec5SDimitry Andric       Record.push_back(VE.getTypeID(BA->getFunction()->getType()));
26460b57cec5SDimitry Andric       Record.push_back(VE.getValueID(BA->getFunction()));
26470b57cec5SDimitry Andric       Record.push_back(VE.getGlobalBasicBlockID(BA->getBasicBlock()));
2648*5f7ddb14SDimitry Andric     } else if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C)) {
2649*5f7ddb14SDimitry Andric       Code = bitc::CST_CODE_DSO_LOCAL_EQUIVALENT;
2650*5f7ddb14SDimitry Andric       Record.push_back(VE.getTypeID(Equiv->getGlobalValue()->getType()));
2651*5f7ddb14SDimitry Andric       Record.push_back(VE.getValueID(Equiv->getGlobalValue()));
26520b57cec5SDimitry Andric     } else {
26530b57cec5SDimitry Andric #ifndef NDEBUG
26540b57cec5SDimitry Andric       C->dump();
26550b57cec5SDimitry Andric #endif
26560b57cec5SDimitry Andric       llvm_unreachable("Unknown constant!");
26570b57cec5SDimitry Andric     }
26580b57cec5SDimitry Andric     Stream.EmitRecord(Code, Record, AbbrevToUse);
26590b57cec5SDimitry Andric     Record.clear();
26600b57cec5SDimitry Andric   }
26610b57cec5SDimitry Andric 
26620b57cec5SDimitry Andric   Stream.ExitBlock();
26630b57cec5SDimitry Andric }
26640b57cec5SDimitry Andric 
writeModuleConstants()26650b57cec5SDimitry Andric void ModuleBitcodeWriter::writeModuleConstants() {
26660b57cec5SDimitry Andric   const ValueEnumerator::ValueList &Vals = VE.getValues();
26670b57cec5SDimitry Andric 
26680b57cec5SDimitry Andric   // Find the first constant to emit, which is the first non-globalvalue value.
26690b57cec5SDimitry Andric   // We know globalvalues have been emitted by WriteModuleInfo.
26700b57cec5SDimitry Andric   for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
26710b57cec5SDimitry Andric     if (!isa<GlobalValue>(Vals[i].first)) {
26720b57cec5SDimitry Andric       writeConstants(i, Vals.size(), true);
26730b57cec5SDimitry Andric       return;
26740b57cec5SDimitry Andric     }
26750b57cec5SDimitry Andric   }
26760b57cec5SDimitry Andric }
26770b57cec5SDimitry Andric 
26780b57cec5SDimitry Andric /// pushValueAndType - The file has to encode both the value and type id for
26790b57cec5SDimitry Andric /// many values, because we need to know what type to create for forward
26800b57cec5SDimitry Andric /// references.  However, most operands are not forward references, so this type
26810b57cec5SDimitry Andric /// field is not needed.
26820b57cec5SDimitry Andric ///
26830b57cec5SDimitry Andric /// This function adds V's value ID to Vals.  If the value ID is higher than the
26840b57cec5SDimitry Andric /// instruction ID, then it is a forward reference, and it also includes the
26850b57cec5SDimitry Andric /// type ID.  The value ID that is written is encoded relative to the InstID.
pushValueAndType(const Value * V,unsigned InstID,SmallVectorImpl<unsigned> & Vals)26860b57cec5SDimitry Andric bool ModuleBitcodeWriter::pushValueAndType(const Value *V, unsigned InstID,
26870b57cec5SDimitry Andric                                            SmallVectorImpl<unsigned> &Vals) {
26880b57cec5SDimitry Andric   unsigned ValID = VE.getValueID(V);
26890b57cec5SDimitry Andric   // Make encoding relative to the InstID.
26900b57cec5SDimitry Andric   Vals.push_back(InstID - ValID);
26910b57cec5SDimitry Andric   if (ValID >= InstID) {
26920b57cec5SDimitry Andric     Vals.push_back(VE.getTypeID(V->getType()));
26930b57cec5SDimitry Andric     return true;
26940b57cec5SDimitry Andric   }
26950b57cec5SDimitry Andric   return false;
26960b57cec5SDimitry Andric }
26970b57cec5SDimitry Andric 
writeOperandBundles(const CallBase & CS,unsigned InstID)26985ffd83dbSDimitry Andric void ModuleBitcodeWriter::writeOperandBundles(const CallBase &CS,
26990b57cec5SDimitry Andric                                               unsigned InstID) {
27000b57cec5SDimitry Andric   SmallVector<unsigned, 64> Record;
27015ffd83dbSDimitry Andric   LLVMContext &C = CS.getContext();
27020b57cec5SDimitry Andric 
27030b57cec5SDimitry Andric   for (unsigned i = 0, e = CS.getNumOperandBundles(); i != e; ++i) {
27040b57cec5SDimitry Andric     const auto &Bundle = CS.getOperandBundleAt(i);
27050b57cec5SDimitry Andric     Record.push_back(C.getOperandBundleTagID(Bundle.getTagName()));
27060b57cec5SDimitry Andric 
27070b57cec5SDimitry Andric     for (auto &Input : Bundle.Inputs)
27080b57cec5SDimitry Andric       pushValueAndType(Input, InstID, Record);
27090b57cec5SDimitry Andric 
27100b57cec5SDimitry Andric     Stream.EmitRecord(bitc::FUNC_CODE_OPERAND_BUNDLE, Record);
27110b57cec5SDimitry Andric     Record.clear();
27120b57cec5SDimitry Andric   }
27130b57cec5SDimitry Andric }
27140b57cec5SDimitry Andric 
27150b57cec5SDimitry Andric /// pushValue - Like pushValueAndType, but where the type of the value is
27160b57cec5SDimitry Andric /// omitted (perhaps it was already encoded in an earlier operand).
pushValue(const Value * V,unsigned InstID,SmallVectorImpl<unsigned> & Vals)27170b57cec5SDimitry Andric void ModuleBitcodeWriter::pushValue(const Value *V, unsigned InstID,
27180b57cec5SDimitry Andric                                     SmallVectorImpl<unsigned> &Vals) {
27190b57cec5SDimitry Andric   unsigned ValID = VE.getValueID(V);
27200b57cec5SDimitry Andric   Vals.push_back(InstID - ValID);
27210b57cec5SDimitry Andric }
27220b57cec5SDimitry Andric 
pushValueSigned(const Value * V,unsigned InstID,SmallVectorImpl<uint64_t> & Vals)27230b57cec5SDimitry Andric void ModuleBitcodeWriter::pushValueSigned(const Value *V, unsigned InstID,
27240b57cec5SDimitry Andric                                           SmallVectorImpl<uint64_t> &Vals) {
27250b57cec5SDimitry Andric   unsigned ValID = VE.getValueID(V);
27260b57cec5SDimitry Andric   int64_t diff = ((int32_t)InstID - (int32_t)ValID);
27270b57cec5SDimitry Andric   emitSignedInt64(Vals, diff);
27280b57cec5SDimitry Andric }
27290b57cec5SDimitry Andric 
27300b57cec5SDimitry Andric /// WriteInstruction - Emit an instruction to the specified stream.
writeInstruction(const Instruction & I,unsigned InstID,SmallVectorImpl<unsigned> & Vals)27310b57cec5SDimitry Andric void ModuleBitcodeWriter::writeInstruction(const Instruction &I,
27320b57cec5SDimitry Andric                                            unsigned InstID,
27330b57cec5SDimitry Andric                                            SmallVectorImpl<unsigned> &Vals) {
27340b57cec5SDimitry Andric   unsigned Code = 0;
27350b57cec5SDimitry Andric   unsigned AbbrevToUse = 0;
27360b57cec5SDimitry Andric   VE.setInstructionID(&I);
27370b57cec5SDimitry Andric   switch (I.getOpcode()) {
27380b57cec5SDimitry Andric   default:
27390b57cec5SDimitry Andric     if (Instruction::isCast(I.getOpcode())) {
27400b57cec5SDimitry Andric       Code = bitc::FUNC_CODE_INST_CAST;
27410b57cec5SDimitry Andric       if (!pushValueAndType(I.getOperand(0), InstID, Vals))
27420b57cec5SDimitry Andric         AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
27430b57cec5SDimitry Andric       Vals.push_back(VE.getTypeID(I.getType()));
27440b57cec5SDimitry Andric       Vals.push_back(getEncodedCastOpcode(I.getOpcode()));
27450b57cec5SDimitry Andric     } else {
27460b57cec5SDimitry Andric       assert(isa<BinaryOperator>(I) && "Unknown instruction!");
27470b57cec5SDimitry Andric       Code = bitc::FUNC_CODE_INST_BINOP;
27480b57cec5SDimitry Andric       if (!pushValueAndType(I.getOperand(0), InstID, Vals))
27490b57cec5SDimitry Andric         AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
27500b57cec5SDimitry Andric       pushValue(I.getOperand(1), InstID, Vals);
27510b57cec5SDimitry Andric       Vals.push_back(getEncodedBinaryOpcode(I.getOpcode()));
27520b57cec5SDimitry Andric       uint64_t Flags = getOptimizationFlags(&I);
27530b57cec5SDimitry Andric       if (Flags != 0) {
27540b57cec5SDimitry Andric         if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV)
27550b57cec5SDimitry Andric           AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV;
27560b57cec5SDimitry Andric         Vals.push_back(Flags);
27570b57cec5SDimitry Andric       }
27580b57cec5SDimitry Andric     }
27590b57cec5SDimitry Andric     break;
27600b57cec5SDimitry Andric   case Instruction::FNeg: {
27610b57cec5SDimitry Andric     Code = bitc::FUNC_CODE_INST_UNOP;
27620b57cec5SDimitry Andric     if (!pushValueAndType(I.getOperand(0), InstID, Vals))
27630b57cec5SDimitry Andric       AbbrevToUse = FUNCTION_INST_UNOP_ABBREV;
27640b57cec5SDimitry Andric     Vals.push_back(getEncodedUnaryOpcode(I.getOpcode()));
27650b57cec5SDimitry Andric     uint64_t Flags = getOptimizationFlags(&I);
27660b57cec5SDimitry Andric     if (Flags != 0) {
27670b57cec5SDimitry Andric       if (AbbrevToUse == FUNCTION_INST_UNOP_ABBREV)
27680b57cec5SDimitry Andric         AbbrevToUse = FUNCTION_INST_UNOP_FLAGS_ABBREV;
27690b57cec5SDimitry Andric       Vals.push_back(Flags);
27700b57cec5SDimitry Andric     }
27710b57cec5SDimitry Andric     break;
27720b57cec5SDimitry Andric   }
27730b57cec5SDimitry Andric   case Instruction::GetElementPtr: {
27740b57cec5SDimitry Andric     Code = bitc::FUNC_CODE_INST_GEP;
27750b57cec5SDimitry Andric     AbbrevToUse = FUNCTION_INST_GEP_ABBREV;
27760b57cec5SDimitry Andric     auto &GEPInst = cast<GetElementPtrInst>(I);
27770b57cec5SDimitry Andric     Vals.push_back(GEPInst.isInBounds());
27780b57cec5SDimitry Andric     Vals.push_back(VE.getTypeID(GEPInst.getSourceElementType()));
27790b57cec5SDimitry Andric     for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
27800b57cec5SDimitry Andric       pushValueAndType(I.getOperand(i), InstID, Vals);
27810b57cec5SDimitry Andric     break;
27820b57cec5SDimitry Andric   }
27830b57cec5SDimitry Andric   case Instruction::ExtractValue: {
27840b57cec5SDimitry Andric     Code = bitc::FUNC_CODE_INST_EXTRACTVAL;
27850b57cec5SDimitry Andric     pushValueAndType(I.getOperand(0), InstID, Vals);
27860b57cec5SDimitry Andric     const ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
27870b57cec5SDimitry Andric     Vals.append(EVI->idx_begin(), EVI->idx_end());
27880b57cec5SDimitry Andric     break;
27890b57cec5SDimitry Andric   }
27900b57cec5SDimitry Andric   case Instruction::InsertValue: {
27910b57cec5SDimitry Andric     Code = bitc::FUNC_CODE_INST_INSERTVAL;
27920b57cec5SDimitry Andric     pushValueAndType(I.getOperand(0), InstID, Vals);
27930b57cec5SDimitry Andric     pushValueAndType(I.getOperand(1), InstID, Vals);
27940b57cec5SDimitry Andric     const InsertValueInst *IVI = cast<InsertValueInst>(&I);
27950b57cec5SDimitry Andric     Vals.append(IVI->idx_begin(), IVI->idx_end());
27960b57cec5SDimitry Andric     break;
27970b57cec5SDimitry Andric   }
27980b57cec5SDimitry Andric   case Instruction::Select: {
27990b57cec5SDimitry Andric     Code = bitc::FUNC_CODE_INST_VSELECT;
28000b57cec5SDimitry Andric     pushValueAndType(I.getOperand(1), InstID, Vals);
28010b57cec5SDimitry Andric     pushValue(I.getOperand(2), InstID, Vals);
28020b57cec5SDimitry Andric     pushValueAndType(I.getOperand(0), InstID, Vals);
28030b57cec5SDimitry Andric     uint64_t Flags = getOptimizationFlags(&I);
28040b57cec5SDimitry Andric     if (Flags != 0)
28050b57cec5SDimitry Andric       Vals.push_back(Flags);
28060b57cec5SDimitry Andric     break;
28070b57cec5SDimitry Andric   }
28080b57cec5SDimitry Andric   case Instruction::ExtractElement:
28090b57cec5SDimitry Andric     Code = bitc::FUNC_CODE_INST_EXTRACTELT;
28100b57cec5SDimitry Andric     pushValueAndType(I.getOperand(0), InstID, Vals);
28110b57cec5SDimitry Andric     pushValueAndType(I.getOperand(1), InstID, Vals);
28120b57cec5SDimitry Andric     break;
28130b57cec5SDimitry Andric   case Instruction::InsertElement:
28140b57cec5SDimitry Andric     Code = bitc::FUNC_CODE_INST_INSERTELT;
28150b57cec5SDimitry Andric     pushValueAndType(I.getOperand(0), InstID, Vals);
28160b57cec5SDimitry Andric     pushValue(I.getOperand(1), InstID, Vals);
28170b57cec5SDimitry Andric     pushValueAndType(I.getOperand(2), InstID, Vals);
28180b57cec5SDimitry Andric     break;
28190b57cec5SDimitry Andric   case Instruction::ShuffleVector:
28200b57cec5SDimitry Andric     Code = bitc::FUNC_CODE_INST_SHUFFLEVEC;
28210b57cec5SDimitry Andric     pushValueAndType(I.getOperand(0), InstID, Vals);
28220b57cec5SDimitry Andric     pushValue(I.getOperand(1), InstID, Vals);
28235ffd83dbSDimitry Andric     pushValue(cast<ShuffleVectorInst>(I).getShuffleMaskForBitcode(), InstID,
28245ffd83dbSDimitry Andric               Vals);
28250b57cec5SDimitry Andric     break;
28260b57cec5SDimitry Andric   case Instruction::ICmp:
28270b57cec5SDimitry Andric   case Instruction::FCmp: {
28280b57cec5SDimitry Andric     // compare returning Int1Ty or vector of Int1Ty
28290b57cec5SDimitry Andric     Code = bitc::FUNC_CODE_INST_CMP2;
28300b57cec5SDimitry Andric     pushValueAndType(I.getOperand(0), InstID, Vals);
28310b57cec5SDimitry Andric     pushValue(I.getOperand(1), InstID, Vals);
28320b57cec5SDimitry Andric     Vals.push_back(cast<CmpInst>(I).getPredicate());
28330b57cec5SDimitry Andric     uint64_t Flags = getOptimizationFlags(&I);
28340b57cec5SDimitry Andric     if (Flags != 0)
28350b57cec5SDimitry Andric       Vals.push_back(Flags);
28360b57cec5SDimitry Andric     break;
28370b57cec5SDimitry Andric   }
28380b57cec5SDimitry Andric 
28390b57cec5SDimitry Andric   case Instruction::Ret:
28400b57cec5SDimitry Andric     {
28410b57cec5SDimitry Andric       Code = bitc::FUNC_CODE_INST_RET;
28420b57cec5SDimitry Andric       unsigned NumOperands = I.getNumOperands();
28430b57cec5SDimitry Andric       if (NumOperands == 0)
28440b57cec5SDimitry Andric         AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
28450b57cec5SDimitry Andric       else if (NumOperands == 1) {
28460b57cec5SDimitry Andric         if (!pushValueAndType(I.getOperand(0), InstID, Vals))
28470b57cec5SDimitry Andric           AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
28480b57cec5SDimitry Andric       } else {
28490b57cec5SDimitry Andric         for (unsigned i = 0, e = NumOperands; i != e; ++i)
28500b57cec5SDimitry Andric           pushValueAndType(I.getOperand(i), InstID, Vals);
28510b57cec5SDimitry Andric       }
28520b57cec5SDimitry Andric     }
28530b57cec5SDimitry Andric     break;
28540b57cec5SDimitry Andric   case Instruction::Br:
28550b57cec5SDimitry Andric     {
28560b57cec5SDimitry Andric       Code = bitc::FUNC_CODE_INST_BR;
28570b57cec5SDimitry Andric       const BranchInst &II = cast<BranchInst>(I);
28580b57cec5SDimitry Andric       Vals.push_back(VE.getValueID(II.getSuccessor(0)));
28590b57cec5SDimitry Andric       if (II.isConditional()) {
28600b57cec5SDimitry Andric         Vals.push_back(VE.getValueID(II.getSuccessor(1)));
28610b57cec5SDimitry Andric         pushValue(II.getCondition(), InstID, Vals);
28620b57cec5SDimitry Andric       }
28630b57cec5SDimitry Andric     }
28640b57cec5SDimitry Andric     break;
28650b57cec5SDimitry Andric   case Instruction::Switch:
28660b57cec5SDimitry Andric     {
28670b57cec5SDimitry Andric       Code = bitc::FUNC_CODE_INST_SWITCH;
28680b57cec5SDimitry Andric       const SwitchInst &SI = cast<SwitchInst>(I);
28690b57cec5SDimitry Andric       Vals.push_back(VE.getTypeID(SI.getCondition()->getType()));
28700b57cec5SDimitry Andric       pushValue(SI.getCondition(), InstID, Vals);
28710b57cec5SDimitry Andric       Vals.push_back(VE.getValueID(SI.getDefaultDest()));
28720b57cec5SDimitry Andric       for (auto Case : SI.cases()) {
28730b57cec5SDimitry Andric         Vals.push_back(VE.getValueID(Case.getCaseValue()));
28740b57cec5SDimitry Andric         Vals.push_back(VE.getValueID(Case.getCaseSuccessor()));
28750b57cec5SDimitry Andric       }
28760b57cec5SDimitry Andric     }
28770b57cec5SDimitry Andric     break;
28780b57cec5SDimitry Andric   case Instruction::IndirectBr:
28790b57cec5SDimitry Andric     Code = bitc::FUNC_CODE_INST_INDIRECTBR;
28800b57cec5SDimitry Andric     Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
28810b57cec5SDimitry Andric     // Encode the address operand as relative, but not the basic blocks.
28820b57cec5SDimitry Andric     pushValue(I.getOperand(0), InstID, Vals);
28830b57cec5SDimitry Andric     for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i)
28840b57cec5SDimitry Andric       Vals.push_back(VE.getValueID(I.getOperand(i)));
28850b57cec5SDimitry Andric     break;
28860b57cec5SDimitry Andric 
28870b57cec5SDimitry Andric   case Instruction::Invoke: {
28880b57cec5SDimitry Andric     const InvokeInst *II = cast<InvokeInst>(&I);
28895ffd83dbSDimitry Andric     const Value *Callee = II->getCalledOperand();
28900b57cec5SDimitry Andric     FunctionType *FTy = II->getFunctionType();
28910b57cec5SDimitry Andric 
28920b57cec5SDimitry Andric     if (II->hasOperandBundles())
28935ffd83dbSDimitry Andric       writeOperandBundles(*II, InstID);
28940b57cec5SDimitry Andric 
28950b57cec5SDimitry Andric     Code = bitc::FUNC_CODE_INST_INVOKE;
28960b57cec5SDimitry Andric 
28970b57cec5SDimitry Andric     Vals.push_back(VE.getAttributeListID(II->getAttributes()));
28980b57cec5SDimitry Andric     Vals.push_back(II->getCallingConv() | 1 << 13);
28990b57cec5SDimitry Andric     Vals.push_back(VE.getValueID(II->getNormalDest()));
29000b57cec5SDimitry Andric     Vals.push_back(VE.getValueID(II->getUnwindDest()));
29010b57cec5SDimitry Andric     Vals.push_back(VE.getTypeID(FTy));
29020b57cec5SDimitry Andric     pushValueAndType(Callee, InstID, Vals);
29030b57cec5SDimitry Andric 
29040b57cec5SDimitry Andric     // Emit value #'s for the fixed parameters.
29050b57cec5SDimitry Andric     for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
29060b57cec5SDimitry Andric       pushValue(I.getOperand(i), InstID, Vals); // fixed param.
29070b57cec5SDimitry Andric 
29080b57cec5SDimitry Andric     // Emit type/value pairs for varargs params.
29090b57cec5SDimitry Andric     if (FTy->isVarArg()) {
29100b57cec5SDimitry Andric       for (unsigned i = FTy->getNumParams(), e = II->getNumArgOperands();
29110b57cec5SDimitry Andric            i != e; ++i)
29120b57cec5SDimitry Andric         pushValueAndType(I.getOperand(i), InstID, Vals); // vararg
29130b57cec5SDimitry Andric     }
29140b57cec5SDimitry Andric     break;
29150b57cec5SDimitry Andric   }
29160b57cec5SDimitry Andric   case Instruction::Resume:
29170b57cec5SDimitry Andric     Code = bitc::FUNC_CODE_INST_RESUME;
29180b57cec5SDimitry Andric     pushValueAndType(I.getOperand(0), InstID, Vals);
29190b57cec5SDimitry Andric     break;
29200b57cec5SDimitry Andric   case Instruction::CleanupRet: {
29210b57cec5SDimitry Andric     Code = bitc::FUNC_CODE_INST_CLEANUPRET;
29220b57cec5SDimitry Andric     const auto &CRI = cast<CleanupReturnInst>(I);
29230b57cec5SDimitry Andric     pushValue(CRI.getCleanupPad(), InstID, Vals);
29240b57cec5SDimitry Andric     if (CRI.hasUnwindDest())
29250b57cec5SDimitry Andric       Vals.push_back(VE.getValueID(CRI.getUnwindDest()));
29260b57cec5SDimitry Andric     break;
29270b57cec5SDimitry Andric   }
29280b57cec5SDimitry Andric   case Instruction::CatchRet: {
29290b57cec5SDimitry Andric     Code = bitc::FUNC_CODE_INST_CATCHRET;
29300b57cec5SDimitry Andric     const auto &CRI = cast<CatchReturnInst>(I);
29310b57cec5SDimitry Andric     pushValue(CRI.getCatchPad(), InstID, Vals);
29320b57cec5SDimitry Andric     Vals.push_back(VE.getValueID(CRI.getSuccessor()));
29330b57cec5SDimitry Andric     break;
29340b57cec5SDimitry Andric   }
29350b57cec5SDimitry Andric   case Instruction::CleanupPad:
29360b57cec5SDimitry Andric   case Instruction::CatchPad: {
29370b57cec5SDimitry Andric     const auto &FuncletPad = cast<FuncletPadInst>(I);
29380b57cec5SDimitry Andric     Code = isa<CatchPadInst>(FuncletPad) ? bitc::FUNC_CODE_INST_CATCHPAD
29390b57cec5SDimitry Andric                                          : bitc::FUNC_CODE_INST_CLEANUPPAD;
29400b57cec5SDimitry Andric     pushValue(FuncletPad.getParentPad(), InstID, Vals);
29410b57cec5SDimitry Andric 
29420b57cec5SDimitry Andric     unsigned NumArgOperands = FuncletPad.getNumArgOperands();
29430b57cec5SDimitry Andric     Vals.push_back(NumArgOperands);
29440b57cec5SDimitry Andric     for (unsigned Op = 0; Op != NumArgOperands; ++Op)
29450b57cec5SDimitry Andric       pushValueAndType(FuncletPad.getArgOperand(Op), InstID, Vals);
29460b57cec5SDimitry Andric     break;
29470b57cec5SDimitry Andric   }
29480b57cec5SDimitry Andric   case Instruction::CatchSwitch: {
29490b57cec5SDimitry Andric     Code = bitc::FUNC_CODE_INST_CATCHSWITCH;
29500b57cec5SDimitry Andric     const auto &CatchSwitch = cast<CatchSwitchInst>(I);
29510b57cec5SDimitry Andric 
29520b57cec5SDimitry Andric     pushValue(CatchSwitch.getParentPad(), InstID, Vals);
29530b57cec5SDimitry Andric 
29540b57cec5SDimitry Andric     unsigned NumHandlers = CatchSwitch.getNumHandlers();
29550b57cec5SDimitry Andric     Vals.push_back(NumHandlers);
29560b57cec5SDimitry Andric     for (const BasicBlock *CatchPadBB : CatchSwitch.handlers())
29570b57cec5SDimitry Andric       Vals.push_back(VE.getValueID(CatchPadBB));
29580b57cec5SDimitry Andric 
29590b57cec5SDimitry Andric     if (CatchSwitch.hasUnwindDest())
29600b57cec5SDimitry Andric       Vals.push_back(VE.getValueID(CatchSwitch.getUnwindDest()));
29610b57cec5SDimitry Andric     break;
29620b57cec5SDimitry Andric   }
29630b57cec5SDimitry Andric   case Instruction::CallBr: {
29640b57cec5SDimitry Andric     const CallBrInst *CBI = cast<CallBrInst>(&I);
29655ffd83dbSDimitry Andric     const Value *Callee = CBI->getCalledOperand();
29660b57cec5SDimitry Andric     FunctionType *FTy = CBI->getFunctionType();
29670b57cec5SDimitry Andric 
29680b57cec5SDimitry Andric     if (CBI->hasOperandBundles())
29695ffd83dbSDimitry Andric       writeOperandBundles(*CBI, InstID);
29700b57cec5SDimitry Andric 
29710b57cec5SDimitry Andric     Code = bitc::FUNC_CODE_INST_CALLBR;
29720b57cec5SDimitry Andric 
29730b57cec5SDimitry Andric     Vals.push_back(VE.getAttributeListID(CBI->getAttributes()));
29740b57cec5SDimitry Andric 
29750b57cec5SDimitry Andric     Vals.push_back(CBI->getCallingConv() << bitc::CALL_CCONV |
29760b57cec5SDimitry Andric                    1 << bitc::CALL_EXPLICIT_TYPE);
29770b57cec5SDimitry Andric 
29780b57cec5SDimitry Andric     Vals.push_back(VE.getValueID(CBI->getDefaultDest()));
29790b57cec5SDimitry Andric     Vals.push_back(CBI->getNumIndirectDests());
29800b57cec5SDimitry Andric     for (unsigned i = 0, e = CBI->getNumIndirectDests(); i != e; ++i)
29810b57cec5SDimitry Andric       Vals.push_back(VE.getValueID(CBI->getIndirectDest(i)));
29820b57cec5SDimitry Andric 
29830b57cec5SDimitry Andric     Vals.push_back(VE.getTypeID(FTy));
29840b57cec5SDimitry Andric     pushValueAndType(Callee, InstID, Vals);
29850b57cec5SDimitry Andric 
29860b57cec5SDimitry Andric     // Emit value #'s for the fixed parameters.
29870b57cec5SDimitry Andric     for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
29880b57cec5SDimitry Andric       pushValue(I.getOperand(i), InstID, Vals); // fixed param.
29890b57cec5SDimitry Andric 
29900b57cec5SDimitry Andric     // Emit type/value pairs for varargs params.
29910b57cec5SDimitry Andric     if (FTy->isVarArg()) {
29920b57cec5SDimitry Andric       for (unsigned i = FTy->getNumParams(), e = CBI->getNumArgOperands();
29930b57cec5SDimitry Andric            i != e; ++i)
29940b57cec5SDimitry Andric         pushValueAndType(I.getOperand(i), InstID, Vals); // vararg
29950b57cec5SDimitry Andric     }
29960b57cec5SDimitry Andric     break;
29970b57cec5SDimitry Andric   }
29980b57cec5SDimitry Andric   case Instruction::Unreachable:
29990b57cec5SDimitry Andric     Code = bitc::FUNC_CODE_INST_UNREACHABLE;
30000b57cec5SDimitry Andric     AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
30010b57cec5SDimitry Andric     break;
30020b57cec5SDimitry Andric 
30030b57cec5SDimitry Andric   case Instruction::PHI: {
30040b57cec5SDimitry Andric     const PHINode &PN = cast<PHINode>(I);
30050b57cec5SDimitry Andric     Code = bitc::FUNC_CODE_INST_PHI;
30060b57cec5SDimitry Andric     // With the newer instruction encoding, forward references could give
30070b57cec5SDimitry Andric     // negative valued IDs.  This is most common for PHIs, so we use
30080b57cec5SDimitry Andric     // signed VBRs.
30090b57cec5SDimitry Andric     SmallVector<uint64_t, 128> Vals64;
30100b57cec5SDimitry Andric     Vals64.push_back(VE.getTypeID(PN.getType()));
30110b57cec5SDimitry Andric     for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
30120b57cec5SDimitry Andric       pushValueSigned(PN.getIncomingValue(i), InstID, Vals64);
30130b57cec5SDimitry Andric       Vals64.push_back(VE.getValueID(PN.getIncomingBlock(i)));
30140b57cec5SDimitry Andric     }
30158bcb0991SDimitry Andric 
30168bcb0991SDimitry Andric     uint64_t Flags = getOptimizationFlags(&I);
30178bcb0991SDimitry Andric     if (Flags != 0)
30188bcb0991SDimitry Andric       Vals64.push_back(Flags);
30198bcb0991SDimitry Andric 
30200b57cec5SDimitry Andric     // Emit a Vals64 vector and exit.
30210b57cec5SDimitry Andric     Stream.EmitRecord(Code, Vals64, AbbrevToUse);
30220b57cec5SDimitry Andric     Vals64.clear();
30230b57cec5SDimitry Andric     return;
30240b57cec5SDimitry Andric   }
30250b57cec5SDimitry Andric 
30260b57cec5SDimitry Andric   case Instruction::LandingPad: {
30270b57cec5SDimitry Andric     const LandingPadInst &LP = cast<LandingPadInst>(I);
30280b57cec5SDimitry Andric     Code = bitc::FUNC_CODE_INST_LANDINGPAD;
30290b57cec5SDimitry Andric     Vals.push_back(VE.getTypeID(LP.getType()));
30300b57cec5SDimitry Andric     Vals.push_back(LP.isCleanup());
30310b57cec5SDimitry Andric     Vals.push_back(LP.getNumClauses());
30320b57cec5SDimitry Andric     for (unsigned I = 0, E = LP.getNumClauses(); I != E; ++I) {
30330b57cec5SDimitry Andric       if (LP.isCatch(I))
30340b57cec5SDimitry Andric         Vals.push_back(LandingPadInst::Catch);
30350b57cec5SDimitry Andric       else
30360b57cec5SDimitry Andric         Vals.push_back(LandingPadInst::Filter);
30370b57cec5SDimitry Andric       pushValueAndType(LP.getClause(I), InstID, Vals);
30380b57cec5SDimitry Andric     }
30390b57cec5SDimitry Andric     break;
30400b57cec5SDimitry Andric   }
30410b57cec5SDimitry Andric 
30420b57cec5SDimitry Andric   case Instruction::Alloca: {
30430b57cec5SDimitry Andric     Code = bitc::FUNC_CODE_INST_ALLOCA;
30440b57cec5SDimitry Andric     const AllocaInst &AI = cast<AllocaInst>(I);
30450b57cec5SDimitry Andric     Vals.push_back(VE.getTypeID(AI.getAllocatedType()));
30460b57cec5SDimitry Andric     Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
30470b57cec5SDimitry Andric     Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
3048af732203SDimitry Andric     using APV = AllocaPackedValues;
3049af732203SDimitry Andric     unsigned Record = 0;
3050af732203SDimitry Andric     Bitfield::set<APV::Align>(Record, getEncodedAlign(AI.getAlign()));
3051af732203SDimitry Andric     Bitfield::set<APV::UsedWithInAlloca>(Record, AI.isUsedWithInAlloca());
3052af732203SDimitry Andric     Bitfield::set<APV::ExplicitType>(Record, true);
3053af732203SDimitry Andric     Bitfield::set<APV::SwiftError>(Record, AI.isSwiftError());
3054af732203SDimitry Andric     Vals.push_back(Record);
30550b57cec5SDimitry Andric     break;
30560b57cec5SDimitry Andric   }
30570b57cec5SDimitry Andric 
30580b57cec5SDimitry Andric   case Instruction::Load:
30590b57cec5SDimitry Andric     if (cast<LoadInst>(I).isAtomic()) {
30600b57cec5SDimitry Andric       Code = bitc::FUNC_CODE_INST_LOADATOMIC;
30610b57cec5SDimitry Andric       pushValueAndType(I.getOperand(0), InstID, Vals);
30620b57cec5SDimitry Andric     } else {
30630b57cec5SDimitry Andric       Code = bitc::FUNC_CODE_INST_LOAD;
30640b57cec5SDimitry Andric       if (!pushValueAndType(I.getOperand(0), InstID, Vals)) // ptr
30650b57cec5SDimitry Andric         AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
30660b57cec5SDimitry Andric     }
30670b57cec5SDimitry Andric     Vals.push_back(VE.getTypeID(I.getType()));
3068af732203SDimitry Andric     Vals.push_back(getEncodedAlign(cast<LoadInst>(I).getAlign()));
30690b57cec5SDimitry Andric     Vals.push_back(cast<LoadInst>(I).isVolatile());
30700b57cec5SDimitry Andric     if (cast<LoadInst>(I).isAtomic()) {
30710b57cec5SDimitry Andric       Vals.push_back(getEncodedOrdering(cast<LoadInst>(I).getOrdering()));
30720b57cec5SDimitry Andric       Vals.push_back(getEncodedSyncScopeID(cast<LoadInst>(I).getSyncScopeID()));
30730b57cec5SDimitry Andric     }
30740b57cec5SDimitry Andric     break;
30750b57cec5SDimitry Andric   case Instruction::Store:
30760b57cec5SDimitry Andric     if (cast<StoreInst>(I).isAtomic())
30770b57cec5SDimitry Andric       Code = bitc::FUNC_CODE_INST_STOREATOMIC;
30780b57cec5SDimitry Andric     else
30790b57cec5SDimitry Andric       Code = bitc::FUNC_CODE_INST_STORE;
30800b57cec5SDimitry Andric     pushValueAndType(I.getOperand(1), InstID, Vals); // ptrty + ptr
30810b57cec5SDimitry Andric     pushValueAndType(I.getOperand(0), InstID, Vals); // valty + val
3082af732203SDimitry Andric     Vals.push_back(getEncodedAlign(cast<StoreInst>(I).getAlign()));
30830b57cec5SDimitry Andric     Vals.push_back(cast<StoreInst>(I).isVolatile());
30840b57cec5SDimitry Andric     if (cast<StoreInst>(I).isAtomic()) {
30850b57cec5SDimitry Andric       Vals.push_back(getEncodedOrdering(cast<StoreInst>(I).getOrdering()));
30860b57cec5SDimitry Andric       Vals.push_back(
30870b57cec5SDimitry Andric           getEncodedSyncScopeID(cast<StoreInst>(I).getSyncScopeID()));
30880b57cec5SDimitry Andric     }
30890b57cec5SDimitry Andric     break;
30900b57cec5SDimitry Andric   case Instruction::AtomicCmpXchg:
30910b57cec5SDimitry Andric     Code = bitc::FUNC_CODE_INST_CMPXCHG;
30920b57cec5SDimitry Andric     pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr
30930b57cec5SDimitry Andric     pushValueAndType(I.getOperand(1), InstID, Vals); // cmp.
30940b57cec5SDimitry Andric     pushValue(I.getOperand(2), InstID, Vals);        // newval.
30950b57cec5SDimitry Andric     Vals.push_back(cast<AtomicCmpXchgInst>(I).isVolatile());
30960b57cec5SDimitry Andric     Vals.push_back(
30970b57cec5SDimitry Andric         getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getSuccessOrdering()));
30980b57cec5SDimitry Andric     Vals.push_back(
30990b57cec5SDimitry Andric         getEncodedSyncScopeID(cast<AtomicCmpXchgInst>(I).getSyncScopeID()));
31000b57cec5SDimitry Andric     Vals.push_back(
31010b57cec5SDimitry Andric         getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getFailureOrdering()));
31020b57cec5SDimitry Andric     Vals.push_back(cast<AtomicCmpXchgInst>(I).isWeak());
3103*5f7ddb14SDimitry Andric     Vals.push_back(getEncodedAlign(cast<AtomicCmpXchgInst>(I).getAlign()));
31040b57cec5SDimitry Andric     break;
31050b57cec5SDimitry Andric   case Instruction::AtomicRMW:
31060b57cec5SDimitry Andric     Code = bitc::FUNC_CODE_INST_ATOMICRMW;
31070b57cec5SDimitry Andric     pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr
3108*5f7ddb14SDimitry Andric     pushValueAndType(I.getOperand(1), InstID, Vals); // valty + val
31090b57cec5SDimitry Andric     Vals.push_back(
31100b57cec5SDimitry Andric         getEncodedRMWOperation(cast<AtomicRMWInst>(I).getOperation()));
31110b57cec5SDimitry Andric     Vals.push_back(cast<AtomicRMWInst>(I).isVolatile());
31120b57cec5SDimitry Andric     Vals.push_back(getEncodedOrdering(cast<AtomicRMWInst>(I).getOrdering()));
31130b57cec5SDimitry Andric     Vals.push_back(
31140b57cec5SDimitry Andric         getEncodedSyncScopeID(cast<AtomicRMWInst>(I).getSyncScopeID()));
3115*5f7ddb14SDimitry Andric     Vals.push_back(getEncodedAlign(cast<AtomicRMWInst>(I).getAlign()));
31160b57cec5SDimitry Andric     break;
31170b57cec5SDimitry Andric   case Instruction::Fence:
31180b57cec5SDimitry Andric     Code = bitc::FUNC_CODE_INST_FENCE;
31190b57cec5SDimitry Andric     Vals.push_back(getEncodedOrdering(cast<FenceInst>(I).getOrdering()));
31200b57cec5SDimitry Andric     Vals.push_back(getEncodedSyncScopeID(cast<FenceInst>(I).getSyncScopeID()));
31210b57cec5SDimitry Andric     break;
31220b57cec5SDimitry Andric   case Instruction::Call: {
31230b57cec5SDimitry Andric     const CallInst &CI = cast<CallInst>(I);
31240b57cec5SDimitry Andric     FunctionType *FTy = CI.getFunctionType();
31250b57cec5SDimitry Andric 
31260b57cec5SDimitry Andric     if (CI.hasOperandBundles())
31275ffd83dbSDimitry Andric       writeOperandBundles(CI, InstID);
31280b57cec5SDimitry Andric 
31290b57cec5SDimitry Andric     Code = bitc::FUNC_CODE_INST_CALL;
31300b57cec5SDimitry Andric 
31310b57cec5SDimitry Andric     Vals.push_back(VE.getAttributeListID(CI.getAttributes()));
31320b57cec5SDimitry Andric 
31330b57cec5SDimitry Andric     unsigned Flags = getOptimizationFlags(&I);
31340b57cec5SDimitry Andric     Vals.push_back(CI.getCallingConv() << bitc::CALL_CCONV |
31350b57cec5SDimitry Andric                    unsigned(CI.isTailCall()) << bitc::CALL_TAIL |
31360b57cec5SDimitry Andric                    unsigned(CI.isMustTailCall()) << bitc::CALL_MUSTTAIL |
31370b57cec5SDimitry Andric                    1 << bitc::CALL_EXPLICIT_TYPE |
31380b57cec5SDimitry Andric                    unsigned(CI.isNoTailCall()) << bitc::CALL_NOTAIL |
31390b57cec5SDimitry Andric                    unsigned(Flags != 0) << bitc::CALL_FMF);
31400b57cec5SDimitry Andric     if (Flags != 0)
31410b57cec5SDimitry Andric       Vals.push_back(Flags);
31420b57cec5SDimitry Andric 
31430b57cec5SDimitry Andric     Vals.push_back(VE.getTypeID(FTy));
31445ffd83dbSDimitry Andric     pushValueAndType(CI.getCalledOperand(), InstID, Vals); // Callee
31450b57cec5SDimitry Andric 
31460b57cec5SDimitry Andric     // Emit value #'s for the fixed parameters.
31470b57cec5SDimitry Andric     for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
31480b57cec5SDimitry Andric       // Check for labels (can happen with asm labels).
31490b57cec5SDimitry Andric       if (FTy->getParamType(i)->isLabelTy())
31500b57cec5SDimitry Andric         Vals.push_back(VE.getValueID(CI.getArgOperand(i)));
31510b57cec5SDimitry Andric       else
31520b57cec5SDimitry Andric         pushValue(CI.getArgOperand(i), InstID, Vals); // fixed param.
31530b57cec5SDimitry Andric     }
31540b57cec5SDimitry Andric 
31550b57cec5SDimitry Andric     // Emit type/value pairs for varargs params.
31560b57cec5SDimitry Andric     if (FTy->isVarArg()) {
31570b57cec5SDimitry Andric       for (unsigned i = FTy->getNumParams(), e = CI.getNumArgOperands();
31580b57cec5SDimitry Andric            i != e; ++i)
31590b57cec5SDimitry Andric         pushValueAndType(CI.getArgOperand(i), InstID, Vals); // varargs
31600b57cec5SDimitry Andric     }
31610b57cec5SDimitry Andric     break;
31620b57cec5SDimitry Andric   }
31630b57cec5SDimitry Andric   case Instruction::VAArg:
31640b57cec5SDimitry Andric     Code = bitc::FUNC_CODE_INST_VAARG;
31650b57cec5SDimitry Andric     Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));   // valistty
31660b57cec5SDimitry Andric     pushValue(I.getOperand(0), InstID, Vals);                   // valist.
31670b57cec5SDimitry Andric     Vals.push_back(VE.getTypeID(I.getType())); // restype.
31680b57cec5SDimitry Andric     break;
3169480093f4SDimitry Andric   case Instruction::Freeze:
3170480093f4SDimitry Andric     Code = bitc::FUNC_CODE_INST_FREEZE;
3171480093f4SDimitry Andric     pushValueAndType(I.getOperand(0), InstID, Vals);
3172480093f4SDimitry Andric     break;
31730b57cec5SDimitry Andric   }
31740b57cec5SDimitry Andric 
31750b57cec5SDimitry Andric   Stream.EmitRecord(Code, Vals, AbbrevToUse);
31760b57cec5SDimitry Andric   Vals.clear();
31770b57cec5SDimitry Andric }
31780b57cec5SDimitry Andric 
31790b57cec5SDimitry Andric /// Write a GlobalValue VST to the module. The purpose of this data structure is
31800b57cec5SDimitry Andric /// to allow clients to efficiently find the function body.
writeGlobalValueSymbolTable(DenseMap<const Function *,uint64_t> & FunctionToBitcodeIndex)31810b57cec5SDimitry Andric void ModuleBitcodeWriter::writeGlobalValueSymbolTable(
31820b57cec5SDimitry Andric   DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) {
31830b57cec5SDimitry Andric   // Get the offset of the VST we are writing, and backpatch it into
31840b57cec5SDimitry Andric   // the VST forward declaration record.
31850b57cec5SDimitry Andric   uint64_t VSTOffset = Stream.GetCurrentBitNo();
31860b57cec5SDimitry Andric   // The BitcodeStartBit was the stream offset of the identification block.
31870b57cec5SDimitry Andric   VSTOffset -= bitcodeStartBit();
31880b57cec5SDimitry Andric   assert((VSTOffset & 31) == 0 && "VST block not 32-bit aligned");
31890b57cec5SDimitry Andric   // Note that we add 1 here because the offset is relative to one word
31900b57cec5SDimitry Andric   // before the start of the identification block, which was historically
31910b57cec5SDimitry Andric   // always the start of the regular bitcode header.
31920b57cec5SDimitry Andric   Stream.BackpatchWord(VSTOffsetPlaceholder, VSTOffset / 32 + 1);
31930b57cec5SDimitry Andric 
31940b57cec5SDimitry Andric   Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
31950b57cec5SDimitry Andric 
31960b57cec5SDimitry Andric   auto Abbv = std::make_shared<BitCodeAbbrev>();
31970b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_FNENTRY));
31980b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
31990b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // funcoffset
32000b57cec5SDimitry Andric   unsigned FnEntryAbbrev = Stream.EmitAbbrev(std::move(Abbv));
32010b57cec5SDimitry Andric 
32020b57cec5SDimitry Andric   for (const Function &F : M) {
32030b57cec5SDimitry Andric     uint64_t Record[2];
32040b57cec5SDimitry Andric 
32050b57cec5SDimitry Andric     if (F.isDeclaration())
32060b57cec5SDimitry Andric       continue;
32070b57cec5SDimitry Andric 
32080b57cec5SDimitry Andric     Record[0] = VE.getValueID(&F);
32090b57cec5SDimitry Andric 
32100b57cec5SDimitry Andric     // Save the word offset of the function (from the start of the
32110b57cec5SDimitry Andric     // actual bitcode written to the stream).
32120b57cec5SDimitry Andric     uint64_t BitcodeIndex = FunctionToBitcodeIndex[&F] - bitcodeStartBit();
32130b57cec5SDimitry Andric     assert((BitcodeIndex & 31) == 0 && "function block not 32-bit aligned");
32140b57cec5SDimitry Andric     // Note that we add 1 here because the offset is relative to one word
32150b57cec5SDimitry Andric     // before the start of the identification block, which was historically
32160b57cec5SDimitry Andric     // always the start of the regular bitcode header.
32170b57cec5SDimitry Andric     Record[1] = BitcodeIndex / 32 + 1;
32180b57cec5SDimitry Andric 
32190b57cec5SDimitry Andric     Stream.EmitRecord(bitc::VST_CODE_FNENTRY, Record, FnEntryAbbrev);
32200b57cec5SDimitry Andric   }
32210b57cec5SDimitry Andric 
32220b57cec5SDimitry Andric   Stream.ExitBlock();
32230b57cec5SDimitry Andric }
32240b57cec5SDimitry Andric 
32250b57cec5SDimitry Andric /// Emit names for arguments, instructions and basic blocks in a function.
writeFunctionLevelValueSymbolTable(const ValueSymbolTable & VST)32260b57cec5SDimitry Andric void ModuleBitcodeWriter::writeFunctionLevelValueSymbolTable(
32270b57cec5SDimitry Andric     const ValueSymbolTable &VST) {
32280b57cec5SDimitry Andric   if (VST.empty())
32290b57cec5SDimitry Andric     return;
32300b57cec5SDimitry Andric 
32310b57cec5SDimitry Andric   Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
32320b57cec5SDimitry Andric 
32330b57cec5SDimitry Andric   // FIXME: Set up the abbrev, we know how many values there are!
32340b57cec5SDimitry Andric   // FIXME: We know if the type names can use 7-bit ascii.
32350b57cec5SDimitry Andric   SmallVector<uint64_t, 64> NameVals;
32360b57cec5SDimitry Andric 
32370b57cec5SDimitry Andric   for (const ValueName &Name : VST) {
32380b57cec5SDimitry Andric     // Figure out the encoding to use for the name.
32390b57cec5SDimitry Andric     StringEncoding Bits = getStringEncoding(Name.getKey());
32400b57cec5SDimitry Andric 
32410b57cec5SDimitry Andric     unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
32420b57cec5SDimitry Andric     NameVals.push_back(VE.getValueID(Name.getValue()));
32430b57cec5SDimitry Andric 
32440b57cec5SDimitry Andric     // VST_CODE_ENTRY:   [valueid, namechar x N]
32450b57cec5SDimitry Andric     // VST_CODE_BBENTRY: [bbid, namechar x N]
32460b57cec5SDimitry Andric     unsigned Code;
32470b57cec5SDimitry Andric     if (isa<BasicBlock>(Name.getValue())) {
32480b57cec5SDimitry Andric       Code = bitc::VST_CODE_BBENTRY;
32490b57cec5SDimitry Andric       if (Bits == SE_Char6)
32500b57cec5SDimitry Andric         AbbrevToUse = VST_BBENTRY_6_ABBREV;
32510b57cec5SDimitry Andric     } else {
32520b57cec5SDimitry Andric       Code = bitc::VST_CODE_ENTRY;
32530b57cec5SDimitry Andric       if (Bits == SE_Char6)
32540b57cec5SDimitry Andric         AbbrevToUse = VST_ENTRY_6_ABBREV;
32550b57cec5SDimitry Andric       else if (Bits == SE_Fixed7)
32560b57cec5SDimitry Andric         AbbrevToUse = VST_ENTRY_7_ABBREV;
32570b57cec5SDimitry Andric     }
32580b57cec5SDimitry Andric 
32590b57cec5SDimitry Andric     for (const auto P : Name.getKey())
32600b57cec5SDimitry Andric       NameVals.push_back((unsigned char)P);
32610b57cec5SDimitry Andric 
32620b57cec5SDimitry Andric     // Emit the finished record.
32630b57cec5SDimitry Andric     Stream.EmitRecord(Code, NameVals, AbbrevToUse);
32640b57cec5SDimitry Andric     NameVals.clear();
32650b57cec5SDimitry Andric   }
32660b57cec5SDimitry Andric 
32670b57cec5SDimitry Andric   Stream.ExitBlock();
32680b57cec5SDimitry Andric }
32690b57cec5SDimitry Andric 
writeUseList(UseListOrder && Order)32700b57cec5SDimitry Andric void ModuleBitcodeWriter::writeUseList(UseListOrder &&Order) {
32710b57cec5SDimitry Andric   assert(Order.Shuffle.size() >= 2 && "Shuffle too small");
32720b57cec5SDimitry Andric   unsigned Code;
32730b57cec5SDimitry Andric   if (isa<BasicBlock>(Order.V))
32740b57cec5SDimitry Andric     Code = bitc::USELIST_CODE_BB;
32750b57cec5SDimitry Andric   else
32760b57cec5SDimitry Andric     Code = bitc::USELIST_CODE_DEFAULT;
32770b57cec5SDimitry Andric 
32780b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record(Order.Shuffle.begin(), Order.Shuffle.end());
32790b57cec5SDimitry Andric   Record.push_back(VE.getValueID(Order.V));
32800b57cec5SDimitry Andric   Stream.EmitRecord(Code, Record);
32810b57cec5SDimitry Andric }
32820b57cec5SDimitry Andric 
writeUseListBlock(const Function * F)32830b57cec5SDimitry Andric void ModuleBitcodeWriter::writeUseListBlock(const Function *F) {
32840b57cec5SDimitry Andric   assert(VE.shouldPreserveUseListOrder() &&
32850b57cec5SDimitry Andric          "Expected to be preserving use-list order");
32860b57cec5SDimitry Andric 
32870b57cec5SDimitry Andric   auto hasMore = [&]() {
32880b57cec5SDimitry Andric     return !VE.UseListOrders.empty() && VE.UseListOrders.back().F == F;
32890b57cec5SDimitry Andric   };
32900b57cec5SDimitry Andric   if (!hasMore())
32910b57cec5SDimitry Andric     // Nothing to do.
32920b57cec5SDimitry Andric     return;
32930b57cec5SDimitry Andric 
32940b57cec5SDimitry Andric   Stream.EnterSubblock(bitc::USELIST_BLOCK_ID, 3);
32950b57cec5SDimitry Andric   while (hasMore()) {
32960b57cec5SDimitry Andric     writeUseList(std::move(VE.UseListOrders.back()));
32970b57cec5SDimitry Andric     VE.UseListOrders.pop_back();
32980b57cec5SDimitry Andric   }
32990b57cec5SDimitry Andric   Stream.ExitBlock();
33000b57cec5SDimitry Andric }
33010b57cec5SDimitry Andric 
33020b57cec5SDimitry Andric /// Emit a function body to the module stream.
writeFunction(const Function & F,DenseMap<const Function *,uint64_t> & FunctionToBitcodeIndex)33030b57cec5SDimitry Andric void ModuleBitcodeWriter::writeFunction(
33040b57cec5SDimitry Andric     const Function &F,
33050b57cec5SDimitry Andric     DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) {
33060b57cec5SDimitry Andric   // Save the bitcode index of the start of this function block for recording
33070b57cec5SDimitry Andric   // in the VST.
33080b57cec5SDimitry Andric   FunctionToBitcodeIndex[&F] = Stream.GetCurrentBitNo();
33090b57cec5SDimitry Andric 
33100b57cec5SDimitry Andric   Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 4);
33110b57cec5SDimitry Andric   VE.incorporateFunction(F);
33120b57cec5SDimitry Andric 
33130b57cec5SDimitry Andric   SmallVector<unsigned, 64> Vals;
33140b57cec5SDimitry Andric 
33150b57cec5SDimitry Andric   // Emit the number of basic blocks, so the reader can create them ahead of
33160b57cec5SDimitry Andric   // time.
33170b57cec5SDimitry Andric   Vals.push_back(VE.getBasicBlocks().size());
33180b57cec5SDimitry Andric   Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals);
33190b57cec5SDimitry Andric   Vals.clear();
33200b57cec5SDimitry Andric 
33210b57cec5SDimitry Andric   // If there are function-local constants, emit them now.
33220b57cec5SDimitry Andric   unsigned CstStart, CstEnd;
33230b57cec5SDimitry Andric   VE.getFunctionConstantRange(CstStart, CstEnd);
33240b57cec5SDimitry Andric   writeConstants(CstStart, CstEnd, false);
33250b57cec5SDimitry Andric 
33260b57cec5SDimitry Andric   // If there is function-local metadata, emit it now.
33270b57cec5SDimitry Andric   writeFunctionMetadata(F);
33280b57cec5SDimitry Andric 
33290b57cec5SDimitry Andric   // Keep a running idea of what the instruction ID is.
33300b57cec5SDimitry Andric   unsigned InstID = CstEnd;
33310b57cec5SDimitry Andric 
33320b57cec5SDimitry Andric   bool NeedsMetadataAttachment = F.hasMetadata();
33330b57cec5SDimitry Andric 
33340b57cec5SDimitry Andric   DILocation *LastDL = nullptr;
33350b57cec5SDimitry Andric   // Finally, emit all the instructions, in order.
33360b57cec5SDimitry Andric   for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
33370b57cec5SDimitry Andric     for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
33380b57cec5SDimitry Andric          I != E; ++I) {
33390b57cec5SDimitry Andric       writeInstruction(*I, InstID, Vals);
33400b57cec5SDimitry Andric 
33410b57cec5SDimitry Andric       if (!I->getType()->isVoidTy())
33420b57cec5SDimitry Andric         ++InstID;
33430b57cec5SDimitry Andric 
33440b57cec5SDimitry Andric       // If the instruction has metadata, write a metadata attachment later.
33450b57cec5SDimitry Andric       NeedsMetadataAttachment |= I->hasMetadataOtherThanDebugLoc();
33460b57cec5SDimitry Andric 
33470b57cec5SDimitry Andric       // If the instruction has a debug location, emit it.
33480b57cec5SDimitry Andric       DILocation *DL = I->getDebugLoc();
33490b57cec5SDimitry Andric       if (!DL)
33500b57cec5SDimitry Andric         continue;
33510b57cec5SDimitry Andric 
33520b57cec5SDimitry Andric       if (DL == LastDL) {
33530b57cec5SDimitry Andric         // Just repeat the same debug loc as last time.
33540b57cec5SDimitry Andric         Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC_AGAIN, Vals);
33550b57cec5SDimitry Andric         continue;
33560b57cec5SDimitry Andric       }
33570b57cec5SDimitry Andric 
33580b57cec5SDimitry Andric       Vals.push_back(DL->getLine());
33590b57cec5SDimitry Andric       Vals.push_back(DL->getColumn());
33600b57cec5SDimitry Andric       Vals.push_back(VE.getMetadataOrNullID(DL->getScope()));
33610b57cec5SDimitry Andric       Vals.push_back(VE.getMetadataOrNullID(DL->getInlinedAt()));
33620b57cec5SDimitry Andric       Vals.push_back(DL->isImplicitCode());
33630b57cec5SDimitry Andric       Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC, Vals);
33640b57cec5SDimitry Andric       Vals.clear();
33650b57cec5SDimitry Andric 
33660b57cec5SDimitry Andric       LastDL = DL;
33670b57cec5SDimitry Andric     }
33680b57cec5SDimitry Andric 
33690b57cec5SDimitry Andric   // Emit names for all the instructions etc.
33700b57cec5SDimitry Andric   if (auto *Symtab = F.getValueSymbolTable())
33710b57cec5SDimitry Andric     writeFunctionLevelValueSymbolTable(*Symtab);
33720b57cec5SDimitry Andric 
33730b57cec5SDimitry Andric   if (NeedsMetadataAttachment)
33740b57cec5SDimitry Andric     writeFunctionMetadataAttachment(F);
33750b57cec5SDimitry Andric   if (VE.shouldPreserveUseListOrder())
33760b57cec5SDimitry Andric     writeUseListBlock(&F);
33770b57cec5SDimitry Andric   VE.purgeFunction();
33780b57cec5SDimitry Andric   Stream.ExitBlock();
33790b57cec5SDimitry Andric }
33800b57cec5SDimitry Andric 
33810b57cec5SDimitry Andric // Emit blockinfo, which defines the standard abbreviations etc.
writeBlockInfo()33820b57cec5SDimitry Andric void ModuleBitcodeWriter::writeBlockInfo() {
33830b57cec5SDimitry Andric   // We only want to emit block info records for blocks that have multiple
33840b57cec5SDimitry Andric   // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK.
33850b57cec5SDimitry Andric   // Other blocks can define their abbrevs inline.
33860b57cec5SDimitry Andric   Stream.EnterBlockInfoBlock();
33870b57cec5SDimitry Andric 
33880b57cec5SDimitry Andric   { // 8-bit fixed-width VST_CODE_ENTRY/VST_CODE_BBENTRY strings.
33890b57cec5SDimitry Andric     auto Abbv = std::make_shared<BitCodeAbbrev>();
33900b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3));
33910b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
33920b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
33930b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
33940b57cec5SDimitry Andric     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
33950b57cec5SDimitry Andric         VST_ENTRY_8_ABBREV)
33960b57cec5SDimitry Andric       llvm_unreachable("Unexpected abbrev ordering!");
33970b57cec5SDimitry Andric   }
33980b57cec5SDimitry Andric 
33990b57cec5SDimitry Andric   { // 7-bit fixed width VST_CODE_ENTRY strings.
34000b57cec5SDimitry Andric     auto Abbv = std::make_shared<BitCodeAbbrev>();
34010b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
34020b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
34030b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
34040b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
34050b57cec5SDimitry Andric     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
34060b57cec5SDimitry Andric         VST_ENTRY_7_ABBREV)
34070b57cec5SDimitry Andric       llvm_unreachable("Unexpected abbrev ordering!");
34080b57cec5SDimitry Andric   }
34090b57cec5SDimitry Andric   { // 6-bit char6 VST_CODE_ENTRY strings.
34100b57cec5SDimitry Andric     auto Abbv = std::make_shared<BitCodeAbbrev>();
34110b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
34120b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
34130b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
34140b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
34150b57cec5SDimitry Andric     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
34160b57cec5SDimitry Andric         VST_ENTRY_6_ABBREV)
34170b57cec5SDimitry Andric       llvm_unreachable("Unexpected abbrev ordering!");
34180b57cec5SDimitry Andric   }
34190b57cec5SDimitry Andric   { // 6-bit char6 VST_CODE_BBENTRY strings.
34200b57cec5SDimitry Andric     auto Abbv = std::make_shared<BitCodeAbbrev>();
34210b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY));
34220b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
34230b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
34240b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
34250b57cec5SDimitry Andric     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
34260b57cec5SDimitry Andric         VST_BBENTRY_6_ABBREV)
34270b57cec5SDimitry Andric       llvm_unreachable("Unexpected abbrev ordering!");
34280b57cec5SDimitry Andric   }
34290b57cec5SDimitry Andric 
34300b57cec5SDimitry Andric   { // SETTYPE abbrev for CONSTANTS_BLOCK.
34310b57cec5SDimitry Andric     auto Abbv = std::make_shared<BitCodeAbbrev>();
34320b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_SETTYPE));
34330b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
34340b57cec5SDimitry Andric                               VE.computeBitsRequiredForTypeIndicies()));
34350b57cec5SDimitry Andric     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
34360b57cec5SDimitry Andric         CONSTANTS_SETTYPE_ABBREV)
34370b57cec5SDimitry Andric       llvm_unreachable("Unexpected abbrev ordering!");
34380b57cec5SDimitry Andric   }
34390b57cec5SDimitry Andric 
34400b57cec5SDimitry Andric   { // INTEGER abbrev for CONSTANTS_BLOCK.
34410b57cec5SDimitry Andric     auto Abbv = std::make_shared<BitCodeAbbrev>();
34420b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_INTEGER));
34430b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
34440b57cec5SDimitry Andric     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
34450b57cec5SDimitry Andric         CONSTANTS_INTEGER_ABBREV)
34460b57cec5SDimitry Andric       llvm_unreachable("Unexpected abbrev ordering!");
34470b57cec5SDimitry Andric   }
34480b57cec5SDimitry Andric 
34490b57cec5SDimitry Andric   { // CE_CAST abbrev for CONSTANTS_BLOCK.
34500b57cec5SDimitry Andric     auto Abbv = std::make_shared<BitCodeAbbrev>();
34510b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CE_CAST));
34520b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4));  // cast opc
34530b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,       // typeid
34540b57cec5SDimitry Andric                               VE.computeBitsRequiredForTypeIndicies()));
34550b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));    // value id
34560b57cec5SDimitry Andric 
34570b57cec5SDimitry Andric     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
34580b57cec5SDimitry Andric         CONSTANTS_CE_CAST_Abbrev)
34590b57cec5SDimitry Andric       llvm_unreachable("Unexpected abbrev ordering!");
34600b57cec5SDimitry Andric   }
34610b57cec5SDimitry Andric   { // NULL abbrev for CONSTANTS_BLOCK.
34620b57cec5SDimitry Andric     auto Abbv = std::make_shared<BitCodeAbbrev>();
34630b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_NULL));
34640b57cec5SDimitry Andric     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
34650b57cec5SDimitry Andric         CONSTANTS_NULL_Abbrev)
34660b57cec5SDimitry Andric       llvm_unreachable("Unexpected abbrev ordering!");
34670b57cec5SDimitry Andric   }
34680b57cec5SDimitry Andric 
34690b57cec5SDimitry Andric   // FIXME: This should only use space for first class types!
34700b57cec5SDimitry Andric 
34710b57cec5SDimitry Andric   { // INST_LOAD abbrev for FUNCTION_BLOCK.
34720b57cec5SDimitry Andric     auto Abbv = std::make_shared<BitCodeAbbrev>();
34730b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_LOAD));
34740b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Ptr
34750b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,    // dest ty
34760b57cec5SDimitry Andric                               VE.computeBitsRequiredForTypeIndicies()));
34770b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align
34780b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile
34790b57cec5SDimitry Andric     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
34800b57cec5SDimitry Andric         FUNCTION_INST_LOAD_ABBREV)
34810b57cec5SDimitry Andric       llvm_unreachable("Unexpected abbrev ordering!");
34820b57cec5SDimitry Andric   }
34830b57cec5SDimitry Andric   { // INST_UNOP abbrev for FUNCTION_BLOCK.
34840b57cec5SDimitry Andric     auto Abbv = std::make_shared<BitCodeAbbrev>();
34850b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNOP));
34860b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
34870b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
34880b57cec5SDimitry Andric     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
34890b57cec5SDimitry Andric         FUNCTION_INST_UNOP_ABBREV)
34900b57cec5SDimitry Andric       llvm_unreachable("Unexpected abbrev ordering!");
34910b57cec5SDimitry Andric   }
34920b57cec5SDimitry Andric   { // INST_UNOP_FLAGS abbrev for FUNCTION_BLOCK.
34930b57cec5SDimitry Andric     auto Abbv = std::make_shared<BitCodeAbbrev>();
34940b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNOP));
34950b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
34960b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
34970b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); // flags
34980b57cec5SDimitry Andric     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
34990b57cec5SDimitry Andric         FUNCTION_INST_UNOP_FLAGS_ABBREV)
35000b57cec5SDimitry Andric       llvm_unreachable("Unexpected abbrev ordering!");
35010b57cec5SDimitry Andric   }
35020b57cec5SDimitry Andric   { // INST_BINOP abbrev for FUNCTION_BLOCK.
35030b57cec5SDimitry Andric     auto Abbv = std::make_shared<BitCodeAbbrev>();
35040b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
35050b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
35060b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
35070b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
35080b57cec5SDimitry Andric     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
35090b57cec5SDimitry Andric         FUNCTION_INST_BINOP_ABBREV)
35100b57cec5SDimitry Andric       llvm_unreachable("Unexpected abbrev ordering!");
35110b57cec5SDimitry Andric   }
35120b57cec5SDimitry Andric   { // INST_BINOP_FLAGS abbrev for FUNCTION_BLOCK.
35130b57cec5SDimitry Andric     auto Abbv = std::make_shared<BitCodeAbbrev>();
35140b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
35150b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
35160b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
35170b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
35180b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); // flags
35190b57cec5SDimitry Andric     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
35200b57cec5SDimitry Andric         FUNCTION_INST_BINOP_FLAGS_ABBREV)
35210b57cec5SDimitry Andric       llvm_unreachable("Unexpected abbrev ordering!");
35220b57cec5SDimitry Andric   }
35230b57cec5SDimitry Andric   { // INST_CAST abbrev for FUNCTION_BLOCK.
35240b57cec5SDimitry Andric     auto Abbv = std::make_shared<BitCodeAbbrev>();
35250b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST));
35260b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));    // OpVal
35270b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,       // dest ty
35280b57cec5SDimitry Andric                               VE.computeBitsRequiredForTypeIndicies()));
35290b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4));  // opc
35300b57cec5SDimitry Andric     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
35310b57cec5SDimitry Andric         FUNCTION_INST_CAST_ABBREV)
35320b57cec5SDimitry Andric       llvm_unreachable("Unexpected abbrev ordering!");
35330b57cec5SDimitry Andric   }
35340b57cec5SDimitry Andric 
35350b57cec5SDimitry Andric   { // INST_RET abbrev for FUNCTION_BLOCK.
35360b57cec5SDimitry Andric     auto Abbv = std::make_shared<BitCodeAbbrev>();
35370b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
35380b57cec5SDimitry Andric     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
35390b57cec5SDimitry Andric         FUNCTION_INST_RET_VOID_ABBREV)
35400b57cec5SDimitry Andric       llvm_unreachable("Unexpected abbrev ordering!");
35410b57cec5SDimitry Andric   }
35420b57cec5SDimitry Andric   { // INST_RET abbrev for FUNCTION_BLOCK.
35430b57cec5SDimitry Andric     auto Abbv = std::make_shared<BitCodeAbbrev>();
35440b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
35450b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ValID
35460b57cec5SDimitry Andric     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
35470b57cec5SDimitry Andric         FUNCTION_INST_RET_VAL_ABBREV)
35480b57cec5SDimitry Andric       llvm_unreachable("Unexpected abbrev ordering!");
35490b57cec5SDimitry Andric   }
35500b57cec5SDimitry Andric   { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK.
35510b57cec5SDimitry Andric     auto Abbv = std::make_shared<BitCodeAbbrev>();
35520b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNREACHABLE));
35530b57cec5SDimitry Andric     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
35540b57cec5SDimitry Andric         FUNCTION_INST_UNREACHABLE_ABBREV)
35550b57cec5SDimitry Andric       llvm_unreachable("Unexpected abbrev ordering!");
35560b57cec5SDimitry Andric   }
35570b57cec5SDimitry Andric   {
35580b57cec5SDimitry Andric     auto Abbv = std::make_shared<BitCodeAbbrev>();
35590b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_GEP));
35600b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
35610b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
35620b57cec5SDimitry Andric                               Log2_32_Ceil(VE.getTypes().size() + 1)));
35630b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
35640b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
35650b57cec5SDimitry Andric     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
35660b57cec5SDimitry Andric         FUNCTION_INST_GEP_ABBREV)
35670b57cec5SDimitry Andric       llvm_unreachable("Unexpected abbrev ordering!");
35680b57cec5SDimitry Andric   }
35690b57cec5SDimitry Andric 
35700b57cec5SDimitry Andric   Stream.ExitBlock();
35710b57cec5SDimitry Andric }
35720b57cec5SDimitry Andric 
35730b57cec5SDimitry Andric /// Write the module path strings, currently only used when generating
35740b57cec5SDimitry Andric /// a combined index file.
writeModStrings()35750b57cec5SDimitry Andric void IndexBitcodeWriter::writeModStrings() {
35760b57cec5SDimitry Andric   Stream.EnterSubblock(bitc::MODULE_STRTAB_BLOCK_ID, 3);
35770b57cec5SDimitry Andric 
35780b57cec5SDimitry Andric   // TODO: See which abbrev sizes we actually need to emit
35790b57cec5SDimitry Andric 
35800b57cec5SDimitry Andric   // 8-bit fixed-width MST_ENTRY strings.
35810b57cec5SDimitry Andric   auto Abbv = std::make_shared<BitCodeAbbrev>();
35820b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
35830b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
35840b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
35850b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
35860b57cec5SDimitry Andric   unsigned Abbrev8Bit = Stream.EmitAbbrev(std::move(Abbv));
35870b57cec5SDimitry Andric 
35880b57cec5SDimitry Andric   // 7-bit fixed width MST_ENTRY strings.
35890b57cec5SDimitry Andric   Abbv = std::make_shared<BitCodeAbbrev>();
35900b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
35910b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
35920b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
35930b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
35940b57cec5SDimitry Andric   unsigned Abbrev7Bit = Stream.EmitAbbrev(std::move(Abbv));
35950b57cec5SDimitry Andric 
35960b57cec5SDimitry Andric   // 6-bit char6 MST_ENTRY strings.
35970b57cec5SDimitry Andric   Abbv = std::make_shared<BitCodeAbbrev>();
35980b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
35990b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
36000b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
36010b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
36020b57cec5SDimitry Andric   unsigned Abbrev6Bit = Stream.EmitAbbrev(std::move(Abbv));
36030b57cec5SDimitry Andric 
36040b57cec5SDimitry Andric   // Module Hash, 160 bits SHA1. Optionally, emitted after each MST_CODE_ENTRY.
36050b57cec5SDimitry Andric   Abbv = std::make_shared<BitCodeAbbrev>();
36060b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_HASH));
36070b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
36080b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
36090b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
36100b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
36110b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
36120b57cec5SDimitry Andric   unsigned AbbrevHash = Stream.EmitAbbrev(std::move(Abbv));
36130b57cec5SDimitry Andric 
36140b57cec5SDimitry Andric   SmallVector<unsigned, 64> Vals;
36150b57cec5SDimitry Andric   forEachModule(
36160b57cec5SDimitry Andric       [&](const StringMapEntry<std::pair<uint64_t, ModuleHash>> &MPSE) {
36170b57cec5SDimitry Andric         StringRef Key = MPSE.getKey();
36180b57cec5SDimitry Andric         const auto &Value = MPSE.getValue();
36190b57cec5SDimitry Andric         StringEncoding Bits = getStringEncoding(Key);
36200b57cec5SDimitry Andric         unsigned AbbrevToUse = Abbrev8Bit;
36210b57cec5SDimitry Andric         if (Bits == SE_Char6)
36220b57cec5SDimitry Andric           AbbrevToUse = Abbrev6Bit;
36230b57cec5SDimitry Andric         else if (Bits == SE_Fixed7)
36240b57cec5SDimitry Andric           AbbrevToUse = Abbrev7Bit;
36250b57cec5SDimitry Andric 
36260b57cec5SDimitry Andric         Vals.push_back(Value.first);
36270b57cec5SDimitry Andric         Vals.append(Key.begin(), Key.end());
36280b57cec5SDimitry Andric 
36290b57cec5SDimitry Andric         // Emit the finished record.
36300b57cec5SDimitry Andric         Stream.EmitRecord(bitc::MST_CODE_ENTRY, Vals, AbbrevToUse);
36310b57cec5SDimitry Andric 
36320b57cec5SDimitry Andric         // Emit an optional hash for the module now
36330b57cec5SDimitry Andric         const auto &Hash = Value.second;
36340b57cec5SDimitry Andric         if (llvm::any_of(Hash, [](uint32_t H) { return H; })) {
36350b57cec5SDimitry Andric           Vals.assign(Hash.begin(), Hash.end());
36360b57cec5SDimitry Andric           // Emit the hash record.
36370b57cec5SDimitry Andric           Stream.EmitRecord(bitc::MST_CODE_HASH, Vals, AbbrevHash);
36380b57cec5SDimitry Andric         }
36390b57cec5SDimitry Andric 
36400b57cec5SDimitry Andric         Vals.clear();
36410b57cec5SDimitry Andric       });
36420b57cec5SDimitry Andric   Stream.ExitBlock();
36430b57cec5SDimitry Andric }
36440b57cec5SDimitry Andric 
36450b57cec5SDimitry Andric /// Write the function type metadata related records that need to appear before
36460b57cec5SDimitry Andric /// a function summary entry (whether per-module or combined).
3647af732203SDimitry Andric template <typename Fn>
writeFunctionTypeMetadataRecords(BitstreamWriter & Stream,FunctionSummary * FS,Fn GetValueID)36480b57cec5SDimitry Andric static void writeFunctionTypeMetadataRecords(BitstreamWriter &Stream,
3649af732203SDimitry Andric                                              FunctionSummary *FS,
3650af732203SDimitry Andric                                              Fn GetValueID) {
36510b57cec5SDimitry Andric   if (!FS->type_tests().empty())
36520b57cec5SDimitry Andric     Stream.EmitRecord(bitc::FS_TYPE_TESTS, FS->type_tests());
36530b57cec5SDimitry Andric 
36540b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
36550b57cec5SDimitry Andric 
36560b57cec5SDimitry Andric   auto WriteVFuncIdVec = [&](uint64_t Ty,
36570b57cec5SDimitry Andric                              ArrayRef<FunctionSummary::VFuncId> VFs) {
36580b57cec5SDimitry Andric     if (VFs.empty())
36590b57cec5SDimitry Andric       return;
36600b57cec5SDimitry Andric     Record.clear();
36610b57cec5SDimitry Andric     for (auto &VF : VFs) {
36620b57cec5SDimitry Andric       Record.push_back(VF.GUID);
36630b57cec5SDimitry Andric       Record.push_back(VF.Offset);
36640b57cec5SDimitry Andric     }
36650b57cec5SDimitry Andric     Stream.EmitRecord(Ty, Record);
36660b57cec5SDimitry Andric   };
36670b57cec5SDimitry Andric 
36680b57cec5SDimitry Andric   WriteVFuncIdVec(bitc::FS_TYPE_TEST_ASSUME_VCALLS,
36690b57cec5SDimitry Andric                   FS->type_test_assume_vcalls());
36700b57cec5SDimitry Andric   WriteVFuncIdVec(bitc::FS_TYPE_CHECKED_LOAD_VCALLS,
36710b57cec5SDimitry Andric                   FS->type_checked_load_vcalls());
36720b57cec5SDimitry Andric 
36730b57cec5SDimitry Andric   auto WriteConstVCallVec = [&](uint64_t Ty,
36740b57cec5SDimitry Andric                                 ArrayRef<FunctionSummary::ConstVCall> VCs) {
36750b57cec5SDimitry Andric     for (auto &VC : VCs) {
36760b57cec5SDimitry Andric       Record.clear();
36770b57cec5SDimitry Andric       Record.push_back(VC.VFunc.GUID);
36780b57cec5SDimitry Andric       Record.push_back(VC.VFunc.Offset);
3679af732203SDimitry Andric       llvm::append_range(Record, VC.Args);
36800b57cec5SDimitry Andric       Stream.EmitRecord(Ty, Record);
36810b57cec5SDimitry Andric     }
36820b57cec5SDimitry Andric   };
36830b57cec5SDimitry Andric 
36840b57cec5SDimitry Andric   WriteConstVCallVec(bitc::FS_TYPE_TEST_ASSUME_CONST_VCALL,
36850b57cec5SDimitry Andric                      FS->type_test_assume_const_vcalls());
36860b57cec5SDimitry Andric   WriteConstVCallVec(bitc::FS_TYPE_CHECKED_LOAD_CONST_VCALL,
36870b57cec5SDimitry Andric                      FS->type_checked_load_const_vcalls());
36885ffd83dbSDimitry Andric 
36895ffd83dbSDimitry Andric   auto WriteRange = [&](ConstantRange Range) {
36905ffd83dbSDimitry Andric     Range = Range.sextOrTrunc(FunctionSummary::ParamAccess::RangeWidth);
36915ffd83dbSDimitry Andric     assert(Range.getLower().getNumWords() == 1);
36925ffd83dbSDimitry Andric     assert(Range.getUpper().getNumWords() == 1);
36935ffd83dbSDimitry Andric     emitSignedInt64(Record, *Range.getLower().getRawData());
36945ffd83dbSDimitry Andric     emitSignedInt64(Record, *Range.getUpper().getRawData());
36955ffd83dbSDimitry Andric   };
36965ffd83dbSDimitry Andric 
36975ffd83dbSDimitry Andric   if (!FS->paramAccesses().empty()) {
36985ffd83dbSDimitry Andric     Record.clear();
36995ffd83dbSDimitry Andric     for (auto &Arg : FS->paramAccesses()) {
3700af732203SDimitry Andric       size_t UndoSize = Record.size();
37015ffd83dbSDimitry Andric       Record.push_back(Arg.ParamNo);
37025ffd83dbSDimitry Andric       WriteRange(Arg.Use);
37035ffd83dbSDimitry Andric       Record.push_back(Arg.Calls.size());
37045ffd83dbSDimitry Andric       for (auto &Call : Arg.Calls) {
37055ffd83dbSDimitry Andric         Record.push_back(Call.ParamNo);
3706af732203SDimitry Andric         Optional<unsigned> ValueID = GetValueID(Call.Callee);
3707af732203SDimitry Andric         if (!ValueID) {
3708af732203SDimitry Andric           // If ValueID is unknown we can't drop just this call, we must drop
3709af732203SDimitry Andric           // entire parameter.
3710af732203SDimitry Andric           Record.resize(UndoSize);
3711af732203SDimitry Andric           break;
3712af732203SDimitry Andric         }
3713af732203SDimitry Andric         Record.push_back(*ValueID);
37145ffd83dbSDimitry Andric         WriteRange(Call.Offsets);
37155ffd83dbSDimitry Andric       }
37165ffd83dbSDimitry Andric     }
3717af732203SDimitry Andric     if (!Record.empty())
37185ffd83dbSDimitry Andric       Stream.EmitRecord(bitc::FS_PARAM_ACCESS, Record);
37195ffd83dbSDimitry Andric   }
37200b57cec5SDimitry Andric }
37210b57cec5SDimitry Andric 
37220b57cec5SDimitry Andric /// Collect type IDs from type tests used by function.
37230b57cec5SDimitry Andric static void
getReferencedTypeIds(FunctionSummary * FS,std::set<GlobalValue::GUID> & ReferencedTypeIds)37240b57cec5SDimitry Andric getReferencedTypeIds(FunctionSummary *FS,
37250b57cec5SDimitry Andric                      std::set<GlobalValue::GUID> &ReferencedTypeIds) {
37260b57cec5SDimitry Andric   if (!FS->type_tests().empty())
37270b57cec5SDimitry Andric     for (auto &TT : FS->type_tests())
37280b57cec5SDimitry Andric       ReferencedTypeIds.insert(TT);
37290b57cec5SDimitry Andric 
37300b57cec5SDimitry Andric   auto GetReferencedTypesFromVFuncIdVec =
37310b57cec5SDimitry Andric       [&](ArrayRef<FunctionSummary::VFuncId> VFs) {
37320b57cec5SDimitry Andric         for (auto &VF : VFs)
37330b57cec5SDimitry Andric           ReferencedTypeIds.insert(VF.GUID);
37340b57cec5SDimitry Andric       };
37350b57cec5SDimitry Andric 
37360b57cec5SDimitry Andric   GetReferencedTypesFromVFuncIdVec(FS->type_test_assume_vcalls());
37370b57cec5SDimitry Andric   GetReferencedTypesFromVFuncIdVec(FS->type_checked_load_vcalls());
37380b57cec5SDimitry Andric 
37390b57cec5SDimitry Andric   auto GetReferencedTypesFromConstVCallVec =
37400b57cec5SDimitry Andric       [&](ArrayRef<FunctionSummary::ConstVCall> VCs) {
37410b57cec5SDimitry Andric         for (auto &VC : VCs)
37420b57cec5SDimitry Andric           ReferencedTypeIds.insert(VC.VFunc.GUID);
37430b57cec5SDimitry Andric       };
37440b57cec5SDimitry Andric 
37450b57cec5SDimitry Andric   GetReferencedTypesFromConstVCallVec(FS->type_test_assume_const_vcalls());
37460b57cec5SDimitry Andric   GetReferencedTypesFromConstVCallVec(FS->type_checked_load_const_vcalls());
37470b57cec5SDimitry Andric }
37480b57cec5SDimitry Andric 
writeWholeProgramDevirtResolutionByArg(SmallVector<uint64_t,64> & NameVals,const std::vector<uint64_t> & args,const WholeProgramDevirtResolution::ByArg & ByArg)37490b57cec5SDimitry Andric static void writeWholeProgramDevirtResolutionByArg(
37500b57cec5SDimitry Andric     SmallVector<uint64_t, 64> &NameVals, const std::vector<uint64_t> &args,
37510b57cec5SDimitry Andric     const WholeProgramDevirtResolution::ByArg &ByArg) {
37520b57cec5SDimitry Andric   NameVals.push_back(args.size());
3753af732203SDimitry Andric   llvm::append_range(NameVals, args);
37540b57cec5SDimitry Andric 
37550b57cec5SDimitry Andric   NameVals.push_back(ByArg.TheKind);
37560b57cec5SDimitry Andric   NameVals.push_back(ByArg.Info);
37570b57cec5SDimitry Andric   NameVals.push_back(ByArg.Byte);
37580b57cec5SDimitry Andric   NameVals.push_back(ByArg.Bit);
37590b57cec5SDimitry Andric }
37600b57cec5SDimitry Andric 
writeWholeProgramDevirtResolution(SmallVector<uint64_t,64> & NameVals,StringTableBuilder & StrtabBuilder,uint64_t Id,const WholeProgramDevirtResolution & Wpd)37610b57cec5SDimitry Andric static void writeWholeProgramDevirtResolution(
37620b57cec5SDimitry Andric     SmallVector<uint64_t, 64> &NameVals, StringTableBuilder &StrtabBuilder,
37630b57cec5SDimitry Andric     uint64_t Id, const WholeProgramDevirtResolution &Wpd) {
37640b57cec5SDimitry Andric   NameVals.push_back(Id);
37650b57cec5SDimitry Andric 
37660b57cec5SDimitry Andric   NameVals.push_back(Wpd.TheKind);
37670b57cec5SDimitry Andric   NameVals.push_back(StrtabBuilder.add(Wpd.SingleImplName));
37680b57cec5SDimitry Andric   NameVals.push_back(Wpd.SingleImplName.size());
37690b57cec5SDimitry Andric 
37700b57cec5SDimitry Andric   NameVals.push_back(Wpd.ResByArg.size());
37710b57cec5SDimitry Andric   for (auto &A : Wpd.ResByArg)
37720b57cec5SDimitry Andric     writeWholeProgramDevirtResolutionByArg(NameVals, A.first, A.second);
37730b57cec5SDimitry Andric }
37740b57cec5SDimitry Andric 
writeTypeIdSummaryRecord(SmallVector<uint64_t,64> & NameVals,StringTableBuilder & StrtabBuilder,const std::string & Id,const TypeIdSummary & Summary)37750b57cec5SDimitry Andric static void writeTypeIdSummaryRecord(SmallVector<uint64_t, 64> &NameVals,
37760b57cec5SDimitry Andric                                      StringTableBuilder &StrtabBuilder,
37770b57cec5SDimitry Andric                                      const std::string &Id,
37780b57cec5SDimitry Andric                                      const TypeIdSummary &Summary) {
37790b57cec5SDimitry Andric   NameVals.push_back(StrtabBuilder.add(Id));
37800b57cec5SDimitry Andric   NameVals.push_back(Id.size());
37810b57cec5SDimitry Andric 
37820b57cec5SDimitry Andric   NameVals.push_back(Summary.TTRes.TheKind);
37830b57cec5SDimitry Andric   NameVals.push_back(Summary.TTRes.SizeM1BitWidth);
37840b57cec5SDimitry Andric   NameVals.push_back(Summary.TTRes.AlignLog2);
37850b57cec5SDimitry Andric   NameVals.push_back(Summary.TTRes.SizeM1);
37860b57cec5SDimitry Andric   NameVals.push_back(Summary.TTRes.BitMask);
37870b57cec5SDimitry Andric   NameVals.push_back(Summary.TTRes.InlineBits);
37880b57cec5SDimitry Andric 
37890b57cec5SDimitry Andric   for (auto &W : Summary.WPDRes)
37900b57cec5SDimitry Andric     writeWholeProgramDevirtResolution(NameVals, StrtabBuilder, W.first,
37910b57cec5SDimitry Andric                                       W.second);
37920b57cec5SDimitry Andric }
37930b57cec5SDimitry Andric 
writeTypeIdCompatibleVtableSummaryRecord(SmallVector<uint64_t,64> & NameVals,StringTableBuilder & StrtabBuilder,const std::string & Id,const TypeIdCompatibleVtableInfo & Summary,ValueEnumerator & VE)37940b57cec5SDimitry Andric static void writeTypeIdCompatibleVtableSummaryRecord(
37950b57cec5SDimitry Andric     SmallVector<uint64_t, 64> &NameVals, StringTableBuilder &StrtabBuilder,
37960b57cec5SDimitry Andric     const std::string &Id, const TypeIdCompatibleVtableInfo &Summary,
37970b57cec5SDimitry Andric     ValueEnumerator &VE) {
37980b57cec5SDimitry Andric   NameVals.push_back(StrtabBuilder.add(Id));
37990b57cec5SDimitry Andric   NameVals.push_back(Id.size());
38000b57cec5SDimitry Andric 
38010b57cec5SDimitry Andric   for (auto &P : Summary) {
38020b57cec5SDimitry Andric     NameVals.push_back(P.AddressPointOffset);
38030b57cec5SDimitry Andric     NameVals.push_back(VE.getValueID(P.VTableVI.getValue()));
38040b57cec5SDimitry Andric   }
38050b57cec5SDimitry Andric }
38060b57cec5SDimitry Andric 
38070b57cec5SDimitry Andric // Helper to emit a single function summary record.
writePerModuleFunctionSummaryRecord(SmallVector<uint64_t,64> & NameVals,GlobalValueSummary * Summary,unsigned ValueID,unsigned FSCallsAbbrev,unsigned FSCallsProfileAbbrev,const Function & F)38080b57cec5SDimitry Andric void ModuleBitcodeWriterBase::writePerModuleFunctionSummaryRecord(
38090b57cec5SDimitry Andric     SmallVector<uint64_t, 64> &NameVals, GlobalValueSummary *Summary,
38100b57cec5SDimitry Andric     unsigned ValueID, unsigned FSCallsAbbrev, unsigned FSCallsProfileAbbrev,
38110b57cec5SDimitry Andric     const Function &F) {
38120b57cec5SDimitry Andric   NameVals.push_back(ValueID);
38130b57cec5SDimitry Andric 
38140b57cec5SDimitry Andric   FunctionSummary *FS = cast<FunctionSummary>(Summary);
3815af732203SDimitry Andric 
3816af732203SDimitry Andric   writeFunctionTypeMetadataRecords(
3817af732203SDimitry Andric       Stream, FS, [&](const ValueInfo &VI) -> Optional<unsigned> {
3818af732203SDimitry Andric         return {VE.getValueID(VI.getValue())};
3819af732203SDimitry Andric       });
38200b57cec5SDimitry Andric 
38210b57cec5SDimitry Andric   auto SpecialRefCnts = FS->specialRefCounts();
38220b57cec5SDimitry Andric   NameVals.push_back(getEncodedGVSummaryFlags(FS->flags()));
38230b57cec5SDimitry Andric   NameVals.push_back(FS->instCount());
38240b57cec5SDimitry Andric   NameVals.push_back(getEncodedFFlags(FS->fflags()));
38250b57cec5SDimitry Andric   NameVals.push_back(FS->refs().size());
38260b57cec5SDimitry Andric   NameVals.push_back(SpecialRefCnts.first);  // rorefcnt
38270b57cec5SDimitry Andric   NameVals.push_back(SpecialRefCnts.second); // worefcnt
38280b57cec5SDimitry Andric 
38290b57cec5SDimitry Andric   for (auto &RI : FS->refs())
38300b57cec5SDimitry Andric     NameVals.push_back(VE.getValueID(RI.getValue()));
38310b57cec5SDimitry Andric 
38320b57cec5SDimitry Andric   bool HasProfileData =
38330b57cec5SDimitry Andric       F.hasProfileData() || ForceSummaryEdgesCold != FunctionSummary::FSHT_None;
38340b57cec5SDimitry Andric   for (auto &ECI : FS->calls()) {
38350b57cec5SDimitry Andric     NameVals.push_back(getValueId(ECI.first));
38360b57cec5SDimitry Andric     if (HasProfileData)
38370b57cec5SDimitry Andric       NameVals.push_back(static_cast<uint8_t>(ECI.second.Hotness));
38380b57cec5SDimitry Andric     else if (WriteRelBFToSummary)
38390b57cec5SDimitry Andric       NameVals.push_back(ECI.second.RelBlockFreq);
38400b57cec5SDimitry Andric   }
38410b57cec5SDimitry Andric 
38420b57cec5SDimitry Andric   unsigned FSAbbrev = (HasProfileData ? FSCallsProfileAbbrev : FSCallsAbbrev);
38430b57cec5SDimitry Andric   unsigned Code =
38440b57cec5SDimitry Andric       (HasProfileData ? bitc::FS_PERMODULE_PROFILE
38450b57cec5SDimitry Andric                       : (WriteRelBFToSummary ? bitc::FS_PERMODULE_RELBF
38460b57cec5SDimitry Andric                                              : bitc::FS_PERMODULE));
38470b57cec5SDimitry Andric 
38480b57cec5SDimitry Andric   // Emit the finished record.
38490b57cec5SDimitry Andric   Stream.EmitRecord(Code, NameVals, FSAbbrev);
38500b57cec5SDimitry Andric   NameVals.clear();
38510b57cec5SDimitry Andric }
38520b57cec5SDimitry Andric 
38530b57cec5SDimitry Andric // Collect the global value references in the given variable's initializer,
38540b57cec5SDimitry Andric // and emit them in a summary record.
writeModuleLevelReferences(const GlobalVariable & V,SmallVector<uint64_t,64> & NameVals,unsigned FSModRefsAbbrev,unsigned FSModVTableRefsAbbrev)38550b57cec5SDimitry Andric void ModuleBitcodeWriterBase::writeModuleLevelReferences(
38560b57cec5SDimitry Andric     const GlobalVariable &V, SmallVector<uint64_t, 64> &NameVals,
38570b57cec5SDimitry Andric     unsigned FSModRefsAbbrev, unsigned FSModVTableRefsAbbrev) {
38580b57cec5SDimitry Andric   auto VI = Index->getValueInfo(V.getGUID());
38590b57cec5SDimitry Andric   if (!VI || VI.getSummaryList().empty()) {
38600b57cec5SDimitry Andric     // Only declarations should not have a summary (a declaration might however
38610b57cec5SDimitry Andric     // have a summary if the def was in module level asm).
38620b57cec5SDimitry Andric     assert(V.isDeclaration());
38630b57cec5SDimitry Andric     return;
38640b57cec5SDimitry Andric   }
38650b57cec5SDimitry Andric   auto *Summary = VI.getSummaryList()[0].get();
38660b57cec5SDimitry Andric   NameVals.push_back(VE.getValueID(&V));
38670b57cec5SDimitry Andric   GlobalVarSummary *VS = cast<GlobalVarSummary>(Summary);
38680b57cec5SDimitry Andric   NameVals.push_back(getEncodedGVSummaryFlags(VS->flags()));
38690b57cec5SDimitry Andric   NameVals.push_back(getEncodedGVarFlags(VS->varflags()));
38700b57cec5SDimitry Andric 
38710b57cec5SDimitry Andric   auto VTableFuncs = VS->vTableFuncs();
38720b57cec5SDimitry Andric   if (!VTableFuncs.empty())
38730b57cec5SDimitry Andric     NameVals.push_back(VS->refs().size());
38740b57cec5SDimitry Andric 
38750b57cec5SDimitry Andric   unsigned SizeBeforeRefs = NameVals.size();
38760b57cec5SDimitry Andric   for (auto &RI : VS->refs())
38770b57cec5SDimitry Andric     NameVals.push_back(VE.getValueID(RI.getValue()));
38780b57cec5SDimitry Andric   // Sort the refs for determinism output, the vector returned by FS->refs() has
38790b57cec5SDimitry Andric   // been initialized from a DenseSet.
3880af732203SDimitry Andric   llvm::sort(drop_begin(NameVals, SizeBeforeRefs));
38810b57cec5SDimitry Andric 
38820b57cec5SDimitry Andric   if (VTableFuncs.empty())
38830b57cec5SDimitry Andric     Stream.EmitRecord(bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS, NameVals,
38840b57cec5SDimitry Andric                       FSModRefsAbbrev);
38850b57cec5SDimitry Andric   else {
38860b57cec5SDimitry Andric     // VTableFuncs pairs should already be sorted by offset.
38870b57cec5SDimitry Andric     for (auto &P : VTableFuncs) {
38880b57cec5SDimitry Andric       NameVals.push_back(VE.getValueID(P.FuncVI.getValue()));
38890b57cec5SDimitry Andric       NameVals.push_back(P.VTableOffset);
38900b57cec5SDimitry Andric     }
38910b57cec5SDimitry Andric 
38920b57cec5SDimitry Andric     Stream.EmitRecord(bitc::FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS, NameVals,
38930b57cec5SDimitry Andric                       FSModVTableRefsAbbrev);
38940b57cec5SDimitry Andric   }
38950b57cec5SDimitry Andric   NameVals.clear();
38960b57cec5SDimitry Andric }
38970b57cec5SDimitry Andric 
38980b57cec5SDimitry Andric /// Emit the per-module summary section alongside the rest of
38990b57cec5SDimitry Andric /// the module's bitcode.
writePerModuleGlobalValueSummary()39000b57cec5SDimitry Andric void ModuleBitcodeWriterBase::writePerModuleGlobalValueSummary() {
39010b57cec5SDimitry Andric   // By default we compile with ThinLTO if the module has a summary, but the
39020b57cec5SDimitry Andric   // client can request full LTO with a module flag.
39030b57cec5SDimitry Andric   bool IsThinLTO = true;
39040b57cec5SDimitry Andric   if (auto *MD =
39050b57cec5SDimitry Andric           mdconst::extract_or_null<ConstantInt>(M.getModuleFlag("ThinLTO")))
39060b57cec5SDimitry Andric     IsThinLTO = MD->getZExtValue();
39070b57cec5SDimitry Andric   Stream.EnterSubblock(IsThinLTO ? bitc::GLOBALVAL_SUMMARY_BLOCK_ID
39080b57cec5SDimitry Andric                                  : bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID,
39090b57cec5SDimitry Andric                        4);
39100b57cec5SDimitry Andric 
3911480093f4SDimitry Andric   Stream.EmitRecord(
3912480093f4SDimitry Andric       bitc::FS_VERSION,
3913480093f4SDimitry Andric       ArrayRef<uint64_t>{ModuleSummaryIndex::BitcodeSummaryVersion});
39140b57cec5SDimitry Andric 
39150b57cec5SDimitry Andric   // Write the index flags.
39160b57cec5SDimitry Andric   uint64_t Flags = 0;
39170b57cec5SDimitry Andric   // Bits 1-3 are set only in the combined index, skip them.
39180b57cec5SDimitry Andric   if (Index->enableSplitLTOUnit())
39190b57cec5SDimitry Andric     Flags |= 0x8;
39200b57cec5SDimitry Andric   Stream.EmitRecord(bitc::FS_FLAGS, ArrayRef<uint64_t>{Flags});
39210b57cec5SDimitry Andric 
39220b57cec5SDimitry Andric   if (Index->begin() == Index->end()) {
39230b57cec5SDimitry Andric     Stream.ExitBlock();
39240b57cec5SDimitry Andric     return;
39250b57cec5SDimitry Andric   }
39260b57cec5SDimitry Andric 
39270b57cec5SDimitry Andric   for (const auto &GVI : valueIds()) {
39280b57cec5SDimitry Andric     Stream.EmitRecord(bitc::FS_VALUE_GUID,
39290b57cec5SDimitry Andric                       ArrayRef<uint64_t>{GVI.second, GVI.first});
39300b57cec5SDimitry Andric   }
39310b57cec5SDimitry Andric 
39320b57cec5SDimitry Andric   // Abbrev for FS_PERMODULE_PROFILE.
39330b57cec5SDimitry Andric   auto Abbv = std::make_shared<BitCodeAbbrev>();
39340b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_PROFILE));
39350b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // valueid
39360b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // flags
39370b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // instcount
39380b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // fflags
39390b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // numrefs
39400b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // rorefcnt
39410b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // worefcnt
39420b57cec5SDimitry Andric   // numrefs x valueid, n x (valueid, hotness)
39430b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
39440b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
39450b57cec5SDimitry Andric   unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(std::move(Abbv));
39460b57cec5SDimitry Andric 
39470b57cec5SDimitry Andric   // Abbrev for FS_PERMODULE or FS_PERMODULE_RELBF.
39480b57cec5SDimitry Andric   Abbv = std::make_shared<BitCodeAbbrev>();
39490b57cec5SDimitry Andric   if (WriteRelBFToSummary)
39500b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_RELBF));
39510b57cec5SDimitry Andric   else
39520b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE));
39530b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // valueid
39540b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // flags
39550b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // instcount
39560b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // fflags
39570b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // numrefs
39580b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // rorefcnt
39590b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // worefcnt
39600b57cec5SDimitry Andric   // numrefs x valueid, n x (valueid [, rel_block_freq])
39610b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
39620b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
39630b57cec5SDimitry Andric   unsigned FSCallsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
39640b57cec5SDimitry Andric 
39650b57cec5SDimitry Andric   // Abbrev for FS_PERMODULE_GLOBALVAR_INIT_REFS.
39660b57cec5SDimitry Andric   Abbv = std::make_shared<BitCodeAbbrev>();
39670b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS));
39680b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
39690b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
39700b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));  // valueids
39710b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
39720b57cec5SDimitry Andric   unsigned FSModRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
39730b57cec5SDimitry Andric 
39740b57cec5SDimitry Andric   // Abbrev for FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS.
39750b57cec5SDimitry Andric   Abbv = std::make_shared<BitCodeAbbrev>();
39760b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS));
39770b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
39780b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
39790b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
39800b57cec5SDimitry Andric   // numrefs x valueid, n x (valueid , offset)
39810b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
39820b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
39830b57cec5SDimitry Andric   unsigned FSModVTableRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
39840b57cec5SDimitry Andric 
39850b57cec5SDimitry Andric   // Abbrev for FS_ALIAS.
39860b57cec5SDimitry Andric   Abbv = std::make_shared<BitCodeAbbrev>();
39870b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::FS_ALIAS));
39880b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // valueid
39890b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // flags
39900b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // valueid
39910b57cec5SDimitry Andric   unsigned FSAliasAbbrev = Stream.EmitAbbrev(std::move(Abbv));
39920b57cec5SDimitry Andric 
39930b57cec5SDimitry Andric   // Abbrev for FS_TYPE_ID_METADATA
39940b57cec5SDimitry Andric   Abbv = std::make_shared<BitCodeAbbrev>();
39950b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::FS_TYPE_ID_METADATA));
39960b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // typeid strtab index
39970b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // typeid length
39980b57cec5SDimitry Andric   // n x (valueid , offset)
39990b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
40000b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
40010b57cec5SDimitry Andric   unsigned TypeIdCompatibleVtableAbbrev = Stream.EmitAbbrev(std::move(Abbv));
40020b57cec5SDimitry Andric 
40030b57cec5SDimitry Andric   SmallVector<uint64_t, 64> NameVals;
40040b57cec5SDimitry Andric   // Iterate over the list of functions instead of the Index to
40050b57cec5SDimitry Andric   // ensure the ordering is stable.
40060b57cec5SDimitry Andric   for (const Function &F : M) {
40070b57cec5SDimitry Andric     // Summary emission does not support anonymous functions, they have to
40080b57cec5SDimitry Andric     // renamed using the anonymous function renaming pass.
40090b57cec5SDimitry Andric     if (!F.hasName())
40100b57cec5SDimitry Andric       report_fatal_error("Unexpected anonymous function when writing summary");
40110b57cec5SDimitry Andric 
40120b57cec5SDimitry Andric     ValueInfo VI = Index->getValueInfo(F.getGUID());
40130b57cec5SDimitry Andric     if (!VI || VI.getSummaryList().empty()) {
40140b57cec5SDimitry Andric       // Only declarations should not have a summary (a declaration might
40150b57cec5SDimitry Andric       // however have a summary if the def was in module level asm).
40160b57cec5SDimitry Andric       assert(F.isDeclaration());
40170b57cec5SDimitry Andric       continue;
40180b57cec5SDimitry Andric     }
40190b57cec5SDimitry Andric     auto *Summary = VI.getSummaryList()[0].get();
40200b57cec5SDimitry Andric     writePerModuleFunctionSummaryRecord(NameVals, Summary, VE.getValueID(&F),
40210b57cec5SDimitry Andric                                         FSCallsAbbrev, FSCallsProfileAbbrev, F);
40220b57cec5SDimitry Andric   }
40230b57cec5SDimitry Andric 
40240b57cec5SDimitry Andric   // Capture references from GlobalVariable initializers, which are outside
40250b57cec5SDimitry Andric   // of a function scope.
40260b57cec5SDimitry Andric   for (const GlobalVariable &G : M.globals())
40270b57cec5SDimitry Andric     writeModuleLevelReferences(G, NameVals, FSModRefsAbbrev,
40280b57cec5SDimitry Andric                                FSModVTableRefsAbbrev);
40290b57cec5SDimitry Andric 
40300b57cec5SDimitry Andric   for (const GlobalAlias &A : M.aliases()) {
40310b57cec5SDimitry Andric     auto *Aliasee = A.getBaseObject();
40320b57cec5SDimitry Andric     if (!Aliasee->hasName())
40330b57cec5SDimitry Andric       // Nameless function don't have an entry in the summary, skip it.
40340b57cec5SDimitry Andric       continue;
40350b57cec5SDimitry Andric     auto AliasId = VE.getValueID(&A);
40360b57cec5SDimitry Andric     auto AliaseeId = VE.getValueID(Aliasee);
40370b57cec5SDimitry Andric     NameVals.push_back(AliasId);
40380b57cec5SDimitry Andric     auto *Summary = Index->getGlobalValueSummary(A);
40390b57cec5SDimitry Andric     AliasSummary *AS = cast<AliasSummary>(Summary);
40400b57cec5SDimitry Andric     NameVals.push_back(getEncodedGVSummaryFlags(AS->flags()));
40410b57cec5SDimitry Andric     NameVals.push_back(AliaseeId);
40420b57cec5SDimitry Andric     Stream.EmitRecord(bitc::FS_ALIAS, NameVals, FSAliasAbbrev);
40430b57cec5SDimitry Andric     NameVals.clear();
40440b57cec5SDimitry Andric   }
40450b57cec5SDimitry Andric 
40460b57cec5SDimitry Andric   for (auto &S : Index->typeIdCompatibleVtableMap()) {
40470b57cec5SDimitry Andric     writeTypeIdCompatibleVtableSummaryRecord(NameVals, StrtabBuilder, S.first,
40480b57cec5SDimitry Andric                                              S.second, VE);
40490b57cec5SDimitry Andric     Stream.EmitRecord(bitc::FS_TYPE_ID_METADATA, NameVals,
40500b57cec5SDimitry Andric                       TypeIdCompatibleVtableAbbrev);
40510b57cec5SDimitry Andric     NameVals.clear();
40520b57cec5SDimitry Andric   }
40530b57cec5SDimitry Andric 
40545ffd83dbSDimitry Andric   Stream.EmitRecord(bitc::FS_BLOCK_COUNT,
40555ffd83dbSDimitry Andric                     ArrayRef<uint64_t>{Index->getBlockCount()});
40565ffd83dbSDimitry Andric 
40570b57cec5SDimitry Andric   Stream.ExitBlock();
40580b57cec5SDimitry Andric }
40590b57cec5SDimitry Andric 
40600b57cec5SDimitry Andric /// Emit the combined summary section into the combined index file.
writeCombinedGlobalValueSummary()40610b57cec5SDimitry Andric void IndexBitcodeWriter::writeCombinedGlobalValueSummary() {
40620b57cec5SDimitry Andric   Stream.EnterSubblock(bitc::GLOBALVAL_SUMMARY_BLOCK_ID, 3);
4063480093f4SDimitry Andric   Stream.EmitRecord(
4064480093f4SDimitry Andric       bitc::FS_VERSION,
4065480093f4SDimitry Andric       ArrayRef<uint64_t>{ModuleSummaryIndex::BitcodeSummaryVersion});
40660b57cec5SDimitry Andric 
40670b57cec5SDimitry Andric   // Write the index flags.
40685ffd83dbSDimitry Andric   Stream.EmitRecord(bitc::FS_FLAGS, ArrayRef<uint64_t>{Index.getFlags()});
40690b57cec5SDimitry Andric 
40700b57cec5SDimitry Andric   for (const auto &GVI : valueIds()) {
40710b57cec5SDimitry Andric     Stream.EmitRecord(bitc::FS_VALUE_GUID,
40720b57cec5SDimitry Andric                       ArrayRef<uint64_t>{GVI.second, GVI.first});
40730b57cec5SDimitry Andric   }
40740b57cec5SDimitry Andric 
40750b57cec5SDimitry Andric   // Abbrev for FS_COMBINED.
40760b57cec5SDimitry Andric   auto Abbv = std::make_shared<BitCodeAbbrev>();
40770b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED));
40780b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // valueid
40790b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // modid
40800b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // flags
40810b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // instcount
40820b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // fflags
40830b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // entrycount
40840b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // numrefs
40850b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // rorefcnt
40860b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // worefcnt
40870b57cec5SDimitry Andric   // numrefs x valueid, n x (valueid)
40880b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
40890b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
40900b57cec5SDimitry Andric   unsigned FSCallsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
40910b57cec5SDimitry Andric 
40920b57cec5SDimitry Andric   // Abbrev for FS_COMBINED_PROFILE.
40930b57cec5SDimitry Andric   Abbv = std::make_shared<BitCodeAbbrev>();
40940b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_PROFILE));
40950b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // valueid
40960b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // modid
40970b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // flags
40980b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // instcount
40990b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // fflags
41000b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // entrycount
41010b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // numrefs
41020b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // rorefcnt
41030b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // worefcnt
41040b57cec5SDimitry Andric   // numrefs x valueid, n x (valueid, hotness)
41050b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
41060b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
41070b57cec5SDimitry Andric   unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(std::move(Abbv));
41080b57cec5SDimitry Andric 
41090b57cec5SDimitry Andric   // Abbrev for FS_COMBINED_GLOBALVAR_INIT_REFS.
41100b57cec5SDimitry Andric   Abbv = std::make_shared<BitCodeAbbrev>();
41110b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_GLOBALVAR_INIT_REFS));
41120b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // valueid
41130b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // modid
41140b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // flags
41150b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));    // valueids
41160b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
41170b57cec5SDimitry Andric   unsigned FSModRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
41180b57cec5SDimitry Andric 
41190b57cec5SDimitry Andric   // Abbrev for FS_COMBINED_ALIAS.
41200b57cec5SDimitry Andric   Abbv = std::make_shared<BitCodeAbbrev>();
41210b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_ALIAS));
41220b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // valueid
41230b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // modid
41240b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // flags
41250b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // valueid
41260b57cec5SDimitry Andric   unsigned FSAliasAbbrev = Stream.EmitAbbrev(std::move(Abbv));
41270b57cec5SDimitry Andric 
41280b57cec5SDimitry Andric   // The aliases are emitted as a post-pass, and will point to the value
41290b57cec5SDimitry Andric   // id of the aliasee. Save them in a vector for post-processing.
41300b57cec5SDimitry Andric   SmallVector<AliasSummary *, 64> Aliases;
41310b57cec5SDimitry Andric 
41320b57cec5SDimitry Andric   // Save the value id for each summary for alias emission.
41330b57cec5SDimitry Andric   DenseMap<const GlobalValueSummary *, unsigned> SummaryToValueIdMap;
41340b57cec5SDimitry Andric 
41350b57cec5SDimitry Andric   SmallVector<uint64_t, 64> NameVals;
41360b57cec5SDimitry Andric 
41370b57cec5SDimitry Andric   // Set that will be populated during call to writeFunctionTypeMetadataRecords
41380b57cec5SDimitry Andric   // with the type ids referenced by this index file.
41390b57cec5SDimitry Andric   std::set<GlobalValue::GUID> ReferencedTypeIds;
41400b57cec5SDimitry Andric 
41410b57cec5SDimitry Andric   // For local linkage, we also emit the original name separately
41420b57cec5SDimitry Andric   // immediately after the record.
41430b57cec5SDimitry Andric   auto MaybeEmitOriginalName = [&](GlobalValueSummary &S) {
41440b57cec5SDimitry Andric     if (!GlobalValue::isLocalLinkage(S.linkage()))
41450b57cec5SDimitry Andric       return;
41460b57cec5SDimitry Andric     NameVals.push_back(S.getOriginalName());
41470b57cec5SDimitry Andric     Stream.EmitRecord(bitc::FS_COMBINED_ORIGINAL_NAME, NameVals);
41480b57cec5SDimitry Andric     NameVals.clear();
41490b57cec5SDimitry Andric   };
41500b57cec5SDimitry Andric 
41510b57cec5SDimitry Andric   std::set<GlobalValue::GUID> DefOrUseGUIDs;
41520b57cec5SDimitry Andric   forEachSummary([&](GVInfo I, bool IsAliasee) {
41530b57cec5SDimitry Andric     GlobalValueSummary *S = I.second;
41540b57cec5SDimitry Andric     assert(S);
41550b57cec5SDimitry Andric     DefOrUseGUIDs.insert(I.first);
41560b57cec5SDimitry Andric     for (const ValueInfo &VI : S->refs())
41570b57cec5SDimitry Andric       DefOrUseGUIDs.insert(VI.getGUID());
41580b57cec5SDimitry Andric 
41590b57cec5SDimitry Andric     auto ValueId = getValueId(I.first);
41600b57cec5SDimitry Andric     assert(ValueId);
41610b57cec5SDimitry Andric     SummaryToValueIdMap[S] = *ValueId;
41620b57cec5SDimitry Andric 
41630b57cec5SDimitry Andric     // If this is invoked for an aliasee, we want to record the above
41640b57cec5SDimitry Andric     // mapping, but then not emit a summary entry (if the aliasee is
41650b57cec5SDimitry Andric     // to be imported, we will invoke this separately with IsAliasee=false).
41660b57cec5SDimitry Andric     if (IsAliasee)
41670b57cec5SDimitry Andric       return;
41680b57cec5SDimitry Andric 
41690b57cec5SDimitry Andric     if (auto *AS = dyn_cast<AliasSummary>(S)) {
41700b57cec5SDimitry Andric       // Will process aliases as a post-pass because the reader wants all
41710b57cec5SDimitry Andric       // global to be loaded first.
41720b57cec5SDimitry Andric       Aliases.push_back(AS);
41730b57cec5SDimitry Andric       return;
41740b57cec5SDimitry Andric     }
41750b57cec5SDimitry Andric 
41760b57cec5SDimitry Andric     if (auto *VS = dyn_cast<GlobalVarSummary>(S)) {
41770b57cec5SDimitry Andric       NameVals.push_back(*ValueId);
41780b57cec5SDimitry Andric       NameVals.push_back(Index.getModuleId(VS->modulePath()));
41790b57cec5SDimitry Andric       NameVals.push_back(getEncodedGVSummaryFlags(VS->flags()));
41800b57cec5SDimitry Andric       NameVals.push_back(getEncodedGVarFlags(VS->varflags()));
41810b57cec5SDimitry Andric       for (auto &RI : VS->refs()) {
41820b57cec5SDimitry Andric         auto RefValueId = getValueId(RI.getGUID());
41830b57cec5SDimitry Andric         if (!RefValueId)
41840b57cec5SDimitry Andric           continue;
41850b57cec5SDimitry Andric         NameVals.push_back(*RefValueId);
41860b57cec5SDimitry Andric       }
41870b57cec5SDimitry Andric 
41880b57cec5SDimitry Andric       // Emit the finished record.
41890b57cec5SDimitry Andric       Stream.EmitRecord(bitc::FS_COMBINED_GLOBALVAR_INIT_REFS, NameVals,
41900b57cec5SDimitry Andric                         FSModRefsAbbrev);
41910b57cec5SDimitry Andric       NameVals.clear();
41920b57cec5SDimitry Andric       MaybeEmitOriginalName(*S);
41930b57cec5SDimitry Andric       return;
41940b57cec5SDimitry Andric     }
41950b57cec5SDimitry Andric 
4196af732203SDimitry Andric     auto GetValueId = [&](const ValueInfo &VI) -> Optional<unsigned> {
4197af732203SDimitry Andric       GlobalValue::GUID GUID = VI.getGUID();
4198af732203SDimitry Andric       Optional<unsigned> CallValueId = getValueId(GUID);
4199af732203SDimitry Andric       if (CallValueId)
4200af732203SDimitry Andric         return CallValueId;
4201af732203SDimitry Andric       // For SamplePGO, the indirect call targets for local functions will
4202af732203SDimitry Andric       // have its original name annotated in profile. We try to find the
4203af732203SDimitry Andric       // corresponding PGOFuncName as the GUID.
4204af732203SDimitry Andric       GUID = Index.getGUIDFromOriginalID(GUID);
4205af732203SDimitry Andric       if (!GUID)
4206af732203SDimitry Andric         return None;
4207af732203SDimitry Andric       CallValueId = getValueId(GUID);
4208af732203SDimitry Andric       if (!CallValueId)
4209af732203SDimitry Andric         return None;
4210af732203SDimitry Andric       // The mapping from OriginalId to GUID may return a GUID
4211af732203SDimitry Andric       // that corresponds to a static variable. Filter it out here.
4212af732203SDimitry Andric       // This can happen when
4213af732203SDimitry Andric       // 1) There is a call to a library function which does not have
4214af732203SDimitry Andric       // a CallValidId;
4215af732203SDimitry Andric       // 2) There is a static variable with the  OriginalGUID identical
4216af732203SDimitry Andric       // to the GUID of the library function in 1);
4217af732203SDimitry Andric       // When this happens, the logic for SamplePGO kicks in and
4218af732203SDimitry Andric       // the static variable in 2) will be found, which needs to be
4219af732203SDimitry Andric       // filtered out.
4220af732203SDimitry Andric       auto *GVSum = Index.getGlobalValueSummary(GUID, false);
4221af732203SDimitry Andric       if (GVSum && GVSum->getSummaryKind() == GlobalValueSummary::GlobalVarKind)
4222af732203SDimitry Andric         return None;
4223af732203SDimitry Andric       return CallValueId;
4224af732203SDimitry Andric     };
4225af732203SDimitry Andric 
42260b57cec5SDimitry Andric     auto *FS = cast<FunctionSummary>(S);
4227af732203SDimitry Andric     writeFunctionTypeMetadataRecords(Stream, FS, GetValueId);
42280b57cec5SDimitry Andric     getReferencedTypeIds(FS, ReferencedTypeIds);
42290b57cec5SDimitry Andric 
42300b57cec5SDimitry Andric     NameVals.push_back(*ValueId);
42310b57cec5SDimitry Andric     NameVals.push_back(Index.getModuleId(FS->modulePath()));
42320b57cec5SDimitry Andric     NameVals.push_back(getEncodedGVSummaryFlags(FS->flags()));
42330b57cec5SDimitry Andric     NameVals.push_back(FS->instCount());
42340b57cec5SDimitry Andric     NameVals.push_back(getEncodedFFlags(FS->fflags()));
42350b57cec5SDimitry Andric     NameVals.push_back(FS->entryCount());
42360b57cec5SDimitry Andric 
42370b57cec5SDimitry Andric     // Fill in below
42380b57cec5SDimitry Andric     NameVals.push_back(0); // numrefs
42390b57cec5SDimitry Andric     NameVals.push_back(0); // rorefcnt
42400b57cec5SDimitry Andric     NameVals.push_back(0); // worefcnt
42410b57cec5SDimitry Andric 
42420b57cec5SDimitry Andric     unsigned Count = 0, RORefCnt = 0, WORefCnt = 0;
42430b57cec5SDimitry Andric     for (auto &RI : FS->refs()) {
42440b57cec5SDimitry Andric       auto RefValueId = getValueId(RI.getGUID());
42450b57cec5SDimitry Andric       if (!RefValueId)
42460b57cec5SDimitry Andric         continue;
42470b57cec5SDimitry Andric       NameVals.push_back(*RefValueId);
42480b57cec5SDimitry Andric       if (RI.isReadOnly())
42490b57cec5SDimitry Andric         RORefCnt++;
42500b57cec5SDimitry Andric       else if (RI.isWriteOnly())
42510b57cec5SDimitry Andric         WORefCnt++;
42520b57cec5SDimitry Andric       Count++;
42530b57cec5SDimitry Andric     }
42540b57cec5SDimitry Andric     NameVals[6] = Count;
42550b57cec5SDimitry Andric     NameVals[7] = RORefCnt;
42560b57cec5SDimitry Andric     NameVals[8] = WORefCnt;
42570b57cec5SDimitry Andric 
42580b57cec5SDimitry Andric     bool HasProfileData = false;
42590b57cec5SDimitry Andric     for (auto &EI : FS->calls()) {
42600b57cec5SDimitry Andric       HasProfileData |=
42610b57cec5SDimitry Andric           EI.second.getHotness() != CalleeInfo::HotnessType::Unknown;
42620b57cec5SDimitry Andric       if (HasProfileData)
42630b57cec5SDimitry Andric         break;
42640b57cec5SDimitry Andric     }
42650b57cec5SDimitry Andric 
42660b57cec5SDimitry Andric     for (auto &EI : FS->calls()) {
42670b57cec5SDimitry Andric       // If this GUID doesn't have a value id, it doesn't have a function
42680b57cec5SDimitry Andric       // summary and we don't need to record any calls to it.
4269af732203SDimitry Andric       Optional<unsigned> CallValueId = GetValueId(EI.first);
42700b57cec5SDimitry Andric       if (!CallValueId)
42710b57cec5SDimitry Andric         continue;
42720b57cec5SDimitry Andric       NameVals.push_back(*CallValueId);
42730b57cec5SDimitry Andric       if (HasProfileData)
42740b57cec5SDimitry Andric         NameVals.push_back(static_cast<uint8_t>(EI.second.Hotness));
42750b57cec5SDimitry Andric     }
42760b57cec5SDimitry Andric 
42770b57cec5SDimitry Andric     unsigned FSAbbrev = (HasProfileData ? FSCallsProfileAbbrev : FSCallsAbbrev);
42780b57cec5SDimitry Andric     unsigned Code =
42790b57cec5SDimitry Andric         (HasProfileData ? bitc::FS_COMBINED_PROFILE : bitc::FS_COMBINED);
42800b57cec5SDimitry Andric 
42810b57cec5SDimitry Andric     // Emit the finished record.
42820b57cec5SDimitry Andric     Stream.EmitRecord(Code, NameVals, FSAbbrev);
42830b57cec5SDimitry Andric     NameVals.clear();
42840b57cec5SDimitry Andric     MaybeEmitOriginalName(*S);
42850b57cec5SDimitry Andric   });
42860b57cec5SDimitry Andric 
42870b57cec5SDimitry Andric   for (auto *AS : Aliases) {
42880b57cec5SDimitry Andric     auto AliasValueId = SummaryToValueIdMap[AS];
42890b57cec5SDimitry Andric     assert(AliasValueId);
42900b57cec5SDimitry Andric     NameVals.push_back(AliasValueId);
42910b57cec5SDimitry Andric     NameVals.push_back(Index.getModuleId(AS->modulePath()));
42920b57cec5SDimitry Andric     NameVals.push_back(getEncodedGVSummaryFlags(AS->flags()));
42930b57cec5SDimitry Andric     auto AliaseeValueId = SummaryToValueIdMap[&AS->getAliasee()];
42940b57cec5SDimitry Andric     assert(AliaseeValueId);
42950b57cec5SDimitry Andric     NameVals.push_back(AliaseeValueId);
42960b57cec5SDimitry Andric 
42970b57cec5SDimitry Andric     // Emit the finished record.
42980b57cec5SDimitry Andric     Stream.EmitRecord(bitc::FS_COMBINED_ALIAS, NameVals, FSAliasAbbrev);
42990b57cec5SDimitry Andric     NameVals.clear();
43000b57cec5SDimitry Andric     MaybeEmitOriginalName(*AS);
43010b57cec5SDimitry Andric 
43020b57cec5SDimitry Andric     if (auto *FS = dyn_cast<FunctionSummary>(&AS->getAliasee()))
43030b57cec5SDimitry Andric       getReferencedTypeIds(FS, ReferencedTypeIds);
43040b57cec5SDimitry Andric   }
43050b57cec5SDimitry Andric 
43060b57cec5SDimitry Andric   if (!Index.cfiFunctionDefs().empty()) {
43070b57cec5SDimitry Andric     for (auto &S : Index.cfiFunctionDefs()) {
43080b57cec5SDimitry Andric       if (DefOrUseGUIDs.count(
43090b57cec5SDimitry Andric               GlobalValue::getGUID(GlobalValue::dropLLVMManglingEscape(S)))) {
43100b57cec5SDimitry Andric         NameVals.push_back(StrtabBuilder.add(S));
43110b57cec5SDimitry Andric         NameVals.push_back(S.size());
43120b57cec5SDimitry Andric       }
43130b57cec5SDimitry Andric     }
43140b57cec5SDimitry Andric     if (!NameVals.empty()) {
43150b57cec5SDimitry Andric       Stream.EmitRecord(bitc::FS_CFI_FUNCTION_DEFS, NameVals);
43160b57cec5SDimitry Andric       NameVals.clear();
43170b57cec5SDimitry Andric     }
43180b57cec5SDimitry Andric   }
43190b57cec5SDimitry Andric 
43200b57cec5SDimitry Andric   if (!Index.cfiFunctionDecls().empty()) {
43210b57cec5SDimitry Andric     for (auto &S : Index.cfiFunctionDecls()) {
43220b57cec5SDimitry Andric       if (DefOrUseGUIDs.count(
43230b57cec5SDimitry Andric               GlobalValue::getGUID(GlobalValue::dropLLVMManglingEscape(S)))) {
43240b57cec5SDimitry Andric         NameVals.push_back(StrtabBuilder.add(S));
43250b57cec5SDimitry Andric         NameVals.push_back(S.size());
43260b57cec5SDimitry Andric       }
43270b57cec5SDimitry Andric     }
43280b57cec5SDimitry Andric     if (!NameVals.empty()) {
43290b57cec5SDimitry Andric       Stream.EmitRecord(bitc::FS_CFI_FUNCTION_DECLS, NameVals);
43300b57cec5SDimitry Andric       NameVals.clear();
43310b57cec5SDimitry Andric     }
43320b57cec5SDimitry Andric   }
43330b57cec5SDimitry Andric 
43340b57cec5SDimitry Andric   // Walk the GUIDs that were referenced, and write the
43350b57cec5SDimitry Andric   // corresponding type id records.
43360b57cec5SDimitry Andric   for (auto &T : ReferencedTypeIds) {
43370b57cec5SDimitry Andric     auto TidIter = Index.typeIds().equal_range(T);
43380b57cec5SDimitry Andric     for (auto It = TidIter.first; It != TidIter.second; ++It) {
43390b57cec5SDimitry Andric       writeTypeIdSummaryRecord(NameVals, StrtabBuilder, It->second.first,
43400b57cec5SDimitry Andric                                It->second.second);
43410b57cec5SDimitry Andric       Stream.EmitRecord(bitc::FS_TYPE_ID, NameVals);
43420b57cec5SDimitry Andric       NameVals.clear();
43430b57cec5SDimitry Andric     }
43440b57cec5SDimitry Andric   }
43450b57cec5SDimitry Andric 
43465ffd83dbSDimitry Andric   Stream.EmitRecord(bitc::FS_BLOCK_COUNT,
43475ffd83dbSDimitry Andric                     ArrayRef<uint64_t>{Index.getBlockCount()});
43485ffd83dbSDimitry Andric 
43490b57cec5SDimitry Andric   Stream.ExitBlock();
43500b57cec5SDimitry Andric }
43510b57cec5SDimitry Andric 
43520b57cec5SDimitry Andric /// Create the "IDENTIFICATION_BLOCK_ID" containing a single string with the
43530b57cec5SDimitry Andric /// current llvm version, and a record for the epoch number.
writeIdentificationBlock(BitstreamWriter & Stream)43540b57cec5SDimitry Andric static void writeIdentificationBlock(BitstreamWriter &Stream) {
43550b57cec5SDimitry Andric   Stream.EnterSubblock(bitc::IDENTIFICATION_BLOCK_ID, 5);
43560b57cec5SDimitry Andric 
43570b57cec5SDimitry Andric   // Write the "user readable" string identifying the bitcode producer
43580b57cec5SDimitry Andric   auto Abbv = std::make_shared<BitCodeAbbrev>();
43590b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::IDENTIFICATION_CODE_STRING));
43600b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
43610b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
43620b57cec5SDimitry Andric   auto StringAbbrev = Stream.EmitAbbrev(std::move(Abbv));
43630b57cec5SDimitry Andric   writeStringRecord(Stream, bitc::IDENTIFICATION_CODE_STRING,
43640b57cec5SDimitry Andric                     "LLVM" LLVM_VERSION_STRING, StringAbbrev);
43650b57cec5SDimitry Andric 
43660b57cec5SDimitry Andric   // Write the epoch version
43670b57cec5SDimitry Andric   Abbv = std::make_shared<BitCodeAbbrev>();
43680b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::IDENTIFICATION_CODE_EPOCH));
43690b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
43700b57cec5SDimitry Andric   auto EpochAbbrev = Stream.EmitAbbrev(std::move(Abbv));
43715ffd83dbSDimitry Andric   constexpr std::array<unsigned, 1> Vals = {{bitc::BITCODE_CURRENT_EPOCH}};
43720b57cec5SDimitry Andric   Stream.EmitRecord(bitc::IDENTIFICATION_CODE_EPOCH, Vals, EpochAbbrev);
43730b57cec5SDimitry Andric   Stream.ExitBlock();
43740b57cec5SDimitry Andric }
43750b57cec5SDimitry Andric 
writeModuleHash(size_t BlockStartPos)43760b57cec5SDimitry Andric void ModuleBitcodeWriter::writeModuleHash(size_t BlockStartPos) {
43770b57cec5SDimitry Andric   // Emit the module's hash.
43780b57cec5SDimitry Andric   // MODULE_CODE_HASH: [5*i32]
43790b57cec5SDimitry Andric   if (GenerateHash) {
43800b57cec5SDimitry Andric     uint32_t Vals[5];
43810b57cec5SDimitry Andric     Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&(Buffer)[BlockStartPos],
43820b57cec5SDimitry Andric                                     Buffer.size() - BlockStartPos));
43830b57cec5SDimitry Andric     StringRef Hash = Hasher.result();
43840b57cec5SDimitry Andric     for (int Pos = 0; Pos < 20; Pos += 4) {
43850b57cec5SDimitry Andric       Vals[Pos / 4] = support::endian::read32be(Hash.data() + Pos);
43860b57cec5SDimitry Andric     }
43870b57cec5SDimitry Andric 
43880b57cec5SDimitry Andric     // Emit the finished record.
43890b57cec5SDimitry Andric     Stream.EmitRecord(bitc::MODULE_CODE_HASH, Vals);
43900b57cec5SDimitry Andric 
43910b57cec5SDimitry Andric     if (ModHash)
43920b57cec5SDimitry Andric       // Save the written hash value.
43930b57cec5SDimitry Andric       llvm::copy(Vals, std::begin(*ModHash));
43940b57cec5SDimitry Andric   }
43950b57cec5SDimitry Andric }
43960b57cec5SDimitry Andric 
write()43970b57cec5SDimitry Andric void ModuleBitcodeWriter::write() {
43980b57cec5SDimitry Andric   writeIdentificationBlock(Stream);
43990b57cec5SDimitry Andric 
44000b57cec5SDimitry Andric   Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
44010b57cec5SDimitry Andric   size_t BlockStartPos = Buffer.size();
44020b57cec5SDimitry Andric 
44030b57cec5SDimitry Andric   writeModuleVersion();
44040b57cec5SDimitry Andric 
44050b57cec5SDimitry Andric   // Emit blockinfo, which defines the standard abbreviations etc.
44060b57cec5SDimitry Andric   writeBlockInfo();
44070b57cec5SDimitry Andric 
44080b57cec5SDimitry Andric   // Emit information describing all of the types in the module.
44090b57cec5SDimitry Andric   writeTypeTable();
44100b57cec5SDimitry Andric 
44110b57cec5SDimitry Andric   // Emit information about attribute groups.
44120b57cec5SDimitry Andric   writeAttributeGroupTable();
44130b57cec5SDimitry Andric 
44140b57cec5SDimitry Andric   // Emit information about parameter attributes.
44150b57cec5SDimitry Andric   writeAttributeTable();
44160b57cec5SDimitry Andric 
44170b57cec5SDimitry Andric   writeComdats();
44180b57cec5SDimitry Andric 
44190b57cec5SDimitry Andric   // Emit top-level description of module, including target triple, inline asm,
44200b57cec5SDimitry Andric   // descriptors for global variables, and function prototype info.
44210b57cec5SDimitry Andric   writeModuleInfo();
44220b57cec5SDimitry Andric 
44230b57cec5SDimitry Andric   // Emit constants.
44240b57cec5SDimitry Andric   writeModuleConstants();
44250b57cec5SDimitry Andric 
44260b57cec5SDimitry Andric   // Emit metadata kind names.
44270b57cec5SDimitry Andric   writeModuleMetadataKinds();
44280b57cec5SDimitry Andric 
44290b57cec5SDimitry Andric   // Emit metadata.
44300b57cec5SDimitry Andric   writeModuleMetadata();
44310b57cec5SDimitry Andric 
44320b57cec5SDimitry Andric   // Emit module-level use-lists.
44330b57cec5SDimitry Andric   if (VE.shouldPreserveUseListOrder())
44340b57cec5SDimitry Andric     writeUseListBlock(nullptr);
44350b57cec5SDimitry Andric 
44360b57cec5SDimitry Andric   writeOperandBundleTags();
44370b57cec5SDimitry Andric   writeSyncScopeNames();
44380b57cec5SDimitry Andric 
44390b57cec5SDimitry Andric   // Emit function bodies.
44400b57cec5SDimitry Andric   DenseMap<const Function *, uint64_t> FunctionToBitcodeIndex;
44410b57cec5SDimitry Andric   for (Module::const_iterator F = M.begin(), E = M.end(); F != E; ++F)
44420b57cec5SDimitry Andric     if (!F->isDeclaration())
44430b57cec5SDimitry Andric       writeFunction(*F, FunctionToBitcodeIndex);
44440b57cec5SDimitry Andric 
44450b57cec5SDimitry Andric   // Need to write after the above call to WriteFunction which populates
44460b57cec5SDimitry Andric   // the summary information in the index.
44470b57cec5SDimitry Andric   if (Index)
44480b57cec5SDimitry Andric     writePerModuleGlobalValueSummary();
44490b57cec5SDimitry Andric 
44500b57cec5SDimitry Andric   writeGlobalValueSymbolTable(FunctionToBitcodeIndex);
44510b57cec5SDimitry Andric 
44520b57cec5SDimitry Andric   writeModuleHash(BlockStartPos);
44530b57cec5SDimitry Andric 
44540b57cec5SDimitry Andric   Stream.ExitBlock();
44550b57cec5SDimitry Andric }
44560b57cec5SDimitry Andric 
writeInt32ToBuffer(uint32_t Value,SmallVectorImpl<char> & Buffer,uint32_t & Position)44570b57cec5SDimitry Andric static void writeInt32ToBuffer(uint32_t Value, SmallVectorImpl<char> &Buffer,
44580b57cec5SDimitry Andric                                uint32_t &Position) {
44590b57cec5SDimitry Andric   support::endian::write32le(&Buffer[Position], Value);
44600b57cec5SDimitry Andric   Position += 4;
44610b57cec5SDimitry Andric }
44620b57cec5SDimitry Andric 
44630b57cec5SDimitry Andric /// If generating a bc file on darwin, we have to emit a
44640b57cec5SDimitry Andric /// header and trailer to make it compatible with the system archiver.  To do
44650b57cec5SDimitry Andric /// this we emit the following header, and then emit a trailer that pads the
44660b57cec5SDimitry Andric /// file out to be a multiple of 16 bytes.
44670b57cec5SDimitry Andric ///
44680b57cec5SDimitry Andric /// struct bc_header {
44690b57cec5SDimitry Andric ///   uint32_t Magic;         // 0x0B17C0DE
44700b57cec5SDimitry Andric ///   uint32_t Version;       // Version, currently always 0.
44710b57cec5SDimitry Andric ///   uint32_t BitcodeOffset; // Offset to traditional bitcode file.
44720b57cec5SDimitry Andric ///   uint32_t BitcodeSize;   // Size of traditional bitcode file.
44730b57cec5SDimitry Andric ///   uint32_t CPUType;       // CPU specifier.
44740b57cec5SDimitry Andric ///   ... potentially more later ...
44750b57cec5SDimitry Andric /// };
emitDarwinBCHeaderAndTrailer(SmallVectorImpl<char> & Buffer,const Triple & TT)44760b57cec5SDimitry Andric static void emitDarwinBCHeaderAndTrailer(SmallVectorImpl<char> &Buffer,
44770b57cec5SDimitry Andric                                          const Triple &TT) {
44780b57cec5SDimitry Andric   unsigned CPUType = ~0U;
44790b57cec5SDimitry Andric 
44800b57cec5SDimitry Andric   // Match x86_64-*, i[3-9]86-*, powerpc-*, powerpc64-*, arm-*, thumb-*,
44810b57cec5SDimitry Andric   // armv[0-9]-*, thumbv[0-9]-*, armv5te-*, or armv6t2-*. The CPUType is a magic
44820b57cec5SDimitry Andric   // number from /usr/include/mach/machine.h.  It is ok to reproduce the
44830b57cec5SDimitry Andric   // specific constants here because they are implicitly part of the Darwin ABI.
44840b57cec5SDimitry Andric   enum {
44850b57cec5SDimitry Andric     DARWIN_CPU_ARCH_ABI64      = 0x01000000,
44860b57cec5SDimitry Andric     DARWIN_CPU_TYPE_X86        = 7,
44870b57cec5SDimitry Andric     DARWIN_CPU_TYPE_ARM        = 12,
44880b57cec5SDimitry Andric     DARWIN_CPU_TYPE_POWERPC    = 18
44890b57cec5SDimitry Andric   };
44900b57cec5SDimitry Andric 
44910b57cec5SDimitry Andric   Triple::ArchType Arch = TT.getArch();
44920b57cec5SDimitry Andric   if (Arch == Triple::x86_64)
44930b57cec5SDimitry Andric     CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64;
44940b57cec5SDimitry Andric   else if (Arch == Triple::x86)
44950b57cec5SDimitry Andric     CPUType = DARWIN_CPU_TYPE_X86;
44960b57cec5SDimitry Andric   else if (Arch == Triple::ppc)
44970b57cec5SDimitry Andric     CPUType = DARWIN_CPU_TYPE_POWERPC;
44980b57cec5SDimitry Andric   else if (Arch == Triple::ppc64)
44990b57cec5SDimitry Andric     CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64;
45000b57cec5SDimitry Andric   else if (Arch == Triple::arm || Arch == Triple::thumb)
45010b57cec5SDimitry Andric     CPUType = DARWIN_CPU_TYPE_ARM;
45020b57cec5SDimitry Andric 
45030b57cec5SDimitry Andric   // Traditional Bitcode starts after header.
45040b57cec5SDimitry Andric   assert(Buffer.size() >= BWH_HeaderSize &&
45050b57cec5SDimitry Andric          "Expected header size to be reserved");
45060b57cec5SDimitry Andric   unsigned BCOffset = BWH_HeaderSize;
45070b57cec5SDimitry Andric   unsigned BCSize = Buffer.size() - BWH_HeaderSize;
45080b57cec5SDimitry Andric 
45090b57cec5SDimitry Andric   // Write the magic and version.
45100b57cec5SDimitry Andric   unsigned Position = 0;
45110b57cec5SDimitry Andric   writeInt32ToBuffer(0x0B17C0DE, Buffer, Position);
45120b57cec5SDimitry Andric   writeInt32ToBuffer(0, Buffer, Position); // Version.
45130b57cec5SDimitry Andric   writeInt32ToBuffer(BCOffset, Buffer, Position);
45140b57cec5SDimitry Andric   writeInt32ToBuffer(BCSize, Buffer, Position);
45150b57cec5SDimitry Andric   writeInt32ToBuffer(CPUType, Buffer, Position);
45160b57cec5SDimitry Andric 
45170b57cec5SDimitry Andric   // If the file is not a multiple of 16 bytes, insert dummy padding.
45180b57cec5SDimitry Andric   while (Buffer.size() & 15)
45190b57cec5SDimitry Andric     Buffer.push_back(0);
45200b57cec5SDimitry Andric }
45210b57cec5SDimitry Andric 
45220b57cec5SDimitry Andric /// Helper to write the header common to all bitcode files.
writeBitcodeHeader(BitstreamWriter & Stream)45230b57cec5SDimitry Andric static void writeBitcodeHeader(BitstreamWriter &Stream) {
45240b57cec5SDimitry Andric   // Emit the file header.
45250b57cec5SDimitry Andric   Stream.Emit((unsigned)'B', 8);
45260b57cec5SDimitry Andric   Stream.Emit((unsigned)'C', 8);
45270b57cec5SDimitry Andric   Stream.Emit(0x0, 4);
45280b57cec5SDimitry Andric   Stream.Emit(0xC, 4);
45290b57cec5SDimitry Andric   Stream.Emit(0xE, 4);
45300b57cec5SDimitry Andric   Stream.Emit(0xD, 4);
45310b57cec5SDimitry Andric }
45320b57cec5SDimitry Andric 
BitcodeWriter(SmallVectorImpl<char> & Buffer,raw_fd_stream * FS)4533af732203SDimitry Andric BitcodeWriter::BitcodeWriter(SmallVectorImpl<char> &Buffer, raw_fd_stream *FS)
4534af732203SDimitry Andric     : Buffer(Buffer), Stream(new BitstreamWriter(Buffer, FS, FlushThreshold)) {
45350b57cec5SDimitry Andric   writeBitcodeHeader(*Stream);
45360b57cec5SDimitry Andric }
45370b57cec5SDimitry Andric 
~BitcodeWriter()45380b57cec5SDimitry Andric BitcodeWriter::~BitcodeWriter() { assert(WroteStrtab); }
45390b57cec5SDimitry Andric 
writeBlob(unsigned Block,unsigned Record,StringRef Blob)45400b57cec5SDimitry Andric void BitcodeWriter::writeBlob(unsigned Block, unsigned Record, StringRef Blob) {
45410b57cec5SDimitry Andric   Stream->EnterSubblock(Block, 3);
45420b57cec5SDimitry Andric 
45430b57cec5SDimitry Andric   auto Abbv = std::make_shared<BitCodeAbbrev>();
45440b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(Record));
45450b57cec5SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
45460b57cec5SDimitry Andric   auto AbbrevNo = Stream->EmitAbbrev(std::move(Abbv));
45470b57cec5SDimitry Andric 
45480b57cec5SDimitry Andric   Stream->EmitRecordWithBlob(AbbrevNo, ArrayRef<uint64_t>{Record}, Blob);
45490b57cec5SDimitry Andric 
45500b57cec5SDimitry Andric   Stream->ExitBlock();
45510b57cec5SDimitry Andric }
45520b57cec5SDimitry Andric 
writeSymtab()45530b57cec5SDimitry Andric void BitcodeWriter::writeSymtab() {
45540b57cec5SDimitry Andric   assert(!WroteStrtab && !WroteSymtab);
45550b57cec5SDimitry Andric 
45560b57cec5SDimitry Andric   // If any module has module-level inline asm, we will require a registered asm
45570b57cec5SDimitry Andric   // parser for the target so that we can create an accurate symbol table for
45580b57cec5SDimitry Andric   // the module.
45590b57cec5SDimitry Andric   for (Module *M : Mods) {
45600b57cec5SDimitry Andric     if (M->getModuleInlineAsm().empty())
45610b57cec5SDimitry Andric       continue;
45620b57cec5SDimitry Andric 
45630b57cec5SDimitry Andric     std::string Err;
45640b57cec5SDimitry Andric     const Triple TT(M->getTargetTriple());
45650b57cec5SDimitry Andric     const Target *T = TargetRegistry::lookupTarget(TT.str(), Err);
45660b57cec5SDimitry Andric     if (!T || !T->hasMCAsmParser())
45670b57cec5SDimitry Andric       return;
45680b57cec5SDimitry Andric   }
45690b57cec5SDimitry Andric 
45700b57cec5SDimitry Andric   WroteSymtab = true;
45710b57cec5SDimitry Andric   SmallVector<char, 0> Symtab;
45720b57cec5SDimitry Andric   // The irsymtab::build function may be unable to create a symbol table if the
45730b57cec5SDimitry Andric   // module is malformed (e.g. it contains an invalid alias). Writing a symbol
45740b57cec5SDimitry Andric   // table is not required for correctness, but we still want to be able to
45750b57cec5SDimitry Andric   // write malformed modules to bitcode files, so swallow the error.
45760b57cec5SDimitry Andric   if (Error E = irsymtab::build(Mods, Symtab, StrtabBuilder, Alloc)) {
45770b57cec5SDimitry Andric     consumeError(std::move(E));
45780b57cec5SDimitry Andric     return;
45790b57cec5SDimitry Andric   }
45800b57cec5SDimitry Andric 
45810b57cec5SDimitry Andric   writeBlob(bitc::SYMTAB_BLOCK_ID, bitc::SYMTAB_BLOB,
45820b57cec5SDimitry Andric             {Symtab.data(), Symtab.size()});
45830b57cec5SDimitry Andric }
45840b57cec5SDimitry Andric 
writeStrtab()45850b57cec5SDimitry Andric void BitcodeWriter::writeStrtab() {
45860b57cec5SDimitry Andric   assert(!WroteStrtab);
45870b57cec5SDimitry Andric 
45880b57cec5SDimitry Andric   std::vector<char> Strtab;
45890b57cec5SDimitry Andric   StrtabBuilder.finalizeInOrder();
45900b57cec5SDimitry Andric   Strtab.resize(StrtabBuilder.getSize());
45910b57cec5SDimitry Andric   StrtabBuilder.write((uint8_t *)Strtab.data());
45920b57cec5SDimitry Andric 
45930b57cec5SDimitry Andric   writeBlob(bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB,
45940b57cec5SDimitry Andric             {Strtab.data(), Strtab.size()});
45950b57cec5SDimitry Andric 
45960b57cec5SDimitry Andric   WroteStrtab = true;
45970b57cec5SDimitry Andric }
45980b57cec5SDimitry Andric 
copyStrtab(StringRef Strtab)45990b57cec5SDimitry Andric void BitcodeWriter::copyStrtab(StringRef Strtab) {
46000b57cec5SDimitry Andric   writeBlob(bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB, Strtab);
46010b57cec5SDimitry Andric   WroteStrtab = true;
46020b57cec5SDimitry Andric }
46030b57cec5SDimitry Andric 
writeModule(const Module & M,bool ShouldPreserveUseListOrder,const ModuleSummaryIndex * Index,bool GenerateHash,ModuleHash * ModHash)46040b57cec5SDimitry Andric void BitcodeWriter::writeModule(const Module &M,
46050b57cec5SDimitry Andric                                 bool ShouldPreserveUseListOrder,
46060b57cec5SDimitry Andric                                 const ModuleSummaryIndex *Index,
46070b57cec5SDimitry Andric                                 bool GenerateHash, ModuleHash *ModHash) {
46080b57cec5SDimitry Andric   assert(!WroteStrtab);
46090b57cec5SDimitry Andric 
46100b57cec5SDimitry Andric   // The Mods vector is used by irsymtab::build, which requires non-const
46110b57cec5SDimitry Andric   // Modules in case it needs to materialize metadata. But the bitcode writer
46120b57cec5SDimitry Andric   // requires that the module is materialized, so we can cast to non-const here,
46130b57cec5SDimitry Andric   // after checking that it is in fact materialized.
46140b57cec5SDimitry Andric   assert(M.isMaterialized());
46150b57cec5SDimitry Andric   Mods.push_back(const_cast<Module *>(&M));
46160b57cec5SDimitry Andric 
46170b57cec5SDimitry Andric   ModuleBitcodeWriter ModuleWriter(M, Buffer, StrtabBuilder, *Stream,
46180b57cec5SDimitry Andric                                    ShouldPreserveUseListOrder, Index,
46190b57cec5SDimitry Andric                                    GenerateHash, ModHash);
46200b57cec5SDimitry Andric   ModuleWriter.write();
46210b57cec5SDimitry Andric }
46220b57cec5SDimitry Andric 
writeIndex(const ModuleSummaryIndex * Index,const std::map<std::string,GVSummaryMapTy> * ModuleToSummariesForIndex)46230b57cec5SDimitry Andric void BitcodeWriter::writeIndex(
46240b57cec5SDimitry Andric     const ModuleSummaryIndex *Index,
46250b57cec5SDimitry Andric     const std::map<std::string, GVSummaryMapTy> *ModuleToSummariesForIndex) {
46260b57cec5SDimitry Andric   IndexBitcodeWriter IndexWriter(*Stream, StrtabBuilder, *Index,
46270b57cec5SDimitry Andric                                  ModuleToSummariesForIndex);
46280b57cec5SDimitry Andric   IndexWriter.write();
46290b57cec5SDimitry Andric }
46300b57cec5SDimitry Andric 
46310b57cec5SDimitry 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)46320b57cec5SDimitry Andric void llvm::WriteBitcodeToFile(const Module &M, raw_ostream &Out,
46330b57cec5SDimitry Andric                               bool ShouldPreserveUseListOrder,
46340b57cec5SDimitry Andric                               const ModuleSummaryIndex *Index,
46350b57cec5SDimitry Andric                               bool GenerateHash, ModuleHash *ModHash) {
46360b57cec5SDimitry Andric   SmallVector<char, 0> Buffer;
46370b57cec5SDimitry Andric   Buffer.reserve(256*1024);
46380b57cec5SDimitry Andric 
46390b57cec5SDimitry Andric   // If this is darwin or another generic macho target, reserve space for the
46400b57cec5SDimitry Andric   // header.
46410b57cec5SDimitry Andric   Triple TT(M.getTargetTriple());
46420b57cec5SDimitry Andric   if (TT.isOSDarwin() || TT.isOSBinFormatMachO())
46430b57cec5SDimitry Andric     Buffer.insert(Buffer.begin(), BWH_HeaderSize, 0);
46440b57cec5SDimitry Andric 
4645af732203SDimitry Andric   BitcodeWriter Writer(Buffer, dyn_cast<raw_fd_stream>(&Out));
46460b57cec5SDimitry Andric   Writer.writeModule(M, ShouldPreserveUseListOrder, Index, GenerateHash,
46470b57cec5SDimitry Andric                      ModHash);
46480b57cec5SDimitry Andric   Writer.writeSymtab();
46490b57cec5SDimitry Andric   Writer.writeStrtab();
46500b57cec5SDimitry Andric 
46510b57cec5SDimitry Andric   if (TT.isOSDarwin() || TT.isOSBinFormatMachO())
46520b57cec5SDimitry Andric     emitDarwinBCHeaderAndTrailer(Buffer, TT);
46530b57cec5SDimitry Andric 
46540b57cec5SDimitry Andric   // Write the generated bitstream to "Out".
4655af732203SDimitry Andric   if (!Buffer.empty())
46560b57cec5SDimitry Andric     Out.write((char *)&Buffer.front(), Buffer.size());
46570b57cec5SDimitry Andric }
46580b57cec5SDimitry Andric 
write()46590b57cec5SDimitry Andric void IndexBitcodeWriter::write() {
46600b57cec5SDimitry Andric   Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
46610b57cec5SDimitry Andric 
46620b57cec5SDimitry Andric   writeModuleVersion();
46630b57cec5SDimitry Andric 
46640b57cec5SDimitry Andric   // Write the module paths in the combined index.
46650b57cec5SDimitry Andric   writeModStrings();
46660b57cec5SDimitry Andric 
46670b57cec5SDimitry Andric   // Write the summary combined index records.
46680b57cec5SDimitry Andric   writeCombinedGlobalValueSummary();
46690b57cec5SDimitry Andric 
46700b57cec5SDimitry Andric   Stream.ExitBlock();
46710b57cec5SDimitry Andric }
46720b57cec5SDimitry Andric 
46730b57cec5SDimitry Andric // Write the specified module summary index to the given raw output stream,
46740b57cec5SDimitry Andric // where it will be written in a new bitcode block. This is used when
46750b57cec5SDimitry Andric // writing the combined index file for ThinLTO. When writing a subset of the
46760b57cec5SDimitry 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)46770b57cec5SDimitry Andric void llvm::WriteIndexToFile(
46780b57cec5SDimitry Andric     const ModuleSummaryIndex &Index, raw_ostream &Out,
46790b57cec5SDimitry Andric     const std::map<std::string, GVSummaryMapTy> *ModuleToSummariesForIndex) {
46800b57cec5SDimitry Andric   SmallVector<char, 0> Buffer;
46810b57cec5SDimitry Andric   Buffer.reserve(256 * 1024);
46820b57cec5SDimitry Andric 
46830b57cec5SDimitry Andric   BitcodeWriter Writer(Buffer);
46840b57cec5SDimitry Andric   Writer.writeIndex(&Index, ModuleToSummariesForIndex);
46850b57cec5SDimitry Andric   Writer.writeStrtab();
46860b57cec5SDimitry Andric 
46870b57cec5SDimitry Andric   Out.write((char *)&Buffer.front(), Buffer.size());
46880b57cec5SDimitry Andric }
46890b57cec5SDimitry Andric 
46900b57cec5SDimitry Andric namespace {
46910b57cec5SDimitry Andric 
46920b57cec5SDimitry Andric /// Class to manage the bitcode writing for a thin link bitcode file.
46930b57cec5SDimitry Andric class ThinLinkBitcodeWriter : public ModuleBitcodeWriterBase {
46940b57cec5SDimitry Andric   /// ModHash is for use in ThinLTO incremental build, generated while writing
46950b57cec5SDimitry Andric   /// the module bitcode file.
46960b57cec5SDimitry Andric   const ModuleHash *ModHash;
46970b57cec5SDimitry Andric 
46980b57cec5SDimitry Andric public:
ThinLinkBitcodeWriter(const Module & M,StringTableBuilder & StrtabBuilder,BitstreamWriter & Stream,const ModuleSummaryIndex & Index,const ModuleHash & ModHash)46990b57cec5SDimitry Andric   ThinLinkBitcodeWriter(const Module &M, StringTableBuilder &StrtabBuilder,
47000b57cec5SDimitry Andric                         BitstreamWriter &Stream,
47010b57cec5SDimitry Andric                         const ModuleSummaryIndex &Index,
47020b57cec5SDimitry Andric                         const ModuleHash &ModHash)
47030b57cec5SDimitry Andric       : ModuleBitcodeWriterBase(M, StrtabBuilder, Stream,
47040b57cec5SDimitry Andric                                 /*ShouldPreserveUseListOrder=*/false, &Index),
47050b57cec5SDimitry Andric         ModHash(&ModHash) {}
47060b57cec5SDimitry Andric 
47070b57cec5SDimitry Andric   void write();
47080b57cec5SDimitry Andric 
47090b57cec5SDimitry Andric private:
47100b57cec5SDimitry Andric   void writeSimplifiedModuleInfo();
47110b57cec5SDimitry Andric };
47120b57cec5SDimitry Andric 
47130b57cec5SDimitry Andric } // end anonymous namespace
47140b57cec5SDimitry Andric 
47150b57cec5SDimitry Andric // This function writes a simpilified module info for thin link bitcode file.
47160b57cec5SDimitry Andric // It only contains the source file name along with the name(the offset and
47170b57cec5SDimitry Andric // size in strtab) and linkage for global values. For the global value info
47180b57cec5SDimitry Andric // entry, in order to keep linkage at offset 5, there are three zeros used
47190b57cec5SDimitry Andric // as padding.
writeSimplifiedModuleInfo()47200b57cec5SDimitry Andric void ThinLinkBitcodeWriter::writeSimplifiedModuleInfo() {
47210b57cec5SDimitry Andric   SmallVector<unsigned, 64> Vals;
47220b57cec5SDimitry Andric   // Emit the module's source file name.
47230b57cec5SDimitry Andric   {
47240b57cec5SDimitry Andric     StringEncoding Bits = getStringEncoding(M.getSourceFileName());
47250b57cec5SDimitry Andric     BitCodeAbbrevOp AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8);
47260b57cec5SDimitry Andric     if (Bits == SE_Char6)
47270b57cec5SDimitry Andric       AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Char6);
47280b57cec5SDimitry Andric     else if (Bits == SE_Fixed7)
47290b57cec5SDimitry Andric       AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7);
47300b57cec5SDimitry Andric 
47310b57cec5SDimitry Andric     // MODULE_CODE_SOURCE_FILENAME: [namechar x N]
47320b57cec5SDimitry Andric     auto Abbv = std::make_shared<BitCodeAbbrev>();
47330b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_SOURCE_FILENAME));
47340b57cec5SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
47350b57cec5SDimitry Andric     Abbv->Add(AbbrevOpToUse);
47360b57cec5SDimitry Andric     unsigned FilenameAbbrev = Stream.EmitAbbrev(std::move(Abbv));
47370b57cec5SDimitry Andric 
47380b57cec5SDimitry Andric     for (const auto P : M.getSourceFileName())
47390b57cec5SDimitry Andric       Vals.push_back((unsigned char)P);
47400b57cec5SDimitry Andric 
47410b57cec5SDimitry Andric     Stream.EmitRecord(bitc::MODULE_CODE_SOURCE_FILENAME, Vals, FilenameAbbrev);
47420b57cec5SDimitry Andric     Vals.clear();
47430b57cec5SDimitry Andric   }
47440b57cec5SDimitry Andric 
47450b57cec5SDimitry Andric   // Emit the global variable information.
47460b57cec5SDimitry Andric   for (const GlobalVariable &GV : M.globals()) {
47470b57cec5SDimitry Andric     // GLOBALVAR: [strtab offset, strtab size, 0, 0, 0, linkage]
47480b57cec5SDimitry Andric     Vals.push_back(StrtabBuilder.add(GV.getName()));
47490b57cec5SDimitry Andric     Vals.push_back(GV.getName().size());
47500b57cec5SDimitry Andric     Vals.push_back(0);
47510b57cec5SDimitry Andric     Vals.push_back(0);
47520b57cec5SDimitry Andric     Vals.push_back(0);
47530b57cec5SDimitry Andric     Vals.push_back(getEncodedLinkage(GV));
47540b57cec5SDimitry Andric 
47550b57cec5SDimitry Andric     Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals);
47560b57cec5SDimitry Andric     Vals.clear();
47570b57cec5SDimitry Andric   }
47580b57cec5SDimitry Andric 
47590b57cec5SDimitry Andric   // Emit the function proto information.
47600b57cec5SDimitry Andric   for (const Function &F : M) {
47610b57cec5SDimitry Andric     // FUNCTION:  [strtab offset, strtab size, 0, 0, 0, linkage]
47620b57cec5SDimitry Andric     Vals.push_back(StrtabBuilder.add(F.getName()));
47630b57cec5SDimitry Andric     Vals.push_back(F.getName().size());
47640b57cec5SDimitry Andric     Vals.push_back(0);
47650b57cec5SDimitry Andric     Vals.push_back(0);
47660b57cec5SDimitry Andric     Vals.push_back(0);
47670b57cec5SDimitry Andric     Vals.push_back(getEncodedLinkage(F));
47680b57cec5SDimitry Andric 
47690b57cec5SDimitry Andric     Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals);
47700b57cec5SDimitry Andric     Vals.clear();
47710b57cec5SDimitry Andric   }
47720b57cec5SDimitry Andric 
47730b57cec5SDimitry Andric   // Emit the alias information.
47740b57cec5SDimitry Andric   for (const GlobalAlias &A : M.aliases()) {
47750b57cec5SDimitry Andric     // ALIAS: [strtab offset, strtab size, 0, 0, 0, linkage]
47760b57cec5SDimitry Andric     Vals.push_back(StrtabBuilder.add(A.getName()));
47770b57cec5SDimitry Andric     Vals.push_back(A.getName().size());
47780b57cec5SDimitry Andric     Vals.push_back(0);
47790b57cec5SDimitry Andric     Vals.push_back(0);
47800b57cec5SDimitry Andric     Vals.push_back(0);
47810b57cec5SDimitry Andric     Vals.push_back(getEncodedLinkage(A));
47820b57cec5SDimitry Andric 
47830b57cec5SDimitry Andric     Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals);
47840b57cec5SDimitry Andric     Vals.clear();
47850b57cec5SDimitry Andric   }
47860b57cec5SDimitry Andric 
47870b57cec5SDimitry Andric   // Emit the ifunc information.
47880b57cec5SDimitry Andric   for (const GlobalIFunc &I : M.ifuncs()) {
47890b57cec5SDimitry Andric     // IFUNC: [strtab offset, strtab size, 0, 0, 0, linkage]
47900b57cec5SDimitry Andric     Vals.push_back(StrtabBuilder.add(I.getName()));
47910b57cec5SDimitry Andric     Vals.push_back(I.getName().size());
47920b57cec5SDimitry Andric     Vals.push_back(0);
47930b57cec5SDimitry Andric     Vals.push_back(0);
47940b57cec5SDimitry Andric     Vals.push_back(0);
47950b57cec5SDimitry Andric     Vals.push_back(getEncodedLinkage(I));
47960b57cec5SDimitry Andric 
47970b57cec5SDimitry Andric     Stream.EmitRecord(bitc::MODULE_CODE_IFUNC, Vals);
47980b57cec5SDimitry Andric     Vals.clear();
47990b57cec5SDimitry Andric   }
48000b57cec5SDimitry Andric }
48010b57cec5SDimitry Andric 
write()48020b57cec5SDimitry Andric void ThinLinkBitcodeWriter::write() {
48030b57cec5SDimitry Andric   Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
48040b57cec5SDimitry Andric 
48050b57cec5SDimitry Andric   writeModuleVersion();
48060b57cec5SDimitry Andric 
48070b57cec5SDimitry Andric   writeSimplifiedModuleInfo();
48080b57cec5SDimitry Andric 
48090b57cec5SDimitry Andric   writePerModuleGlobalValueSummary();
48100b57cec5SDimitry Andric 
48110b57cec5SDimitry Andric   // Write module hash.
48120b57cec5SDimitry Andric   Stream.EmitRecord(bitc::MODULE_CODE_HASH, ArrayRef<uint32_t>(*ModHash));
48130b57cec5SDimitry Andric 
48140b57cec5SDimitry Andric   Stream.ExitBlock();
48150b57cec5SDimitry Andric }
48160b57cec5SDimitry Andric 
writeThinLinkBitcode(const Module & M,const ModuleSummaryIndex & Index,const ModuleHash & ModHash)48170b57cec5SDimitry Andric void BitcodeWriter::writeThinLinkBitcode(const Module &M,
48180b57cec5SDimitry Andric                                          const ModuleSummaryIndex &Index,
48190b57cec5SDimitry Andric                                          const ModuleHash &ModHash) {
48200b57cec5SDimitry Andric   assert(!WroteStrtab);
48210b57cec5SDimitry Andric 
48220b57cec5SDimitry Andric   // The Mods vector is used by irsymtab::build, which requires non-const
48230b57cec5SDimitry Andric   // Modules in case it needs to materialize metadata. But the bitcode writer
48240b57cec5SDimitry Andric   // requires that the module is materialized, so we can cast to non-const here,
48250b57cec5SDimitry Andric   // after checking that it is in fact materialized.
48260b57cec5SDimitry Andric   assert(M.isMaterialized());
48270b57cec5SDimitry Andric   Mods.push_back(const_cast<Module *>(&M));
48280b57cec5SDimitry Andric 
48290b57cec5SDimitry Andric   ThinLinkBitcodeWriter ThinLinkWriter(M, StrtabBuilder, *Stream, Index,
48300b57cec5SDimitry Andric                                        ModHash);
48310b57cec5SDimitry Andric   ThinLinkWriter.write();
48320b57cec5SDimitry Andric }
48330b57cec5SDimitry Andric 
48340b57cec5SDimitry Andric // Write the specified thin link bitcode file to the given raw output stream,
48350b57cec5SDimitry Andric // where it will be written in a new bitcode block. This is used when
48360b57cec5SDimitry Andric // writing the per-module index file for ThinLTO.
WriteThinLinkBitcodeToFile(const Module & M,raw_ostream & Out,const ModuleSummaryIndex & Index,const ModuleHash & ModHash)48370b57cec5SDimitry Andric void llvm::WriteThinLinkBitcodeToFile(const Module &M, raw_ostream &Out,
48380b57cec5SDimitry Andric                                       const ModuleSummaryIndex &Index,
48390b57cec5SDimitry Andric                                       const ModuleHash &ModHash) {
48400b57cec5SDimitry Andric   SmallVector<char, 0> Buffer;
48410b57cec5SDimitry Andric   Buffer.reserve(256 * 1024);
48420b57cec5SDimitry Andric 
48430b57cec5SDimitry Andric   BitcodeWriter Writer(Buffer);
48440b57cec5SDimitry Andric   Writer.writeThinLinkBitcode(M, Index, ModHash);
48450b57cec5SDimitry Andric   Writer.writeSymtab();
48460b57cec5SDimitry Andric   Writer.writeStrtab();
48470b57cec5SDimitry Andric 
48480b57cec5SDimitry Andric   Out.write((char *)&Buffer.front(), Buffer.size());
48490b57cec5SDimitry Andric }
4850480093f4SDimitry Andric 
getSectionNameForBitcode(const Triple & T)4851480093f4SDimitry Andric static const char *getSectionNameForBitcode(const Triple &T) {
4852480093f4SDimitry Andric   switch (T.getObjectFormat()) {
4853480093f4SDimitry Andric   case Triple::MachO:
4854480093f4SDimitry Andric     return "__LLVM,__bitcode";
4855480093f4SDimitry Andric   case Triple::COFF:
4856480093f4SDimitry Andric   case Triple::ELF:
4857480093f4SDimitry Andric   case Triple::Wasm:
4858480093f4SDimitry Andric   case Triple::UnknownObjectFormat:
4859480093f4SDimitry Andric     return ".llvmbc";
4860af732203SDimitry Andric   case Triple::GOFF:
4861af732203SDimitry Andric     llvm_unreachable("GOFF is not yet implemented");
4862af732203SDimitry Andric     break;
4863480093f4SDimitry Andric   case Triple::XCOFF:
4864480093f4SDimitry Andric     llvm_unreachable("XCOFF is not yet implemented");
4865480093f4SDimitry Andric     break;
4866480093f4SDimitry Andric   }
4867480093f4SDimitry Andric   llvm_unreachable("Unimplemented ObjectFormatType");
4868480093f4SDimitry Andric }
4869480093f4SDimitry Andric 
getSectionNameForCommandline(const Triple & T)4870480093f4SDimitry Andric static const char *getSectionNameForCommandline(const Triple &T) {
4871480093f4SDimitry Andric   switch (T.getObjectFormat()) {
4872480093f4SDimitry Andric   case Triple::MachO:
4873480093f4SDimitry Andric     return "__LLVM,__cmdline";
4874480093f4SDimitry Andric   case Triple::COFF:
4875480093f4SDimitry Andric   case Triple::ELF:
4876480093f4SDimitry Andric   case Triple::Wasm:
4877480093f4SDimitry Andric   case Triple::UnknownObjectFormat:
4878480093f4SDimitry Andric     return ".llvmcmd";
4879af732203SDimitry Andric   case Triple::GOFF:
4880af732203SDimitry Andric     llvm_unreachable("GOFF is not yet implemented");
4881af732203SDimitry Andric     break;
4882480093f4SDimitry Andric   case Triple::XCOFF:
4883480093f4SDimitry Andric     llvm_unreachable("XCOFF is not yet implemented");
4884480093f4SDimitry Andric     break;
4885480093f4SDimitry Andric   }
4886480093f4SDimitry Andric   llvm_unreachable("Unimplemented ObjectFormatType");
4887480093f4SDimitry Andric }
4888480093f4SDimitry Andric 
EmbedBitcodeInModule(llvm::Module & M,llvm::MemoryBufferRef Buf,bool EmbedBitcode,bool EmbedCmdline,const std::vector<uint8_t> & CmdArgs)4889480093f4SDimitry Andric void llvm::EmbedBitcodeInModule(llvm::Module &M, llvm::MemoryBufferRef Buf,
4890af732203SDimitry Andric                                 bool EmbedBitcode, bool EmbedCmdline,
4891af732203SDimitry Andric                                 const std::vector<uint8_t> &CmdArgs) {
4892480093f4SDimitry Andric   // Save llvm.compiler.used and remove it.
4893480093f4SDimitry Andric   SmallVector<Constant *, 2> UsedArray;
4894*5f7ddb14SDimitry Andric   SmallVector<GlobalValue *, 4> UsedGlobals;
4895480093f4SDimitry Andric   Type *UsedElementType = Type::getInt8Ty(M.getContext())->getPointerTo(0);
4896480093f4SDimitry Andric   GlobalVariable *Used = collectUsedGlobalVariables(M, UsedGlobals, true);
4897480093f4SDimitry Andric   for (auto *GV : UsedGlobals) {
4898480093f4SDimitry Andric     if (GV->getName() != "llvm.embedded.module" &&
4899480093f4SDimitry Andric         GV->getName() != "llvm.cmdline")
4900480093f4SDimitry Andric       UsedArray.push_back(
4901480093f4SDimitry Andric           ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
4902480093f4SDimitry Andric   }
4903480093f4SDimitry Andric   if (Used)
4904480093f4SDimitry Andric     Used->eraseFromParent();
4905480093f4SDimitry Andric 
4906480093f4SDimitry Andric   // Embed the bitcode for the llvm module.
4907480093f4SDimitry Andric   std::string Data;
4908480093f4SDimitry Andric   ArrayRef<uint8_t> ModuleData;
4909480093f4SDimitry Andric   Triple T(M.getTargetTriple());
4910af732203SDimitry Andric 
4911480093f4SDimitry Andric   if (EmbedBitcode) {
4912af732203SDimitry Andric     if (Buf.getBufferSize() == 0 ||
4913af732203SDimitry Andric         !isBitcode((const unsigned char *)Buf.getBufferStart(),
4914480093f4SDimitry Andric                    (const unsigned char *)Buf.getBufferEnd())) {
4915480093f4SDimitry Andric       // If the input is LLVM Assembly, bitcode is produced by serializing
4916480093f4SDimitry Andric       // the module. Use-lists order need to be preserved in this case.
4917480093f4SDimitry Andric       llvm::raw_string_ostream OS(Data);
4918480093f4SDimitry Andric       llvm::WriteBitcodeToFile(M, OS, /* ShouldPreserveUseListOrder */ true);
4919480093f4SDimitry Andric       ModuleData =
4920480093f4SDimitry Andric           ArrayRef<uint8_t>((const uint8_t *)OS.str().data(), OS.str().size());
4921480093f4SDimitry Andric     } else
4922480093f4SDimitry Andric       // If the input is LLVM bitcode, write the input byte stream directly.
4923480093f4SDimitry Andric       ModuleData = ArrayRef<uint8_t>((const uint8_t *)Buf.getBufferStart(),
4924480093f4SDimitry Andric                                      Buf.getBufferSize());
4925480093f4SDimitry Andric   }
4926480093f4SDimitry Andric   llvm::Constant *ModuleConstant =
4927480093f4SDimitry Andric       llvm::ConstantDataArray::get(M.getContext(), ModuleData);
4928480093f4SDimitry Andric   llvm::GlobalVariable *GV = new llvm::GlobalVariable(
4929480093f4SDimitry Andric       M, ModuleConstant->getType(), true, llvm::GlobalValue::PrivateLinkage,
4930480093f4SDimitry Andric       ModuleConstant);
4931480093f4SDimitry Andric   GV->setSection(getSectionNameForBitcode(T));
4932af732203SDimitry Andric   // Set alignment to 1 to prevent padding between two contributions from input
4933af732203SDimitry Andric   // sections after linking.
4934af732203SDimitry Andric   GV->setAlignment(Align(1));
4935480093f4SDimitry Andric   UsedArray.push_back(
4936480093f4SDimitry Andric       ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
4937480093f4SDimitry Andric   if (llvm::GlobalVariable *Old =
4938480093f4SDimitry Andric           M.getGlobalVariable("llvm.embedded.module", true)) {
4939480093f4SDimitry Andric     assert(Old->hasOneUse() &&
4940480093f4SDimitry Andric            "llvm.embedded.module can only be used once in llvm.compiler.used");
4941480093f4SDimitry Andric     GV->takeName(Old);
4942480093f4SDimitry Andric     Old->eraseFromParent();
4943480093f4SDimitry Andric   } else {
4944480093f4SDimitry Andric     GV->setName("llvm.embedded.module");
4945480093f4SDimitry Andric   }
4946480093f4SDimitry Andric 
4947480093f4SDimitry Andric   // Skip if only bitcode needs to be embedded.
4948af732203SDimitry Andric   if (EmbedCmdline) {
4949480093f4SDimitry Andric     // Embed command-line options.
4950af732203SDimitry Andric     ArrayRef<uint8_t> CmdData(const_cast<uint8_t *>(CmdArgs.data()),
4951af732203SDimitry Andric                               CmdArgs.size());
4952480093f4SDimitry Andric     llvm::Constant *CmdConstant =
4953480093f4SDimitry Andric         llvm::ConstantDataArray::get(M.getContext(), CmdData);
4954480093f4SDimitry Andric     GV = new llvm::GlobalVariable(M, CmdConstant->getType(), true,
4955480093f4SDimitry Andric                                   llvm::GlobalValue::PrivateLinkage,
4956480093f4SDimitry Andric                                   CmdConstant);
4957480093f4SDimitry Andric     GV->setSection(getSectionNameForCommandline(T));
4958af732203SDimitry Andric     GV->setAlignment(Align(1));
4959480093f4SDimitry Andric     UsedArray.push_back(
4960480093f4SDimitry Andric         ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
4961480093f4SDimitry Andric     if (llvm::GlobalVariable *Old = M.getGlobalVariable("llvm.cmdline", true)) {
4962480093f4SDimitry Andric       assert(Old->hasOneUse() &&
4963480093f4SDimitry Andric              "llvm.cmdline can only be used once in llvm.compiler.used");
4964480093f4SDimitry Andric       GV->takeName(Old);
4965480093f4SDimitry Andric       Old->eraseFromParent();
4966480093f4SDimitry Andric     } else {
4967480093f4SDimitry Andric       GV->setName("llvm.cmdline");
4968480093f4SDimitry Andric     }
4969480093f4SDimitry Andric   }
4970480093f4SDimitry Andric 
4971480093f4SDimitry Andric   if (UsedArray.empty())
4972480093f4SDimitry Andric     return;
4973480093f4SDimitry Andric 
4974480093f4SDimitry Andric   // Recreate llvm.compiler.used.
4975480093f4SDimitry Andric   ArrayType *ATy = ArrayType::get(UsedElementType, UsedArray.size());
4976480093f4SDimitry Andric   auto *NewUsed = new GlobalVariable(
4977480093f4SDimitry Andric       M, ATy, false, llvm::GlobalValue::AppendingLinkage,
4978480093f4SDimitry Andric       llvm::ConstantArray::get(ATy, UsedArray), "llvm.compiler.used");
4979480093f4SDimitry Andric   NewUsed->setSection("llvm.metadata");
4980480093f4SDimitry Andric }
4981