10b57cec5SDimitry Andric //===- BitcodeReader.cpp - Internal BitcodeReader implementation ----------===// 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 #include "llvm/Bitcode/BitcodeReader.h" 100b57cec5SDimitry Andric #include "MetadataLoader.h" 110b57cec5SDimitry Andric #include "ValueList.h" 120b57cec5SDimitry Andric #include "llvm/ADT/APFloat.h" 130b57cec5SDimitry Andric #include "llvm/ADT/APInt.h" 140b57cec5SDimitry Andric #include "llvm/ADT/ArrayRef.h" 150b57cec5SDimitry Andric #include "llvm/ADT/DenseMap.h" 160b57cec5SDimitry Andric #include "llvm/ADT/STLExtras.h" 170b57cec5SDimitry Andric #include "llvm/ADT/SmallString.h" 180b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h" 190b57cec5SDimitry Andric #include "llvm/ADT/StringRef.h" 200b57cec5SDimitry Andric #include "llvm/ADT/Twine.h" 21e8d8bef9SDimitry Andric #include "llvm/Bitcode/BitcodeCommon.h" 220b57cec5SDimitry Andric #include "llvm/Bitcode/LLVMBitCodes.h" 23e8d8bef9SDimitry Andric #include "llvm/Bitstream/BitstreamReader.h" 240b57cec5SDimitry Andric #include "llvm/Config/llvm-config.h" 250b57cec5SDimitry Andric #include "llvm/IR/Argument.h" 26*fe013be4SDimitry Andric #include "llvm/IR/AttributeMask.h" 270b57cec5SDimitry Andric #include "llvm/IR/Attributes.h" 280b57cec5SDimitry Andric #include "llvm/IR/AutoUpgrade.h" 290b57cec5SDimitry Andric #include "llvm/IR/BasicBlock.h" 300b57cec5SDimitry Andric #include "llvm/IR/CallingConv.h" 310b57cec5SDimitry Andric #include "llvm/IR/Comdat.h" 320b57cec5SDimitry Andric #include "llvm/IR/Constant.h" 330b57cec5SDimitry Andric #include "llvm/IR/Constants.h" 340b57cec5SDimitry Andric #include "llvm/IR/DataLayout.h" 350b57cec5SDimitry Andric #include "llvm/IR/DebugInfo.h" 360b57cec5SDimitry Andric #include "llvm/IR/DebugInfoMetadata.h" 370b57cec5SDimitry Andric #include "llvm/IR/DebugLoc.h" 380b57cec5SDimitry Andric #include "llvm/IR/DerivedTypes.h" 390b57cec5SDimitry Andric #include "llvm/IR/Function.h" 400b57cec5SDimitry Andric #include "llvm/IR/GVMaterializer.h" 4181ad6265SDimitry Andric #include "llvm/IR/GetElementPtrTypeIterator.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/InstIterator.h" 490b57cec5SDimitry Andric #include "llvm/IR/InstrTypes.h" 500b57cec5SDimitry Andric #include "llvm/IR/Instruction.h" 510b57cec5SDimitry Andric #include "llvm/IR/Instructions.h" 520b57cec5SDimitry Andric #include "llvm/IR/Intrinsics.h" 5381ad6265SDimitry Andric #include "llvm/IR/IntrinsicsAArch64.h" 5481ad6265SDimitry Andric #include "llvm/IR/IntrinsicsARM.h" 550b57cec5SDimitry Andric #include "llvm/IR/LLVMContext.h" 560b57cec5SDimitry Andric #include "llvm/IR/Metadata.h" 570b57cec5SDimitry Andric #include "llvm/IR/Module.h" 580b57cec5SDimitry Andric #include "llvm/IR/ModuleSummaryIndex.h" 590b57cec5SDimitry Andric #include "llvm/IR/Operator.h" 600b57cec5SDimitry Andric #include "llvm/IR/Type.h" 610b57cec5SDimitry Andric #include "llvm/IR/Value.h" 620b57cec5SDimitry Andric #include "llvm/IR/Verifier.h" 630b57cec5SDimitry Andric #include "llvm/Support/AtomicOrdering.h" 640b57cec5SDimitry Andric #include "llvm/Support/Casting.h" 650b57cec5SDimitry Andric #include "llvm/Support/CommandLine.h" 660b57cec5SDimitry Andric #include "llvm/Support/Compiler.h" 670b57cec5SDimitry Andric #include "llvm/Support/Debug.h" 680b57cec5SDimitry Andric #include "llvm/Support/Error.h" 690b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h" 700b57cec5SDimitry Andric #include "llvm/Support/ErrorOr.h" 710b57cec5SDimitry Andric #include "llvm/Support/MathExtras.h" 720b57cec5SDimitry Andric #include "llvm/Support/MemoryBuffer.h" 73bdd1243dSDimitry Andric #include "llvm/Support/ModRef.h" 740b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h" 75*fe013be4SDimitry Andric #include "llvm/TargetParser/Triple.h" 760b57cec5SDimitry Andric #include <algorithm> 770b57cec5SDimitry Andric #include <cassert> 780b57cec5SDimitry Andric #include <cstddef> 790b57cec5SDimitry Andric #include <cstdint> 800b57cec5SDimitry Andric #include <deque> 810b57cec5SDimitry Andric #include <map> 820b57cec5SDimitry Andric #include <memory> 83bdd1243dSDimitry Andric #include <optional> 840b57cec5SDimitry Andric #include <set> 850b57cec5SDimitry Andric #include <string> 860b57cec5SDimitry Andric #include <system_error> 870b57cec5SDimitry Andric #include <tuple> 880b57cec5SDimitry Andric #include <utility> 890b57cec5SDimitry Andric #include <vector> 900b57cec5SDimitry Andric 910b57cec5SDimitry Andric using namespace llvm; 920b57cec5SDimitry Andric 930b57cec5SDimitry Andric static cl::opt<bool> PrintSummaryGUIDs( 940b57cec5SDimitry Andric "print-summary-global-ids", cl::init(false), cl::Hidden, 950b57cec5SDimitry Andric cl::desc( 960b57cec5SDimitry Andric "Print the global id for each value when reading the module summary")); 970b57cec5SDimitry Andric 9881ad6265SDimitry Andric static cl::opt<bool> ExpandConstantExprs( 9981ad6265SDimitry Andric "expand-constant-exprs", cl::Hidden, 10081ad6265SDimitry Andric cl::desc( 10181ad6265SDimitry Andric "Expand constant expressions to instructions for testing purposes")); 10281ad6265SDimitry Andric 1030b57cec5SDimitry Andric namespace { 1040b57cec5SDimitry Andric 1050b57cec5SDimitry Andric enum { 1060b57cec5SDimitry Andric SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex 1070b57cec5SDimitry Andric }; 1080b57cec5SDimitry Andric 1090b57cec5SDimitry Andric } // end anonymous namespace 1100b57cec5SDimitry Andric 1110b57cec5SDimitry Andric static Error error(const Twine &Message) { 1120b57cec5SDimitry Andric return make_error<StringError>( 1130b57cec5SDimitry Andric Message, make_error_code(BitcodeError::CorruptedBitcode)); 1140b57cec5SDimitry Andric } 1150b57cec5SDimitry Andric 1160b57cec5SDimitry Andric static Error hasInvalidBitcodeHeader(BitstreamCursor &Stream) { 1170b57cec5SDimitry Andric if (!Stream.canSkipToPos(4)) 1180b57cec5SDimitry Andric return createStringError(std::errc::illegal_byte_sequence, 1190b57cec5SDimitry Andric "file too small to contain bitcode header"); 1200b57cec5SDimitry Andric for (unsigned C : {'B', 'C'}) 1210b57cec5SDimitry Andric if (Expected<SimpleBitstreamCursor::word_t> Res = Stream.Read(8)) { 1220b57cec5SDimitry Andric if (Res.get() != C) 1230b57cec5SDimitry Andric return createStringError(std::errc::illegal_byte_sequence, 1240b57cec5SDimitry Andric "file doesn't start with bitcode header"); 1250b57cec5SDimitry Andric } else 1260b57cec5SDimitry Andric return Res.takeError(); 1270b57cec5SDimitry Andric for (unsigned C : {0x0, 0xC, 0xE, 0xD}) 1280b57cec5SDimitry Andric if (Expected<SimpleBitstreamCursor::word_t> Res = Stream.Read(4)) { 1290b57cec5SDimitry Andric if (Res.get() != C) 1300b57cec5SDimitry Andric return createStringError(std::errc::illegal_byte_sequence, 1310b57cec5SDimitry Andric "file doesn't start with bitcode header"); 1320b57cec5SDimitry Andric } else 1330b57cec5SDimitry Andric return Res.takeError(); 1340b57cec5SDimitry Andric return Error::success(); 1350b57cec5SDimitry Andric } 1360b57cec5SDimitry Andric 1370b57cec5SDimitry Andric static Expected<BitstreamCursor> initStream(MemoryBufferRef Buffer) { 1380b57cec5SDimitry Andric const unsigned char *BufPtr = (const unsigned char *)Buffer.getBufferStart(); 1390b57cec5SDimitry Andric const unsigned char *BufEnd = BufPtr + Buffer.getBufferSize(); 1400b57cec5SDimitry Andric 1410b57cec5SDimitry Andric if (Buffer.getBufferSize() & 3) 1420b57cec5SDimitry Andric return error("Invalid bitcode signature"); 1430b57cec5SDimitry Andric 1440b57cec5SDimitry Andric // If we have a wrapper header, parse it and ignore the non-bc file contents. 1450b57cec5SDimitry Andric // The magic number is 0x0B17C0DE stored in little endian. 1460b57cec5SDimitry Andric if (isBitcodeWrapper(BufPtr, BufEnd)) 1470b57cec5SDimitry Andric if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true)) 1480b57cec5SDimitry Andric return error("Invalid bitcode wrapper header"); 1490b57cec5SDimitry Andric 1500b57cec5SDimitry Andric BitstreamCursor Stream(ArrayRef<uint8_t>(BufPtr, BufEnd)); 1510b57cec5SDimitry Andric if (Error Err = hasInvalidBitcodeHeader(Stream)) 1520b57cec5SDimitry Andric return std::move(Err); 1530b57cec5SDimitry Andric 1540b57cec5SDimitry Andric return std::move(Stream); 1550b57cec5SDimitry Andric } 1560b57cec5SDimitry Andric 1570b57cec5SDimitry Andric /// Convert a string from a record into an std::string, return true on failure. 1580b57cec5SDimitry Andric template <typename StrTy> 1590b57cec5SDimitry Andric static bool convertToString(ArrayRef<uint64_t> Record, unsigned Idx, 1600b57cec5SDimitry Andric StrTy &Result) { 1610b57cec5SDimitry Andric if (Idx > Record.size()) 1620b57cec5SDimitry Andric return true; 1630b57cec5SDimitry Andric 1645ffd83dbSDimitry Andric Result.append(Record.begin() + Idx, Record.end()); 1650b57cec5SDimitry Andric return false; 1660b57cec5SDimitry Andric } 1670b57cec5SDimitry Andric 1680b57cec5SDimitry Andric // Strip all the TBAA attachment for the module. 1690b57cec5SDimitry Andric static void stripTBAA(Module *M) { 1700b57cec5SDimitry Andric for (auto &F : *M) { 1710b57cec5SDimitry Andric if (F.isMaterializable()) 1720b57cec5SDimitry Andric continue; 1730b57cec5SDimitry Andric for (auto &I : instructions(F)) 1740b57cec5SDimitry Andric I.setMetadata(LLVMContext::MD_tbaa, nullptr); 1750b57cec5SDimitry Andric } 1760b57cec5SDimitry Andric } 1770b57cec5SDimitry Andric 1780b57cec5SDimitry Andric /// Read the "IDENTIFICATION_BLOCK_ID" block, do some basic enforcement on the 1790b57cec5SDimitry Andric /// "epoch" encoded in the bitcode, and return the producer name if any. 1800b57cec5SDimitry Andric static Expected<std::string> readIdentificationBlock(BitstreamCursor &Stream) { 1810b57cec5SDimitry Andric if (Error Err = Stream.EnterSubBlock(bitc::IDENTIFICATION_BLOCK_ID)) 1820b57cec5SDimitry Andric return std::move(Err); 1830b57cec5SDimitry Andric 1840b57cec5SDimitry Andric // Read all the records. 1850b57cec5SDimitry Andric SmallVector<uint64_t, 64> Record; 1860b57cec5SDimitry Andric 1870b57cec5SDimitry Andric std::string ProducerIdentification; 1880b57cec5SDimitry Andric 1890b57cec5SDimitry Andric while (true) { 1900b57cec5SDimitry Andric BitstreamEntry Entry; 191349cc55cSDimitry Andric if (Error E = Stream.advance().moveInto(Entry)) 192349cc55cSDimitry Andric return std::move(E); 1930b57cec5SDimitry Andric 1940b57cec5SDimitry Andric switch (Entry.Kind) { 1950b57cec5SDimitry Andric default: 1960b57cec5SDimitry Andric case BitstreamEntry::Error: 1970b57cec5SDimitry Andric return error("Malformed block"); 1980b57cec5SDimitry Andric case BitstreamEntry::EndBlock: 1990b57cec5SDimitry Andric return ProducerIdentification; 2000b57cec5SDimitry Andric case BitstreamEntry::Record: 2010b57cec5SDimitry Andric // The interesting case. 2020b57cec5SDimitry Andric break; 2030b57cec5SDimitry Andric } 2040b57cec5SDimitry Andric 2050b57cec5SDimitry Andric // Read a record. 2060b57cec5SDimitry Andric Record.clear(); 2070b57cec5SDimitry Andric Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record); 2080b57cec5SDimitry Andric if (!MaybeBitCode) 2090b57cec5SDimitry Andric return MaybeBitCode.takeError(); 2100b57cec5SDimitry Andric switch (MaybeBitCode.get()) { 2110b57cec5SDimitry Andric default: // Default behavior: reject 2120b57cec5SDimitry Andric return error("Invalid value"); 2130b57cec5SDimitry Andric case bitc::IDENTIFICATION_CODE_STRING: // IDENTIFICATION: [strchr x N] 2140b57cec5SDimitry Andric convertToString(Record, 0, ProducerIdentification); 2150b57cec5SDimitry Andric break; 2160b57cec5SDimitry Andric case bitc::IDENTIFICATION_CODE_EPOCH: { // EPOCH: [epoch#] 2170b57cec5SDimitry Andric unsigned epoch = (unsigned)Record[0]; 2180b57cec5SDimitry Andric if (epoch != bitc::BITCODE_CURRENT_EPOCH) { 2190b57cec5SDimitry Andric return error( 2200b57cec5SDimitry Andric Twine("Incompatible epoch: Bitcode '") + Twine(epoch) + 2210b57cec5SDimitry Andric "' vs current: '" + Twine(bitc::BITCODE_CURRENT_EPOCH) + "'"); 2220b57cec5SDimitry Andric } 2230b57cec5SDimitry Andric } 2240b57cec5SDimitry Andric } 2250b57cec5SDimitry Andric } 2260b57cec5SDimitry Andric } 2270b57cec5SDimitry Andric 2280b57cec5SDimitry Andric static Expected<std::string> readIdentificationCode(BitstreamCursor &Stream) { 2290b57cec5SDimitry Andric // We expect a number of well-defined blocks, though we don't necessarily 2300b57cec5SDimitry Andric // need to understand them all. 2310b57cec5SDimitry Andric while (true) { 2320b57cec5SDimitry Andric if (Stream.AtEndOfStream()) 2330b57cec5SDimitry Andric return ""; 2340b57cec5SDimitry Andric 2350b57cec5SDimitry Andric BitstreamEntry Entry; 236349cc55cSDimitry Andric if (Error E = Stream.advance().moveInto(Entry)) 237349cc55cSDimitry Andric return std::move(E); 2380b57cec5SDimitry Andric 2390b57cec5SDimitry Andric switch (Entry.Kind) { 2400b57cec5SDimitry Andric case BitstreamEntry::EndBlock: 2410b57cec5SDimitry Andric case BitstreamEntry::Error: 2420b57cec5SDimitry Andric return error("Malformed block"); 2430b57cec5SDimitry Andric 2440b57cec5SDimitry Andric case BitstreamEntry::SubBlock: 2450b57cec5SDimitry Andric if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) 2460b57cec5SDimitry Andric return readIdentificationBlock(Stream); 2470b57cec5SDimitry Andric 2480b57cec5SDimitry Andric // Ignore other sub-blocks. 2490b57cec5SDimitry Andric if (Error Err = Stream.SkipBlock()) 2500b57cec5SDimitry Andric return std::move(Err); 2510b57cec5SDimitry Andric continue; 2520b57cec5SDimitry Andric case BitstreamEntry::Record: 253349cc55cSDimitry Andric if (Error E = Stream.skipRecord(Entry.ID).takeError()) 254349cc55cSDimitry Andric return std::move(E); 2550b57cec5SDimitry Andric continue; 2560b57cec5SDimitry Andric } 2570b57cec5SDimitry Andric } 2580b57cec5SDimitry Andric } 2590b57cec5SDimitry Andric 2600b57cec5SDimitry Andric static Expected<bool> hasObjCCategoryInModule(BitstreamCursor &Stream) { 2610b57cec5SDimitry Andric if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID)) 2620b57cec5SDimitry Andric return std::move(Err); 2630b57cec5SDimitry Andric 2640b57cec5SDimitry Andric SmallVector<uint64_t, 64> Record; 2650b57cec5SDimitry Andric // Read all the records for this module. 2660b57cec5SDimitry Andric 2670b57cec5SDimitry Andric while (true) { 2680b57cec5SDimitry Andric Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); 2690b57cec5SDimitry Andric if (!MaybeEntry) 2700b57cec5SDimitry Andric return MaybeEntry.takeError(); 2710b57cec5SDimitry Andric BitstreamEntry Entry = MaybeEntry.get(); 2720b57cec5SDimitry Andric 2730b57cec5SDimitry Andric switch (Entry.Kind) { 2740b57cec5SDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already. 2750b57cec5SDimitry Andric case BitstreamEntry::Error: 2760b57cec5SDimitry Andric return error("Malformed block"); 2770b57cec5SDimitry Andric case BitstreamEntry::EndBlock: 2780b57cec5SDimitry Andric return false; 2790b57cec5SDimitry Andric case BitstreamEntry::Record: 2800b57cec5SDimitry Andric // The interesting case. 2810b57cec5SDimitry Andric break; 2820b57cec5SDimitry Andric } 2830b57cec5SDimitry Andric 2840b57cec5SDimitry Andric // Read a record. 2850b57cec5SDimitry Andric Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record); 2860b57cec5SDimitry Andric if (!MaybeRecord) 2870b57cec5SDimitry Andric return MaybeRecord.takeError(); 2880b57cec5SDimitry Andric switch (MaybeRecord.get()) { 2890b57cec5SDimitry Andric default: 2900b57cec5SDimitry Andric break; // Default behavior, ignore unknown content. 2910b57cec5SDimitry Andric case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N] 2920b57cec5SDimitry Andric std::string S; 2930b57cec5SDimitry Andric if (convertToString(Record, 0, S)) 29481ad6265SDimitry Andric return error("Invalid section name record"); 2950b57cec5SDimitry Andric // Check for the i386 and other (x86_64, ARM) conventions 2960b57cec5SDimitry Andric if (S.find("__DATA,__objc_catlist") != std::string::npos || 2970b57cec5SDimitry Andric S.find("__OBJC,__category") != std::string::npos) 2980b57cec5SDimitry Andric return true; 2990b57cec5SDimitry Andric break; 3000b57cec5SDimitry Andric } 3010b57cec5SDimitry Andric } 3020b57cec5SDimitry Andric Record.clear(); 3030b57cec5SDimitry Andric } 3040b57cec5SDimitry Andric llvm_unreachable("Exit infinite loop"); 3050b57cec5SDimitry Andric } 3060b57cec5SDimitry Andric 3070b57cec5SDimitry Andric static Expected<bool> hasObjCCategory(BitstreamCursor &Stream) { 3080b57cec5SDimitry Andric // We expect a number of well-defined blocks, though we don't necessarily 3090b57cec5SDimitry Andric // need to understand them all. 3100b57cec5SDimitry Andric while (true) { 3110b57cec5SDimitry Andric BitstreamEntry Entry; 312349cc55cSDimitry Andric if (Error E = Stream.advance().moveInto(Entry)) 313349cc55cSDimitry Andric return std::move(E); 3140b57cec5SDimitry Andric 3150b57cec5SDimitry Andric switch (Entry.Kind) { 3160b57cec5SDimitry Andric case BitstreamEntry::Error: 3170b57cec5SDimitry Andric return error("Malformed block"); 3180b57cec5SDimitry Andric case BitstreamEntry::EndBlock: 3190b57cec5SDimitry Andric return false; 3200b57cec5SDimitry Andric 3210b57cec5SDimitry Andric case BitstreamEntry::SubBlock: 3220b57cec5SDimitry Andric if (Entry.ID == bitc::MODULE_BLOCK_ID) 3230b57cec5SDimitry Andric return hasObjCCategoryInModule(Stream); 3240b57cec5SDimitry Andric 3250b57cec5SDimitry Andric // Ignore other sub-blocks. 3260b57cec5SDimitry Andric if (Error Err = Stream.SkipBlock()) 3270b57cec5SDimitry Andric return std::move(Err); 3280b57cec5SDimitry Andric continue; 3290b57cec5SDimitry Andric 3300b57cec5SDimitry Andric case BitstreamEntry::Record: 331349cc55cSDimitry Andric if (Error E = Stream.skipRecord(Entry.ID).takeError()) 332349cc55cSDimitry Andric return std::move(E); 3330b57cec5SDimitry Andric continue; 3340b57cec5SDimitry Andric } 3350b57cec5SDimitry Andric } 3360b57cec5SDimitry Andric } 3370b57cec5SDimitry Andric 3380b57cec5SDimitry Andric static Expected<std::string> readModuleTriple(BitstreamCursor &Stream) { 3390b57cec5SDimitry Andric if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID)) 3400b57cec5SDimitry Andric return std::move(Err); 3410b57cec5SDimitry Andric 3420b57cec5SDimitry Andric SmallVector<uint64_t, 64> Record; 3430b57cec5SDimitry Andric 3440b57cec5SDimitry Andric std::string Triple; 3450b57cec5SDimitry Andric 3460b57cec5SDimitry Andric // Read all the records for this module. 3470b57cec5SDimitry Andric while (true) { 3480b57cec5SDimitry Andric Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); 3490b57cec5SDimitry Andric if (!MaybeEntry) 3500b57cec5SDimitry Andric return MaybeEntry.takeError(); 3510b57cec5SDimitry Andric BitstreamEntry Entry = MaybeEntry.get(); 3520b57cec5SDimitry Andric 3530b57cec5SDimitry Andric switch (Entry.Kind) { 3540b57cec5SDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already. 3550b57cec5SDimitry Andric case BitstreamEntry::Error: 3560b57cec5SDimitry Andric return error("Malformed block"); 3570b57cec5SDimitry Andric case BitstreamEntry::EndBlock: 3580b57cec5SDimitry Andric return Triple; 3590b57cec5SDimitry Andric case BitstreamEntry::Record: 3600b57cec5SDimitry Andric // The interesting case. 3610b57cec5SDimitry Andric break; 3620b57cec5SDimitry Andric } 3630b57cec5SDimitry Andric 3640b57cec5SDimitry Andric // Read a record. 3650b57cec5SDimitry Andric Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record); 3660b57cec5SDimitry Andric if (!MaybeRecord) 3670b57cec5SDimitry Andric return MaybeRecord.takeError(); 3680b57cec5SDimitry Andric switch (MaybeRecord.get()) { 3690b57cec5SDimitry Andric default: break; // Default behavior, ignore unknown content. 3700b57cec5SDimitry Andric case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N] 3710b57cec5SDimitry Andric std::string S; 3720b57cec5SDimitry Andric if (convertToString(Record, 0, S)) 37381ad6265SDimitry Andric return error("Invalid triple record"); 3740b57cec5SDimitry Andric Triple = S; 3750b57cec5SDimitry Andric break; 3760b57cec5SDimitry Andric } 3770b57cec5SDimitry Andric } 3780b57cec5SDimitry Andric Record.clear(); 3790b57cec5SDimitry Andric } 3800b57cec5SDimitry Andric llvm_unreachable("Exit infinite loop"); 3810b57cec5SDimitry Andric } 3820b57cec5SDimitry Andric 3830b57cec5SDimitry Andric static Expected<std::string> readTriple(BitstreamCursor &Stream) { 3840b57cec5SDimitry Andric // We expect a number of well-defined blocks, though we don't necessarily 3850b57cec5SDimitry Andric // need to understand them all. 3860b57cec5SDimitry Andric while (true) { 3870b57cec5SDimitry Andric Expected<BitstreamEntry> MaybeEntry = Stream.advance(); 3880b57cec5SDimitry Andric if (!MaybeEntry) 3890b57cec5SDimitry Andric return MaybeEntry.takeError(); 3900b57cec5SDimitry Andric BitstreamEntry Entry = MaybeEntry.get(); 3910b57cec5SDimitry Andric 3920b57cec5SDimitry Andric switch (Entry.Kind) { 3930b57cec5SDimitry Andric case BitstreamEntry::Error: 3940b57cec5SDimitry Andric return error("Malformed block"); 3950b57cec5SDimitry Andric case BitstreamEntry::EndBlock: 3960b57cec5SDimitry Andric return ""; 3970b57cec5SDimitry Andric 3980b57cec5SDimitry Andric case BitstreamEntry::SubBlock: 3990b57cec5SDimitry Andric if (Entry.ID == bitc::MODULE_BLOCK_ID) 4000b57cec5SDimitry Andric return readModuleTriple(Stream); 4010b57cec5SDimitry Andric 4020b57cec5SDimitry Andric // Ignore other sub-blocks. 4030b57cec5SDimitry Andric if (Error Err = Stream.SkipBlock()) 4040b57cec5SDimitry Andric return std::move(Err); 4050b57cec5SDimitry Andric continue; 4060b57cec5SDimitry Andric 4070b57cec5SDimitry Andric case BitstreamEntry::Record: 4080b57cec5SDimitry Andric if (llvm::Expected<unsigned> Skipped = Stream.skipRecord(Entry.ID)) 4090b57cec5SDimitry Andric continue; 4100b57cec5SDimitry Andric else 4110b57cec5SDimitry Andric return Skipped.takeError(); 4120b57cec5SDimitry Andric } 4130b57cec5SDimitry Andric } 4140b57cec5SDimitry Andric } 4150b57cec5SDimitry Andric 4160b57cec5SDimitry Andric namespace { 4170b57cec5SDimitry Andric 4180b57cec5SDimitry Andric class BitcodeReaderBase { 4190b57cec5SDimitry Andric protected: 4200b57cec5SDimitry Andric BitcodeReaderBase(BitstreamCursor Stream, StringRef Strtab) 4210b57cec5SDimitry Andric : Stream(std::move(Stream)), Strtab(Strtab) { 4220b57cec5SDimitry Andric this->Stream.setBlockInfo(&BlockInfo); 4230b57cec5SDimitry Andric } 4240b57cec5SDimitry Andric 4250b57cec5SDimitry Andric BitstreamBlockInfo BlockInfo; 4260b57cec5SDimitry Andric BitstreamCursor Stream; 4270b57cec5SDimitry Andric StringRef Strtab; 4280b57cec5SDimitry Andric 4290b57cec5SDimitry Andric /// In version 2 of the bitcode we store names of global values and comdats in 4300b57cec5SDimitry Andric /// a string table rather than in the VST. 4310b57cec5SDimitry Andric bool UseStrtab = false; 4320b57cec5SDimitry Andric 4330b57cec5SDimitry Andric Expected<unsigned> parseVersionRecord(ArrayRef<uint64_t> Record); 4340b57cec5SDimitry Andric 4350b57cec5SDimitry Andric /// If this module uses a string table, pop the reference to the string table 4360b57cec5SDimitry Andric /// and return the referenced string and the rest of the record. Otherwise 4370b57cec5SDimitry Andric /// just return the record itself. 4380b57cec5SDimitry Andric std::pair<StringRef, ArrayRef<uint64_t>> 4390b57cec5SDimitry Andric readNameFromStrtab(ArrayRef<uint64_t> Record); 4400b57cec5SDimitry Andric 44181ad6265SDimitry Andric Error readBlockInfo(); 4420b57cec5SDimitry Andric 4430b57cec5SDimitry Andric // Contains an arbitrary and optional string identifying the bitcode producer 4440b57cec5SDimitry Andric std::string ProducerIdentification; 4450b57cec5SDimitry Andric 4460b57cec5SDimitry Andric Error error(const Twine &Message); 4470b57cec5SDimitry Andric }; 4480b57cec5SDimitry Andric 4490b57cec5SDimitry Andric } // end anonymous namespace 4500b57cec5SDimitry Andric 4510b57cec5SDimitry Andric Error BitcodeReaderBase::error(const Twine &Message) { 4520b57cec5SDimitry Andric std::string FullMsg = Message.str(); 4530b57cec5SDimitry Andric if (!ProducerIdentification.empty()) 4540b57cec5SDimitry Andric FullMsg += " (Producer: '" + ProducerIdentification + "' Reader: 'LLVM " + 4550b57cec5SDimitry Andric LLVM_VERSION_STRING "')"; 4560b57cec5SDimitry Andric return ::error(FullMsg); 4570b57cec5SDimitry Andric } 4580b57cec5SDimitry Andric 4590b57cec5SDimitry Andric Expected<unsigned> 4600b57cec5SDimitry Andric BitcodeReaderBase::parseVersionRecord(ArrayRef<uint64_t> Record) { 4610b57cec5SDimitry Andric if (Record.empty()) 46281ad6265SDimitry Andric return error("Invalid version record"); 4630b57cec5SDimitry Andric unsigned ModuleVersion = Record[0]; 4640b57cec5SDimitry Andric if (ModuleVersion > 2) 4650b57cec5SDimitry Andric return error("Invalid value"); 4660b57cec5SDimitry Andric UseStrtab = ModuleVersion >= 2; 4670b57cec5SDimitry Andric return ModuleVersion; 4680b57cec5SDimitry Andric } 4690b57cec5SDimitry Andric 4700b57cec5SDimitry Andric std::pair<StringRef, ArrayRef<uint64_t>> 4710b57cec5SDimitry Andric BitcodeReaderBase::readNameFromStrtab(ArrayRef<uint64_t> Record) { 4720b57cec5SDimitry Andric if (!UseStrtab) 4730b57cec5SDimitry Andric return {"", Record}; 4740b57cec5SDimitry Andric // Invalid reference. Let the caller complain about the record being empty. 4750b57cec5SDimitry Andric if (Record[0] + Record[1] > Strtab.size()) 4760b57cec5SDimitry Andric return {"", {}}; 4770b57cec5SDimitry Andric return {StringRef(Strtab.data() + Record[0], Record[1]), Record.slice(2)}; 4780b57cec5SDimitry Andric } 4790b57cec5SDimitry Andric 4800b57cec5SDimitry Andric namespace { 4810b57cec5SDimitry Andric 48281ad6265SDimitry Andric /// This represents a constant expression or constant aggregate using a custom 48381ad6265SDimitry Andric /// structure internal to the bitcode reader. Later, this structure will be 48481ad6265SDimitry Andric /// expanded by materializeValue() either into a constant expression/aggregate, 48581ad6265SDimitry Andric /// or into an instruction sequence at the point of use. This allows us to 48681ad6265SDimitry Andric /// upgrade bitcode using constant expressions even if this kind of constant 48781ad6265SDimitry Andric /// expression is no longer supported. 48881ad6265SDimitry Andric class BitcodeConstant final : public Value, 48981ad6265SDimitry Andric TrailingObjects<BitcodeConstant, unsigned> { 49081ad6265SDimitry Andric friend TrailingObjects; 49181ad6265SDimitry Andric 49281ad6265SDimitry Andric // Value subclass ID: Pick largest possible value to avoid any clashes. 49381ad6265SDimitry Andric static constexpr uint8_t SubclassID = 255; 49481ad6265SDimitry Andric 49581ad6265SDimitry Andric public: 49681ad6265SDimitry Andric // Opcodes used for non-expressions. This includes constant aggregates 49781ad6265SDimitry Andric // (struct, array, vector) that might need expansion, as well as non-leaf 49881ad6265SDimitry Andric // constants that don't need expansion (no_cfi, dso_local, blockaddress), 49981ad6265SDimitry Andric // but still go through BitcodeConstant to avoid different uselist orders 50081ad6265SDimitry Andric // between the two cases. 50181ad6265SDimitry Andric static constexpr uint8_t ConstantStructOpcode = 255; 50281ad6265SDimitry Andric static constexpr uint8_t ConstantArrayOpcode = 254; 50381ad6265SDimitry Andric static constexpr uint8_t ConstantVectorOpcode = 253; 50481ad6265SDimitry Andric static constexpr uint8_t NoCFIOpcode = 252; 50581ad6265SDimitry Andric static constexpr uint8_t DSOLocalEquivalentOpcode = 251; 50681ad6265SDimitry Andric static constexpr uint8_t BlockAddressOpcode = 250; 50781ad6265SDimitry Andric static constexpr uint8_t FirstSpecialOpcode = BlockAddressOpcode; 50881ad6265SDimitry Andric 50981ad6265SDimitry Andric // Separate struct to make passing different number of parameters to 51081ad6265SDimitry Andric // BitcodeConstant::create() more convenient. 51181ad6265SDimitry Andric struct ExtraInfo { 51281ad6265SDimitry Andric uint8_t Opcode; 51381ad6265SDimitry Andric uint8_t Flags; 51481ad6265SDimitry Andric unsigned Extra; 51581ad6265SDimitry Andric Type *SrcElemTy; 51681ad6265SDimitry Andric 51781ad6265SDimitry Andric ExtraInfo(uint8_t Opcode, uint8_t Flags = 0, unsigned Extra = 0, 51881ad6265SDimitry Andric Type *SrcElemTy = nullptr) 51981ad6265SDimitry Andric : Opcode(Opcode), Flags(Flags), Extra(Extra), SrcElemTy(SrcElemTy) {} 52081ad6265SDimitry Andric }; 52181ad6265SDimitry Andric 52281ad6265SDimitry Andric uint8_t Opcode; 52381ad6265SDimitry Andric uint8_t Flags; 52481ad6265SDimitry Andric unsigned NumOperands; 52581ad6265SDimitry Andric unsigned Extra; // GEP inrange index or blockaddress BB id. 52681ad6265SDimitry Andric Type *SrcElemTy; // GEP source element type. 52781ad6265SDimitry Andric 52881ad6265SDimitry Andric private: 52981ad6265SDimitry Andric BitcodeConstant(Type *Ty, const ExtraInfo &Info, ArrayRef<unsigned> OpIDs) 53081ad6265SDimitry Andric : Value(Ty, SubclassID), Opcode(Info.Opcode), Flags(Info.Flags), 53181ad6265SDimitry Andric NumOperands(OpIDs.size()), Extra(Info.Extra), 53281ad6265SDimitry Andric SrcElemTy(Info.SrcElemTy) { 53381ad6265SDimitry Andric std::uninitialized_copy(OpIDs.begin(), OpIDs.end(), 53481ad6265SDimitry Andric getTrailingObjects<unsigned>()); 53581ad6265SDimitry Andric } 53681ad6265SDimitry Andric 53781ad6265SDimitry Andric BitcodeConstant &operator=(const BitcodeConstant &) = delete; 53881ad6265SDimitry Andric 53981ad6265SDimitry Andric public: 54081ad6265SDimitry Andric static BitcodeConstant *create(BumpPtrAllocator &A, Type *Ty, 54181ad6265SDimitry Andric const ExtraInfo &Info, 54281ad6265SDimitry Andric ArrayRef<unsigned> OpIDs) { 54381ad6265SDimitry Andric void *Mem = A.Allocate(totalSizeToAlloc<unsigned>(OpIDs.size()), 54481ad6265SDimitry Andric alignof(BitcodeConstant)); 54581ad6265SDimitry Andric return new (Mem) BitcodeConstant(Ty, Info, OpIDs); 54681ad6265SDimitry Andric } 54781ad6265SDimitry Andric 54881ad6265SDimitry Andric static bool classof(const Value *V) { return V->getValueID() == SubclassID; } 54981ad6265SDimitry Andric 55081ad6265SDimitry Andric ArrayRef<unsigned> getOperandIDs() const { 551bdd1243dSDimitry Andric return ArrayRef(getTrailingObjects<unsigned>(), NumOperands); 55281ad6265SDimitry Andric } 55381ad6265SDimitry Andric 554bdd1243dSDimitry Andric std::optional<unsigned> getInRangeIndex() const { 55581ad6265SDimitry Andric assert(Opcode == Instruction::GetElementPtr); 55681ad6265SDimitry Andric if (Extra == (unsigned)-1) 557bdd1243dSDimitry Andric return std::nullopt; 55881ad6265SDimitry Andric return Extra; 55981ad6265SDimitry Andric } 56081ad6265SDimitry Andric 56181ad6265SDimitry Andric const char *getOpcodeName() const { 56281ad6265SDimitry Andric return Instruction::getOpcodeName(Opcode); 56381ad6265SDimitry Andric } 56481ad6265SDimitry Andric }; 56581ad6265SDimitry Andric 5660b57cec5SDimitry Andric class BitcodeReader : public BitcodeReaderBase, public GVMaterializer { 5670b57cec5SDimitry Andric LLVMContext &Context; 5680b57cec5SDimitry Andric Module *TheModule = nullptr; 5690b57cec5SDimitry Andric // Next offset to start scanning for lazy parsing of function bodies. 5700b57cec5SDimitry Andric uint64_t NextUnreadBit = 0; 5710b57cec5SDimitry Andric // Last function offset found in the VST. 5720b57cec5SDimitry Andric uint64_t LastFunctionBlockBit = 0; 5730b57cec5SDimitry Andric bool SeenValueSymbolTable = false; 5740b57cec5SDimitry Andric uint64_t VSTOffset = 0; 5750b57cec5SDimitry Andric 5760b57cec5SDimitry Andric std::vector<std::string> SectionTable; 5770b57cec5SDimitry Andric std::vector<std::string> GCTable; 5780b57cec5SDimitry Andric 5790b57cec5SDimitry Andric std::vector<Type *> TypeList; 58081ad6265SDimitry Andric /// Track type IDs of contained types. Order is the same as the contained 58181ad6265SDimitry Andric /// types of a Type*. This is used during upgrades of typed pointer IR in 58281ad6265SDimitry Andric /// opaque pointer mode. 58381ad6265SDimitry Andric DenseMap<unsigned, SmallVector<unsigned, 1>> ContainedTypeIDs; 58481ad6265SDimitry Andric /// In some cases, we need to create a type ID for a type that was not 58581ad6265SDimitry Andric /// explicitly encoded in the bitcode, or we don't know about at the current 58681ad6265SDimitry Andric /// point. For example, a global may explicitly encode the value type ID, but 58781ad6265SDimitry Andric /// not have a type ID for the pointer to value type, for which we create a 58881ad6265SDimitry Andric /// virtual type ID instead. This map stores the new type ID that was created 58981ad6265SDimitry Andric /// for the given pair of Type and contained type ID. 59081ad6265SDimitry Andric DenseMap<std::pair<Type *, unsigned>, unsigned> VirtualTypeIDs; 59181ad6265SDimitry Andric DenseMap<Function *, unsigned> FunctionTypeIDs; 59281ad6265SDimitry Andric /// Allocator for BitcodeConstants. This should come before ValueList, 59381ad6265SDimitry Andric /// because the ValueList might hold ValueHandles to these constants, so 59481ad6265SDimitry Andric /// ValueList must be destroyed before Alloc. 59581ad6265SDimitry Andric BumpPtrAllocator Alloc; 5960b57cec5SDimitry Andric BitcodeReaderValueList ValueList; 597bdd1243dSDimitry Andric std::optional<MetadataLoader> MDLoader; 5980b57cec5SDimitry Andric std::vector<Comdat *> ComdatList; 5990eae32dcSDimitry Andric DenseSet<GlobalObject *> ImplicitComdatObjects; 6000b57cec5SDimitry Andric SmallVector<Instruction *, 64> InstructionList; 6010b57cec5SDimitry Andric 6020b57cec5SDimitry Andric std::vector<std::pair<GlobalVariable *, unsigned>> GlobalInits; 603349cc55cSDimitry Andric std::vector<std::pair<GlobalValue *, unsigned>> IndirectSymbolInits; 604349cc55cSDimitry Andric 605349cc55cSDimitry Andric struct FunctionOperandInfo { 606349cc55cSDimitry Andric Function *F; 607349cc55cSDimitry Andric unsigned PersonalityFn; 608349cc55cSDimitry Andric unsigned Prefix; 609349cc55cSDimitry Andric unsigned Prologue; 610349cc55cSDimitry Andric }; 611349cc55cSDimitry Andric std::vector<FunctionOperandInfo> FunctionOperands; 6120b57cec5SDimitry Andric 6130b57cec5SDimitry Andric /// The set of attributes by index. Index zero in the file is for null, and 6140b57cec5SDimitry Andric /// is thus not represented here. As such all indices are off by one. 6150b57cec5SDimitry Andric std::vector<AttributeList> MAttributes; 6160b57cec5SDimitry Andric 6170b57cec5SDimitry Andric /// The set of attribute groups. 6180b57cec5SDimitry Andric std::map<unsigned, AttributeList> MAttributeGroups; 6190b57cec5SDimitry Andric 6200b57cec5SDimitry Andric /// While parsing a function body, this is a list of the basic blocks for the 6210b57cec5SDimitry Andric /// function. 6220b57cec5SDimitry Andric std::vector<BasicBlock*> FunctionBBs; 6230b57cec5SDimitry Andric 6240b57cec5SDimitry Andric // When reading the module header, this list is populated with functions that 6250b57cec5SDimitry Andric // have bodies later in the file. 6260b57cec5SDimitry Andric std::vector<Function*> FunctionsWithBodies; 6270b57cec5SDimitry Andric 6280b57cec5SDimitry Andric // When intrinsic functions are encountered which require upgrading they are 6290b57cec5SDimitry Andric // stored here with their replacement function. 6300b57cec5SDimitry Andric using UpdatedIntrinsicMap = DenseMap<Function *, Function *>; 6310b57cec5SDimitry Andric UpdatedIntrinsicMap UpgradedIntrinsics; 6320b57cec5SDimitry Andric 6330b57cec5SDimitry Andric // Several operations happen after the module header has been read, but 6340b57cec5SDimitry Andric // before function bodies are processed. This keeps track of whether 6350b57cec5SDimitry Andric // we've done this yet. 6360b57cec5SDimitry Andric bool SeenFirstFunctionBody = false; 6370b57cec5SDimitry Andric 6380b57cec5SDimitry Andric /// When function bodies are initially scanned, this map contains info about 6390b57cec5SDimitry Andric /// where to find deferred function body in the stream. 6400b57cec5SDimitry Andric DenseMap<Function*, uint64_t> DeferredFunctionInfo; 6410b57cec5SDimitry Andric 6420b57cec5SDimitry Andric /// When Metadata block is initially scanned when parsing the module, we may 6430b57cec5SDimitry Andric /// choose to defer parsing of the metadata. This vector contains info about 6440b57cec5SDimitry Andric /// which Metadata blocks are deferred. 6450b57cec5SDimitry Andric std::vector<uint64_t> DeferredMetadataInfo; 6460b57cec5SDimitry Andric 6470b57cec5SDimitry Andric /// These are basic blocks forward-referenced by block addresses. They are 6480b57cec5SDimitry Andric /// inserted lazily into functions when they're loaded. The basic block ID is 6490b57cec5SDimitry Andric /// its index into the vector. 6500b57cec5SDimitry Andric DenseMap<Function *, std::vector<BasicBlock *>> BasicBlockFwdRefs; 6510b57cec5SDimitry Andric std::deque<Function *> BasicBlockFwdRefQueue; 6520b57cec5SDimitry Andric 65381ad6265SDimitry Andric /// These are Functions that contain BlockAddresses which refer a different 65481ad6265SDimitry Andric /// Function. When parsing the different Function, queue Functions that refer 65581ad6265SDimitry Andric /// to the different Function. Those Functions must be materialized in order 65681ad6265SDimitry Andric /// to resolve their BlockAddress constants before the different Function 65781ad6265SDimitry Andric /// gets moved into another Module. 65881ad6265SDimitry Andric std::vector<Function *> BackwardRefFunctions; 65981ad6265SDimitry Andric 6600b57cec5SDimitry Andric /// Indicates that we are using a new encoding for instruction operands where 6610b57cec5SDimitry Andric /// most operands in the current FUNCTION_BLOCK are encoded relative to the 6620b57cec5SDimitry Andric /// instruction number, for a more compact encoding. Some instruction 6630b57cec5SDimitry Andric /// operands are not relative to the instruction ID: basic block numbers, and 6640b57cec5SDimitry Andric /// types. Once the old style function blocks have been phased out, we would 6650b57cec5SDimitry Andric /// not need this flag. 6660b57cec5SDimitry Andric bool UseRelativeIDs = false; 6670b57cec5SDimitry Andric 6680b57cec5SDimitry Andric /// True if all functions will be materialized, negating the need to process 6690b57cec5SDimitry Andric /// (e.g.) blockaddress forward references. 6700b57cec5SDimitry Andric bool WillMaterializeAllForwardRefs = false; 6710b57cec5SDimitry Andric 6720b57cec5SDimitry Andric bool StripDebugInfo = false; 6730b57cec5SDimitry Andric TBAAVerifier TBAAVerifyHelper; 6740b57cec5SDimitry Andric 6750b57cec5SDimitry Andric std::vector<std::string> BundleTags; 6760b57cec5SDimitry Andric SmallVector<SyncScope::ID, 8> SSIDs; 6770b57cec5SDimitry Andric 678bdd1243dSDimitry Andric std::optional<ValueTypeCallbackTy> ValueTypeCallback; 679bdd1243dSDimitry Andric 6800b57cec5SDimitry Andric public: 6810b57cec5SDimitry Andric BitcodeReader(BitstreamCursor Stream, StringRef Strtab, 6820b57cec5SDimitry Andric StringRef ProducerIdentification, LLVMContext &Context); 6830b57cec5SDimitry Andric 6840b57cec5SDimitry Andric Error materializeForwardReferencedFunctions(); 6850b57cec5SDimitry Andric 6860b57cec5SDimitry Andric Error materialize(GlobalValue *GV) override; 6870b57cec5SDimitry Andric Error materializeModule() override; 6880b57cec5SDimitry Andric std::vector<StructType *> getIdentifiedStructTypes() const override; 6890b57cec5SDimitry Andric 6900b57cec5SDimitry Andric /// Main interface to parsing a bitcode buffer. 6910b57cec5SDimitry Andric /// \returns true if an error occurred. 692bdd1243dSDimitry Andric Error parseBitcodeInto(Module *M, bool ShouldLazyLoadMetadata, 693bdd1243dSDimitry Andric bool IsImporting, ParserCallbacks Callbacks = {}); 6940b57cec5SDimitry Andric 6950b57cec5SDimitry Andric static uint64_t decodeSignRotatedValue(uint64_t V); 6960b57cec5SDimitry Andric 6970b57cec5SDimitry Andric /// Materialize any deferred Metadata block. 6980b57cec5SDimitry Andric Error materializeMetadata() override; 6990b57cec5SDimitry Andric 7000b57cec5SDimitry Andric void setStripDebugInfo() override; 7010b57cec5SDimitry Andric 7020b57cec5SDimitry Andric private: 7030b57cec5SDimitry Andric std::vector<StructType *> IdentifiedStructTypes; 7040b57cec5SDimitry Andric StructType *createIdentifiedStructType(LLVMContext &Context, StringRef Name); 7050b57cec5SDimitry Andric StructType *createIdentifiedStructType(LLVMContext &Context); 7060b57cec5SDimitry Andric 70781ad6265SDimitry Andric static constexpr unsigned InvalidTypeID = ~0u; 7080b57cec5SDimitry Andric 70981ad6265SDimitry Andric Type *getTypeByID(unsigned ID); 71081ad6265SDimitry Andric Type *getPtrElementTypeByID(unsigned ID); 71181ad6265SDimitry Andric unsigned getContainedTypeID(unsigned ID, unsigned Idx = 0); 71281ad6265SDimitry Andric unsigned getVirtualTypeID(Type *Ty, ArrayRef<unsigned> ContainedTypeIDs = {}); 71381ad6265SDimitry Andric 714bdd1243dSDimitry Andric void callValueTypeCallback(Value *F, unsigned TypeID); 71581ad6265SDimitry Andric Expected<Value *> materializeValue(unsigned ValID, BasicBlock *InsertBB); 71681ad6265SDimitry Andric Expected<Constant *> getValueForInitializer(unsigned ID); 71781ad6265SDimitry Andric 71881ad6265SDimitry Andric Value *getFnValueByID(unsigned ID, Type *Ty, unsigned TyID, 71981ad6265SDimitry Andric BasicBlock *ConstExprInsertBB) { 7200b57cec5SDimitry Andric if (Ty && Ty->isMetadataTy()) 7210b57cec5SDimitry Andric return MetadataAsValue::get(Ty->getContext(), getFnMetadataByID(ID)); 72281ad6265SDimitry Andric return ValueList.getValueFwdRef(ID, Ty, TyID, ConstExprInsertBB); 7230b57cec5SDimitry Andric } 7240b57cec5SDimitry Andric 7250b57cec5SDimitry Andric Metadata *getFnMetadataByID(unsigned ID) { 7260b57cec5SDimitry Andric return MDLoader->getMetadataFwdRefOrLoad(ID); 7270b57cec5SDimitry Andric } 7280b57cec5SDimitry Andric 7290b57cec5SDimitry Andric BasicBlock *getBasicBlock(unsigned ID) const { 7300b57cec5SDimitry Andric if (ID >= FunctionBBs.size()) return nullptr; // Invalid ID 7310b57cec5SDimitry Andric return FunctionBBs[ID]; 7320b57cec5SDimitry Andric } 7330b57cec5SDimitry Andric 7340b57cec5SDimitry Andric AttributeList getAttributes(unsigned i) const { 7350b57cec5SDimitry Andric if (i-1 < MAttributes.size()) 7360b57cec5SDimitry Andric return MAttributes[i-1]; 7370b57cec5SDimitry Andric return AttributeList(); 7380b57cec5SDimitry Andric } 7390b57cec5SDimitry Andric 7400b57cec5SDimitry Andric /// Read a value/type pair out of the specified record from slot 'Slot'. 7410b57cec5SDimitry Andric /// Increment Slot past the number of slots used in the record. Return true on 7420b57cec5SDimitry Andric /// failure. 743e8d8bef9SDimitry Andric bool getValueTypePair(const SmallVectorImpl<uint64_t> &Record, unsigned &Slot, 74481ad6265SDimitry Andric unsigned InstNum, Value *&ResVal, unsigned &TypeID, 74581ad6265SDimitry Andric BasicBlock *ConstExprInsertBB) { 7460b57cec5SDimitry Andric if (Slot == Record.size()) return true; 7470b57cec5SDimitry Andric unsigned ValNo = (unsigned)Record[Slot++]; 7480b57cec5SDimitry Andric // Adjust the ValNo, if it was encoded relative to the InstNum. 7490b57cec5SDimitry Andric if (UseRelativeIDs) 7500b57cec5SDimitry Andric ValNo = InstNum - ValNo; 7510b57cec5SDimitry Andric if (ValNo < InstNum) { 7520b57cec5SDimitry Andric // If this is not a forward reference, just return the value we already 7530b57cec5SDimitry Andric // have. 75481ad6265SDimitry Andric TypeID = ValueList.getTypeID(ValNo); 75581ad6265SDimitry Andric ResVal = getFnValueByID(ValNo, nullptr, TypeID, ConstExprInsertBB); 75681ad6265SDimitry Andric assert((!ResVal || ResVal->getType() == getTypeByID(TypeID)) && 75781ad6265SDimitry Andric "Incorrect type ID stored for value"); 7580b57cec5SDimitry Andric return ResVal == nullptr; 7590b57cec5SDimitry Andric } 7600b57cec5SDimitry Andric if (Slot == Record.size()) 7610b57cec5SDimitry Andric return true; 7620b57cec5SDimitry Andric 76381ad6265SDimitry Andric TypeID = (unsigned)Record[Slot++]; 76481ad6265SDimitry Andric ResVal = getFnValueByID(ValNo, getTypeByID(TypeID), TypeID, 76581ad6265SDimitry Andric ConstExprInsertBB); 7660b57cec5SDimitry Andric return ResVal == nullptr; 7670b57cec5SDimitry Andric } 7680b57cec5SDimitry Andric 7690b57cec5SDimitry Andric /// Read a value out of the specified record from slot 'Slot'. Increment Slot 7700b57cec5SDimitry Andric /// past the number of slots used by the value in the record. Return true if 7710b57cec5SDimitry Andric /// there is an error. 772e8d8bef9SDimitry Andric bool popValue(const SmallVectorImpl<uint64_t> &Record, unsigned &Slot, 77381ad6265SDimitry Andric unsigned InstNum, Type *Ty, unsigned TyID, Value *&ResVal, 77481ad6265SDimitry Andric BasicBlock *ConstExprInsertBB) { 77581ad6265SDimitry Andric if (getValue(Record, Slot, InstNum, Ty, TyID, ResVal, ConstExprInsertBB)) 7760b57cec5SDimitry Andric return true; 7770b57cec5SDimitry Andric // All values currently take a single record slot. 7780b57cec5SDimitry Andric ++Slot; 7790b57cec5SDimitry Andric return false; 7800b57cec5SDimitry Andric } 7810b57cec5SDimitry Andric 7820b57cec5SDimitry Andric /// Like popValue, but does not increment the Slot number. 783e8d8bef9SDimitry Andric bool getValue(const SmallVectorImpl<uint64_t> &Record, unsigned Slot, 78481ad6265SDimitry Andric unsigned InstNum, Type *Ty, unsigned TyID, Value *&ResVal, 78581ad6265SDimitry Andric BasicBlock *ConstExprInsertBB) { 78681ad6265SDimitry Andric ResVal = getValue(Record, Slot, InstNum, Ty, TyID, ConstExprInsertBB); 7870b57cec5SDimitry Andric return ResVal == nullptr; 7880b57cec5SDimitry Andric } 7890b57cec5SDimitry Andric 7900b57cec5SDimitry Andric /// Version of getValue that returns ResVal directly, or 0 if there is an 7910b57cec5SDimitry Andric /// error. 792e8d8bef9SDimitry Andric Value *getValue(const SmallVectorImpl<uint64_t> &Record, unsigned Slot, 79381ad6265SDimitry Andric unsigned InstNum, Type *Ty, unsigned TyID, 79481ad6265SDimitry Andric BasicBlock *ConstExprInsertBB) { 7950b57cec5SDimitry Andric if (Slot == Record.size()) return nullptr; 7960b57cec5SDimitry Andric unsigned ValNo = (unsigned)Record[Slot]; 7970b57cec5SDimitry Andric // Adjust the ValNo, if it was encoded relative to the InstNum. 7980b57cec5SDimitry Andric if (UseRelativeIDs) 7990b57cec5SDimitry Andric ValNo = InstNum - ValNo; 80081ad6265SDimitry Andric return getFnValueByID(ValNo, Ty, TyID, ConstExprInsertBB); 8010b57cec5SDimitry Andric } 8020b57cec5SDimitry Andric 8030b57cec5SDimitry Andric /// Like getValue, but decodes signed VBRs. 804e8d8bef9SDimitry Andric Value *getValueSigned(const SmallVectorImpl<uint64_t> &Record, unsigned Slot, 80581ad6265SDimitry Andric unsigned InstNum, Type *Ty, unsigned TyID, 80681ad6265SDimitry Andric BasicBlock *ConstExprInsertBB) { 8070b57cec5SDimitry Andric if (Slot == Record.size()) return nullptr; 8080b57cec5SDimitry Andric unsigned ValNo = (unsigned)decodeSignRotatedValue(Record[Slot]); 8090b57cec5SDimitry Andric // Adjust the ValNo, if it was encoded relative to the InstNum. 8100b57cec5SDimitry Andric if (UseRelativeIDs) 8110b57cec5SDimitry Andric ValNo = InstNum - ValNo; 81281ad6265SDimitry Andric return getFnValueByID(ValNo, Ty, TyID, ConstExprInsertBB); 8130b57cec5SDimitry Andric } 8140b57cec5SDimitry Andric 815fe6060f1SDimitry Andric /// Upgrades old-style typeless byval/sret/inalloca attributes by adding the 816fe6060f1SDimitry Andric /// corresponding argument's pointee type. Also upgrades intrinsics that now 817fe6060f1SDimitry Andric /// require an elementtype attribute. 81881ad6265SDimitry Andric Error propagateAttributeTypes(CallBase *CB, ArrayRef<unsigned> ArgsTys); 8190b57cec5SDimitry Andric 8200b57cec5SDimitry Andric /// Converts alignment exponent (i.e. power of two (or zero)) to the 8210b57cec5SDimitry Andric /// corresponding alignment to use. If alignment is too large, returns 8220b57cec5SDimitry Andric /// a corresponding error code. 8238bcb0991SDimitry Andric Error parseAlignmentValue(uint64_t Exponent, MaybeAlign &Alignment); 8240b57cec5SDimitry Andric Error parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind); 825bdd1243dSDimitry Andric Error parseModule(uint64_t ResumeBit, bool ShouldLazyLoadMetadata = false, 826bdd1243dSDimitry Andric ParserCallbacks Callbacks = {}); 8270b57cec5SDimitry Andric 8280b57cec5SDimitry Andric Error parseComdatRecord(ArrayRef<uint64_t> Record); 8290b57cec5SDimitry Andric Error parseGlobalVarRecord(ArrayRef<uint64_t> Record); 8300b57cec5SDimitry Andric Error parseFunctionRecord(ArrayRef<uint64_t> Record); 8310b57cec5SDimitry Andric Error parseGlobalIndirectSymbolRecord(unsigned BitCode, 8320b57cec5SDimitry Andric ArrayRef<uint64_t> Record); 8330b57cec5SDimitry Andric 8340b57cec5SDimitry Andric Error parseAttributeBlock(); 8350b57cec5SDimitry Andric Error parseAttributeGroupBlock(); 8360b57cec5SDimitry Andric Error parseTypeTable(); 8370b57cec5SDimitry Andric Error parseTypeTableBody(); 8380b57cec5SDimitry Andric Error parseOperandBundleTags(); 8390b57cec5SDimitry Andric Error parseSyncScopeNames(); 8400b57cec5SDimitry Andric 8410b57cec5SDimitry Andric Expected<Value *> recordValue(SmallVectorImpl<uint64_t> &Record, 8420b57cec5SDimitry Andric unsigned NameIndex, Triple &TT); 8430b57cec5SDimitry Andric void setDeferredFunctionInfo(unsigned FuncBitcodeOffsetDelta, Function *F, 8440b57cec5SDimitry Andric ArrayRef<uint64_t> Record); 8450b57cec5SDimitry Andric Error parseValueSymbolTable(uint64_t Offset = 0); 8460b57cec5SDimitry Andric Error parseGlobalValueSymbolTable(); 8470b57cec5SDimitry Andric Error parseConstants(); 8480b57cec5SDimitry Andric Error rememberAndSkipFunctionBodies(); 8490b57cec5SDimitry Andric Error rememberAndSkipFunctionBody(); 8500b57cec5SDimitry Andric /// Save the positions of the Metadata blocks and skip parsing the blocks. 8510b57cec5SDimitry Andric Error rememberAndSkipMetadata(); 8520b57cec5SDimitry Andric Error typeCheckLoadStoreInst(Type *ValType, Type *PtrType); 8530b57cec5SDimitry Andric Error parseFunctionBody(Function *F); 8540b57cec5SDimitry Andric Error globalCleanup(); 8550b57cec5SDimitry Andric Error resolveGlobalAndIndirectSymbolInits(); 8560b57cec5SDimitry Andric Error parseUseLists(); 8570b57cec5SDimitry Andric Error findFunctionInStream( 8580b57cec5SDimitry Andric Function *F, 8590b57cec5SDimitry Andric DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator); 8600b57cec5SDimitry Andric 8610b57cec5SDimitry Andric SyncScope::ID getDecodedSyncScopeID(unsigned Val); 8620b57cec5SDimitry Andric }; 8630b57cec5SDimitry Andric 8640b57cec5SDimitry Andric /// Class to manage reading and parsing function summary index bitcode 8650b57cec5SDimitry Andric /// files/sections. 8660b57cec5SDimitry Andric class ModuleSummaryIndexBitcodeReader : public BitcodeReaderBase { 8670b57cec5SDimitry Andric /// The module index built during parsing. 8680b57cec5SDimitry Andric ModuleSummaryIndex &TheIndex; 8690b57cec5SDimitry Andric 8700b57cec5SDimitry Andric /// Indicates whether we have encountered a global value summary section 8710b57cec5SDimitry Andric /// yet during parsing. 8720b57cec5SDimitry Andric bool SeenGlobalValSummary = false; 8730b57cec5SDimitry Andric 8740b57cec5SDimitry Andric /// Indicates whether we have already parsed the VST, used for error checking. 8750b57cec5SDimitry Andric bool SeenValueSymbolTable = false; 8760b57cec5SDimitry Andric 8770b57cec5SDimitry Andric /// Set to the offset of the VST recorded in the MODULE_CODE_VSTOFFSET record. 8780b57cec5SDimitry Andric /// Used to enable on-demand parsing of the VST. 8790b57cec5SDimitry Andric uint64_t VSTOffset = 0; 8800b57cec5SDimitry Andric 8810b57cec5SDimitry Andric // Map to save ValueId to ValueInfo association that was recorded in the 8820b57cec5SDimitry Andric // ValueSymbolTable. It is used after the VST is parsed to convert 8830b57cec5SDimitry Andric // call graph edges read from the function summary from referencing 8840b57cec5SDimitry Andric // callees by their ValueId to using the ValueInfo instead, which is how 8850b57cec5SDimitry Andric // they are recorded in the summary index being built. 8860b57cec5SDimitry Andric // We save a GUID which refers to the same global as the ValueInfo, but 8870b57cec5SDimitry Andric // ignoring the linkage, i.e. for values other than local linkage they are 888bdd1243dSDimitry Andric // identical (this is the second tuple member). 889bdd1243dSDimitry Andric // The third tuple member is the real GUID of the ValueInfo. 890bdd1243dSDimitry Andric DenseMap<unsigned, 891bdd1243dSDimitry Andric std::tuple<ValueInfo, GlobalValue::GUID, GlobalValue::GUID>> 8920b57cec5SDimitry Andric ValueIdToValueInfoMap; 8930b57cec5SDimitry Andric 8940b57cec5SDimitry Andric /// Map populated during module path string table parsing, from the 8950b57cec5SDimitry Andric /// module ID to a string reference owned by the index's module 8960b57cec5SDimitry Andric /// path string table, used to correlate with combined index 8970b57cec5SDimitry Andric /// summary records. 8980b57cec5SDimitry Andric DenseMap<uint64_t, StringRef> ModuleIdMap; 8990b57cec5SDimitry Andric 9000b57cec5SDimitry Andric /// Original source file name recorded in a bitcode record. 9010b57cec5SDimitry Andric std::string SourceFileName; 9020b57cec5SDimitry Andric 9030b57cec5SDimitry Andric /// The string identifier given to this module by the client, normally the 9040b57cec5SDimitry Andric /// path to the bitcode file. 9050b57cec5SDimitry Andric StringRef ModulePath; 9060b57cec5SDimitry Andric 9070b57cec5SDimitry Andric /// For per-module summary indexes, the unique numerical identifier given to 9080b57cec5SDimitry Andric /// this module by the client. 9090b57cec5SDimitry Andric unsigned ModuleId; 9100b57cec5SDimitry Andric 911bdd1243dSDimitry Andric /// Callback to ask whether a symbol is the prevailing copy when invoked 912bdd1243dSDimitry Andric /// during combined index building. 913bdd1243dSDimitry Andric std::function<bool(GlobalValue::GUID)> IsPrevailing; 914bdd1243dSDimitry Andric 915bdd1243dSDimitry Andric /// Saves the stack ids from the STACK_IDS record to consult when adding stack 916bdd1243dSDimitry Andric /// ids from the lists in the callsite and alloc entries to the index. 917bdd1243dSDimitry Andric std::vector<uint64_t> StackIds; 918bdd1243dSDimitry Andric 9190b57cec5SDimitry Andric public: 920bdd1243dSDimitry Andric ModuleSummaryIndexBitcodeReader( 921bdd1243dSDimitry Andric BitstreamCursor Stream, StringRef Strtab, ModuleSummaryIndex &TheIndex, 922bdd1243dSDimitry Andric StringRef ModulePath, unsigned ModuleId, 923bdd1243dSDimitry Andric std::function<bool(GlobalValue::GUID)> IsPrevailing = nullptr); 9240b57cec5SDimitry Andric 9250b57cec5SDimitry Andric Error parseModule(); 9260b57cec5SDimitry Andric 9270b57cec5SDimitry Andric private: 9280b57cec5SDimitry Andric void setValueGUID(uint64_t ValueID, StringRef ValueName, 9290b57cec5SDimitry Andric GlobalValue::LinkageTypes Linkage, 9300b57cec5SDimitry Andric StringRef SourceFileName); 9310b57cec5SDimitry Andric Error parseValueSymbolTable( 9320b57cec5SDimitry Andric uint64_t Offset, 9330b57cec5SDimitry Andric DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap); 9340b57cec5SDimitry Andric std::vector<ValueInfo> makeRefList(ArrayRef<uint64_t> Record); 9350b57cec5SDimitry Andric std::vector<FunctionSummary::EdgeTy> makeCallList(ArrayRef<uint64_t> Record, 9360b57cec5SDimitry Andric bool IsOldProfileFormat, 9370b57cec5SDimitry Andric bool HasProfile, 9380b57cec5SDimitry Andric bool HasRelBF); 9390b57cec5SDimitry Andric Error parseEntireSummary(unsigned ID); 9400b57cec5SDimitry Andric Error parseModuleStringTable(); 9410b57cec5SDimitry Andric void parseTypeIdCompatibleVtableSummaryRecord(ArrayRef<uint64_t> Record); 9420b57cec5SDimitry Andric void parseTypeIdCompatibleVtableInfo(ArrayRef<uint64_t> Record, size_t &Slot, 9430b57cec5SDimitry Andric TypeIdCompatibleVtableInfo &TypeId); 944e8d8bef9SDimitry Andric std::vector<FunctionSummary::ParamAccess> 945e8d8bef9SDimitry Andric parseParamAccesses(ArrayRef<uint64_t> Record); 9460b57cec5SDimitry Andric 947bdd1243dSDimitry Andric template <bool AllowNullValueInfo = false> 948bdd1243dSDimitry Andric std::tuple<ValueInfo, GlobalValue::GUID, GlobalValue::GUID> 9490b57cec5SDimitry Andric getValueInfoFromValueId(unsigned ValueId); 9500b57cec5SDimitry Andric 9510b57cec5SDimitry Andric void addThisModule(); 9520b57cec5SDimitry Andric ModuleSummaryIndex::ModuleInfo *getThisModule(); 9530b57cec5SDimitry Andric }; 9540b57cec5SDimitry Andric 9550b57cec5SDimitry Andric } // end anonymous namespace 9560b57cec5SDimitry Andric 9570b57cec5SDimitry Andric std::error_code llvm::errorToErrorCodeAndEmitErrors(LLVMContext &Ctx, 9580b57cec5SDimitry Andric Error Err) { 9590b57cec5SDimitry Andric if (Err) { 9600b57cec5SDimitry Andric std::error_code EC; 9610b57cec5SDimitry Andric handleAllErrors(std::move(Err), [&](ErrorInfoBase &EIB) { 9620b57cec5SDimitry Andric EC = EIB.convertToErrorCode(); 9630b57cec5SDimitry Andric Ctx.emitError(EIB.message()); 9640b57cec5SDimitry Andric }); 9650b57cec5SDimitry Andric return EC; 9660b57cec5SDimitry Andric } 9670b57cec5SDimitry Andric return std::error_code(); 9680b57cec5SDimitry Andric } 9690b57cec5SDimitry Andric 9700b57cec5SDimitry Andric BitcodeReader::BitcodeReader(BitstreamCursor Stream, StringRef Strtab, 9710b57cec5SDimitry Andric StringRef ProducerIdentification, 9720b57cec5SDimitry Andric LLVMContext &Context) 9730b57cec5SDimitry Andric : BitcodeReaderBase(std::move(Stream), Strtab), Context(Context), 97481ad6265SDimitry Andric ValueList(this->Stream.SizeInBytes(), 97581ad6265SDimitry Andric [this](unsigned ValID, BasicBlock *InsertBB) { 97681ad6265SDimitry Andric return materializeValue(ValID, InsertBB); 97781ad6265SDimitry Andric }) { 9785ffd83dbSDimitry Andric this->ProducerIdentification = std::string(ProducerIdentification); 9790b57cec5SDimitry Andric } 9800b57cec5SDimitry Andric 9810b57cec5SDimitry Andric Error BitcodeReader::materializeForwardReferencedFunctions() { 9820b57cec5SDimitry Andric if (WillMaterializeAllForwardRefs) 9830b57cec5SDimitry Andric return Error::success(); 9840b57cec5SDimitry Andric 9850b57cec5SDimitry Andric // Prevent recursion. 9860b57cec5SDimitry Andric WillMaterializeAllForwardRefs = true; 9870b57cec5SDimitry Andric 9880b57cec5SDimitry Andric while (!BasicBlockFwdRefQueue.empty()) { 9890b57cec5SDimitry Andric Function *F = BasicBlockFwdRefQueue.front(); 9900b57cec5SDimitry Andric BasicBlockFwdRefQueue.pop_front(); 9910b57cec5SDimitry Andric assert(F && "Expected valid function"); 9920b57cec5SDimitry Andric if (!BasicBlockFwdRefs.count(F)) 9930b57cec5SDimitry Andric // Already materialized. 9940b57cec5SDimitry Andric continue; 9950b57cec5SDimitry Andric 9960b57cec5SDimitry Andric // Check for a function that isn't materializable to prevent an infinite 9970b57cec5SDimitry Andric // loop. When parsing a blockaddress stored in a global variable, there 9980b57cec5SDimitry Andric // isn't a trivial way to check if a function will have a body without a 9990b57cec5SDimitry Andric // linear search through FunctionsWithBodies, so just check it here. 10000b57cec5SDimitry Andric if (!F->isMaterializable()) 10010b57cec5SDimitry Andric return error("Never resolved function from blockaddress"); 10020b57cec5SDimitry Andric 10030b57cec5SDimitry Andric // Try to materialize F. 10040b57cec5SDimitry Andric if (Error Err = materialize(F)) 10050b57cec5SDimitry Andric return Err; 10060b57cec5SDimitry Andric } 10070b57cec5SDimitry Andric assert(BasicBlockFwdRefs.empty() && "Function missing from queue"); 10080b57cec5SDimitry Andric 100981ad6265SDimitry Andric for (Function *F : BackwardRefFunctions) 101081ad6265SDimitry Andric if (Error Err = materialize(F)) 101181ad6265SDimitry Andric return Err; 101281ad6265SDimitry Andric BackwardRefFunctions.clear(); 101381ad6265SDimitry Andric 10140b57cec5SDimitry Andric // Reset state. 10150b57cec5SDimitry Andric WillMaterializeAllForwardRefs = false; 10160b57cec5SDimitry Andric return Error::success(); 10170b57cec5SDimitry Andric } 10180b57cec5SDimitry Andric 10190b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 10200b57cec5SDimitry Andric // Helper functions to implement forward reference resolution, etc. 10210b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 10220b57cec5SDimitry Andric 10230b57cec5SDimitry Andric static bool hasImplicitComdat(size_t Val) { 10240b57cec5SDimitry Andric switch (Val) { 10250b57cec5SDimitry Andric default: 10260b57cec5SDimitry Andric return false; 10270b57cec5SDimitry Andric case 1: // Old WeakAnyLinkage 10280b57cec5SDimitry Andric case 4: // Old LinkOnceAnyLinkage 10290b57cec5SDimitry Andric case 10: // Old WeakODRLinkage 10300b57cec5SDimitry Andric case 11: // Old LinkOnceODRLinkage 10310b57cec5SDimitry Andric return true; 10320b57cec5SDimitry Andric } 10330b57cec5SDimitry Andric } 10340b57cec5SDimitry Andric 10350b57cec5SDimitry Andric static GlobalValue::LinkageTypes getDecodedLinkage(unsigned Val) { 10360b57cec5SDimitry Andric switch (Val) { 10370b57cec5SDimitry Andric default: // Map unknown/new linkages to external 10380b57cec5SDimitry Andric case 0: 10390b57cec5SDimitry Andric return GlobalValue::ExternalLinkage; 10400b57cec5SDimitry Andric case 2: 10410b57cec5SDimitry Andric return GlobalValue::AppendingLinkage; 10420b57cec5SDimitry Andric case 3: 10430b57cec5SDimitry Andric return GlobalValue::InternalLinkage; 10440b57cec5SDimitry Andric case 5: 10450b57cec5SDimitry Andric return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage 10460b57cec5SDimitry Andric case 6: 10470b57cec5SDimitry Andric return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage 10480b57cec5SDimitry Andric case 7: 10490b57cec5SDimitry Andric return GlobalValue::ExternalWeakLinkage; 10500b57cec5SDimitry Andric case 8: 10510b57cec5SDimitry Andric return GlobalValue::CommonLinkage; 10520b57cec5SDimitry Andric case 9: 10530b57cec5SDimitry Andric return GlobalValue::PrivateLinkage; 10540b57cec5SDimitry Andric case 12: 10550b57cec5SDimitry Andric return GlobalValue::AvailableExternallyLinkage; 10560b57cec5SDimitry Andric case 13: 10570b57cec5SDimitry Andric return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage 10580b57cec5SDimitry Andric case 14: 10590b57cec5SDimitry Andric return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage 10600b57cec5SDimitry Andric case 15: 10610b57cec5SDimitry Andric return GlobalValue::ExternalLinkage; // Obsolete LinkOnceODRAutoHideLinkage 10620b57cec5SDimitry Andric case 1: // Old value with implicit comdat. 10630b57cec5SDimitry Andric case 16: 10640b57cec5SDimitry Andric return GlobalValue::WeakAnyLinkage; 10650b57cec5SDimitry Andric case 10: // Old value with implicit comdat. 10660b57cec5SDimitry Andric case 17: 10670b57cec5SDimitry Andric return GlobalValue::WeakODRLinkage; 10680b57cec5SDimitry Andric case 4: // Old value with implicit comdat. 10690b57cec5SDimitry Andric case 18: 10700b57cec5SDimitry Andric return GlobalValue::LinkOnceAnyLinkage; 10710b57cec5SDimitry Andric case 11: // Old value with implicit comdat. 10720b57cec5SDimitry Andric case 19: 10730b57cec5SDimitry Andric return GlobalValue::LinkOnceODRLinkage; 10740b57cec5SDimitry Andric } 10750b57cec5SDimitry Andric } 10760b57cec5SDimitry Andric 10770b57cec5SDimitry Andric static FunctionSummary::FFlags getDecodedFFlags(uint64_t RawFlags) { 10780b57cec5SDimitry Andric FunctionSummary::FFlags Flags; 10790b57cec5SDimitry Andric Flags.ReadNone = RawFlags & 0x1; 10800b57cec5SDimitry Andric Flags.ReadOnly = (RawFlags >> 1) & 0x1; 10810b57cec5SDimitry Andric Flags.NoRecurse = (RawFlags >> 2) & 0x1; 10820b57cec5SDimitry Andric Flags.ReturnDoesNotAlias = (RawFlags >> 3) & 0x1; 10830b57cec5SDimitry Andric Flags.NoInline = (RawFlags >> 4) & 0x1; 1084480093f4SDimitry Andric Flags.AlwaysInline = (RawFlags >> 5) & 0x1; 1085349cc55cSDimitry Andric Flags.NoUnwind = (RawFlags >> 6) & 0x1; 1086349cc55cSDimitry Andric Flags.MayThrow = (RawFlags >> 7) & 0x1; 1087349cc55cSDimitry Andric Flags.HasUnknownCall = (RawFlags >> 8) & 0x1; 10880eae32dcSDimitry Andric Flags.MustBeUnreachable = (RawFlags >> 9) & 0x1; 10890b57cec5SDimitry Andric return Flags; 10900b57cec5SDimitry Andric } 10910b57cec5SDimitry Andric 1092fe6060f1SDimitry Andric // Decode the flags for GlobalValue in the summary. The bits for each attribute: 1093fe6060f1SDimitry Andric // 1094fe6060f1SDimitry Andric // linkage: [0,4), notEligibleToImport: 4, live: 5, local: 6, canAutoHide: 7, 1095fe6060f1SDimitry Andric // visibility: [8, 10). 10960b57cec5SDimitry Andric static GlobalValueSummary::GVFlags getDecodedGVSummaryFlags(uint64_t RawFlags, 10970b57cec5SDimitry Andric uint64_t Version) { 10980b57cec5SDimitry Andric // Summary were not emitted before LLVM 3.9, we don't need to upgrade Linkage 10990b57cec5SDimitry Andric // like getDecodedLinkage() above. Any future change to the linkage enum and 11000b57cec5SDimitry Andric // to getDecodedLinkage() will need to be taken into account here as above. 11010b57cec5SDimitry Andric auto Linkage = GlobalValue::LinkageTypes(RawFlags & 0xF); // 4 bits 1102fe6060f1SDimitry Andric auto Visibility = GlobalValue::VisibilityTypes((RawFlags >> 8) & 3); // 2 bits 11030b57cec5SDimitry Andric RawFlags = RawFlags >> 4; 11040b57cec5SDimitry Andric bool NotEligibleToImport = (RawFlags & 0x1) || Version < 3; 11050b57cec5SDimitry Andric // The Live flag wasn't introduced until version 3. For dead stripping 11060b57cec5SDimitry Andric // to work correctly on earlier versions, we must conservatively treat all 11070b57cec5SDimitry Andric // values as live. 11080b57cec5SDimitry Andric bool Live = (RawFlags & 0x2) || Version < 3; 11090b57cec5SDimitry Andric bool Local = (RawFlags & 0x4); 11100b57cec5SDimitry Andric bool AutoHide = (RawFlags & 0x8); 11110b57cec5SDimitry Andric 1112fe6060f1SDimitry Andric return GlobalValueSummary::GVFlags(Linkage, Visibility, NotEligibleToImport, 1113fe6060f1SDimitry Andric Live, Local, AutoHide); 11140b57cec5SDimitry Andric } 11150b57cec5SDimitry Andric 11160b57cec5SDimitry Andric // Decode the flags for GlobalVariable in the summary 11170b57cec5SDimitry Andric static GlobalVarSummary::GVarFlags getDecodedGVarFlags(uint64_t RawFlags) { 11185ffd83dbSDimitry Andric return GlobalVarSummary::GVarFlags( 11195ffd83dbSDimitry Andric (RawFlags & 0x1) ? true : false, (RawFlags & 0x2) ? true : false, 11205ffd83dbSDimitry Andric (RawFlags & 0x4) ? true : false, 11215ffd83dbSDimitry Andric (GlobalObject::VCallVisibility)(RawFlags >> 3)); 11220b57cec5SDimitry Andric } 11230b57cec5SDimitry Andric 11240b57cec5SDimitry Andric static GlobalValue::VisibilityTypes getDecodedVisibility(unsigned Val) { 11250b57cec5SDimitry Andric switch (Val) { 11260b57cec5SDimitry Andric default: // Map unknown visibilities to default. 11270b57cec5SDimitry Andric case 0: return GlobalValue::DefaultVisibility; 11280b57cec5SDimitry Andric case 1: return GlobalValue::HiddenVisibility; 11290b57cec5SDimitry Andric case 2: return GlobalValue::ProtectedVisibility; 11300b57cec5SDimitry Andric } 11310b57cec5SDimitry Andric } 11320b57cec5SDimitry Andric 11330b57cec5SDimitry Andric static GlobalValue::DLLStorageClassTypes 11340b57cec5SDimitry Andric getDecodedDLLStorageClass(unsigned Val) { 11350b57cec5SDimitry Andric switch (Val) { 11360b57cec5SDimitry Andric default: // Map unknown values to default. 11370b57cec5SDimitry Andric case 0: return GlobalValue::DefaultStorageClass; 11380b57cec5SDimitry Andric case 1: return GlobalValue::DLLImportStorageClass; 11390b57cec5SDimitry Andric case 2: return GlobalValue::DLLExportStorageClass; 11400b57cec5SDimitry Andric } 11410b57cec5SDimitry Andric } 11420b57cec5SDimitry Andric 11430b57cec5SDimitry Andric static bool getDecodedDSOLocal(unsigned Val) { 11440b57cec5SDimitry Andric switch(Val) { 11450b57cec5SDimitry Andric default: // Map unknown values to preemptable. 11460b57cec5SDimitry Andric case 0: return false; 11470b57cec5SDimitry Andric case 1: return true; 11480b57cec5SDimitry Andric } 11490b57cec5SDimitry Andric } 11500b57cec5SDimitry Andric 11510b57cec5SDimitry Andric static GlobalVariable::ThreadLocalMode getDecodedThreadLocalMode(unsigned Val) { 11520b57cec5SDimitry Andric switch (Val) { 11530b57cec5SDimitry Andric case 0: return GlobalVariable::NotThreadLocal; 11540b57cec5SDimitry Andric default: // Map unknown non-zero value to general dynamic. 11550b57cec5SDimitry Andric case 1: return GlobalVariable::GeneralDynamicTLSModel; 11560b57cec5SDimitry Andric case 2: return GlobalVariable::LocalDynamicTLSModel; 11570b57cec5SDimitry Andric case 3: return GlobalVariable::InitialExecTLSModel; 11580b57cec5SDimitry Andric case 4: return GlobalVariable::LocalExecTLSModel; 11590b57cec5SDimitry Andric } 11600b57cec5SDimitry Andric } 11610b57cec5SDimitry Andric 11620b57cec5SDimitry Andric static GlobalVariable::UnnamedAddr getDecodedUnnamedAddrType(unsigned Val) { 11630b57cec5SDimitry Andric switch (Val) { 11640b57cec5SDimitry Andric default: // Map unknown to UnnamedAddr::None. 11650b57cec5SDimitry Andric case 0: return GlobalVariable::UnnamedAddr::None; 11660b57cec5SDimitry Andric case 1: return GlobalVariable::UnnamedAddr::Global; 11670b57cec5SDimitry Andric case 2: return GlobalVariable::UnnamedAddr::Local; 11680b57cec5SDimitry Andric } 11690b57cec5SDimitry Andric } 11700b57cec5SDimitry Andric 11710b57cec5SDimitry Andric static int getDecodedCastOpcode(unsigned Val) { 11720b57cec5SDimitry Andric switch (Val) { 11730b57cec5SDimitry Andric default: return -1; 11740b57cec5SDimitry Andric case bitc::CAST_TRUNC : return Instruction::Trunc; 11750b57cec5SDimitry Andric case bitc::CAST_ZEXT : return Instruction::ZExt; 11760b57cec5SDimitry Andric case bitc::CAST_SEXT : return Instruction::SExt; 11770b57cec5SDimitry Andric case bitc::CAST_FPTOUI : return Instruction::FPToUI; 11780b57cec5SDimitry Andric case bitc::CAST_FPTOSI : return Instruction::FPToSI; 11790b57cec5SDimitry Andric case bitc::CAST_UITOFP : return Instruction::UIToFP; 11800b57cec5SDimitry Andric case bitc::CAST_SITOFP : return Instruction::SIToFP; 11810b57cec5SDimitry Andric case bitc::CAST_FPTRUNC : return Instruction::FPTrunc; 11820b57cec5SDimitry Andric case bitc::CAST_FPEXT : return Instruction::FPExt; 11830b57cec5SDimitry Andric case bitc::CAST_PTRTOINT: return Instruction::PtrToInt; 11840b57cec5SDimitry Andric case bitc::CAST_INTTOPTR: return Instruction::IntToPtr; 11850b57cec5SDimitry Andric case bitc::CAST_BITCAST : return Instruction::BitCast; 11860b57cec5SDimitry Andric case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast; 11870b57cec5SDimitry Andric } 11880b57cec5SDimitry Andric } 11890b57cec5SDimitry Andric 11900b57cec5SDimitry Andric static int getDecodedUnaryOpcode(unsigned Val, Type *Ty) { 11910b57cec5SDimitry Andric bool IsFP = Ty->isFPOrFPVectorTy(); 11920b57cec5SDimitry Andric // UnOps are only valid for int/fp or vector of int/fp types 11930b57cec5SDimitry Andric if (!IsFP && !Ty->isIntOrIntVectorTy()) 11940b57cec5SDimitry Andric return -1; 11950b57cec5SDimitry Andric 11960b57cec5SDimitry Andric switch (Val) { 11970b57cec5SDimitry Andric default: 11980b57cec5SDimitry Andric return -1; 11998bcb0991SDimitry Andric case bitc::UNOP_FNEG: 12000b57cec5SDimitry Andric return IsFP ? Instruction::FNeg : -1; 12010b57cec5SDimitry Andric } 12020b57cec5SDimitry Andric } 12030b57cec5SDimitry Andric 12040b57cec5SDimitry Andric static int getDecodedBinaryOpcode(unsigned Val, Type *Ty) { 12050b57cec5SDimitry Andric bool IsFP = Ty->isFPOrFPVectorTy(); 12060b57cec5SDimitry Andric // BinOps are only valid for int/fp or vector of int/fp types 12070b57cec5SDimitry Andric if (!IsFP && !Ty->isIntOrIntVectorTy()) 12080b57cec5SDimitry Andric return -1; 12090b57cec5SDimitry Andric 12100b57cec5SDimitry Andric switch (Val) { 12110b57cec5SDimitry Andric default: 12120b57cec5SDimitry Andric return -1; 12130b57cec5SDimitry Andric case bitc::BINOP_ADD: 12140b57cec5SDimitry Andric return IsFP ? Instruction::FAdd : Instruction::Add; 12150b57cec5SDimitry Andric case bitc::BINOP_SUB: 12160b57cec5SDimitry Andric return IsFP ? Instruction::FSub : Instruction::Sub; 12170b57cec5SDimitry Andric case bitc::BINOP_MUL: 12180b57cec5SDimitry Andric return IsFP ? Instruction::FMul : Instruction::Mul; 12190b57cec5SDimitry Andric case bitc::BINOP_UDIV: 12200b57cec5SDimitry Andric return IsFP ? -1 : Instruction::UDiv; 12210b57cec5SDimitry Andric case bitc::BINOP_SDIV: 12220b57cec5SDimitry Andric return IsFP ? Instruction::FDiv : Instruction::SDiv; 12230b57cec5SDimitry Andric case bitc::BINOP_UREM: 12240b57cec5SDimitry Andric return IsFP ? -1 : Instruction::URem; 12250b57cec5SDimitry Andric case bitc::BINOP_SREM: 12260b57cec5SDimitry Andric return IsFP ? Instruction::FRem : Instruction::SRem; 12270b57cec5SDimitry Andric case bitc::BINOP_SHL: 12280b57cec5SDimitry Andric return IsFP ? -1 : Instruction::Shl; 12290b57cec5SDimitry Andric case bitc::BINOP_LSHR: 12300b57cec5SDimitry Andric return IsFP ? -1 : Instruction::LShr; 12310b57cec5SDimitry Andric case bitc::BINOP_ASHR: 12320b57cec5SDimitry Andric return IsFP ? -1 : Instruction::AShr; 12330b57cec5SDimitry Andric case bitc::BINOP_AND: 12340b57cec5SDimitry Andric return IsFP ? -1 : Instruction::And; 12350b57cec5SDimitry Andric case bitc::BINOP_OR: 12360b57cec5SDimitry Andric return IsFP ? -1 : Instruction::Or; 12370b57cec5SDimitry Andric case bitc::BINOP_XOR: 12380b57cec5SDimitry Andric return IsFP ? -1 : Instruction::Xor; 12390b57cec5SDimitry Andric } 12400b57cec5SDimitry Andric } 12410b57cec5SDimitry Andric 12420b57cec5SDimitry Andric static AtomicRMWInst::BinOp getDecodedRMWOperation(unsigned Val) { 12430b57cec5SDimitry Andric switch (Val) { 12440b57cec5SDimitry Andric default: return AtomicRMWInst::BAD_BINOP; 12450b57cec5SDimitry Andric case bitc::RMW_XCHG: return AtomicRMWInst::Xchg; 12460b57cec5SDimitry Andric case bitc::RMW_ADD: return AtomicRMWInst::Add; 12470b57cec5SDimitry Andric case bitc::RMW_SUB: return AtomicRMWInst::Sub; 12480b57cec5SDimitry Andric case bitc::RMW_AND: return AtomicRMWInst::And; 12490b57cec5SDimitry Andric case bitc::RMW_NAND: return AtomicRMWInst::Nand; 12500b57cec5SDimitry Andric case bitc::RMW_OR: return AtomicRMWInst::Or; 12510b57cec5SDimitry Andric case bitc::RMW_XOR: return AtomicRMWInst::Xor; 12520b57cec5SDimitry Andric case bitc::RMW_MAX: return AtomicRMWInst::Max; 12530b57cec5SDimitry Andric case bitc::RMW_MIN: return AtomicRMWInst::Min; 12540b57cec5SDimitry Andric case bitc::RMW_UMAX: return AtomicRMWInst::UMax; 12550b57cec5SDimitry Andric case bitc::RMW_UMIN: return AtomicRMWInst::UMin; 12560b57cec5SDimitry Andric case bitc::RMW_FADD: return AtomicRMWInst::FAdd; 12570b57cec5SDimitry Andric case bitc::RMW_FSUB: return AtomicRMWInst::FSub; 1258753f127fSDimitry Andric case bitc::RMW_FMAX: return AtomicRMWInst::FMax; 1259753f127fSDimitry Andric case bitc::RMW_FMIN: return AtomicRMWInst::FMin; 1260bdd1243dSDimitry Andric case bitc::RMW_UINC_WRAP: 1261bdd1243dSDimitry Andric return AtomicRMWInst::UIncWrap; 1262bdd1243dSDimitry Andric case bitc::RMW_UDEC_WRAP: 1263bdd1243dSDimitry Andric return AtomicRMWInst::UDecWrap; 12640b57cec5SDimitry Andric } 12650b57cec5SDimitry Andric } 12660b57cec5SDimitry Andric 12670b57cec5SDimitry Andric static AtomicOrdering getDecodedOrdering(unsigned Val) { 12680b57cec5SDimitry Andric switch (Val) { 12690b57cec5SDimitry Andric case bitc::ORDERING_NOTATOMIC: return AtomicOrdering::NotAtomic; 12700b57cec5SDimitry Andric case bitc::ORDERING_UNORDERED: return AtomicOrdering::Unordered; 12710b57cec5SDimitry Andric case bitc::ORDERING_MONOTONIC: return AtomicOrdering::Monotonic; 12720b57cec5SDimitry Andric case bitc::ORDERING_ACQUIRE: return AtomicOrdering::Acquire; 12730b57cec5SDimitry Andric case bitc::ORDERING_RELEASE: return AtomicOrdering::Release; 12740b57cec5SDimitry Andric case bitc::ORDERING_ACQREL: return AtomicOrdering::AcquireRelease; 12750b57cec5SDimitry Andric default: // Map unknown orderings to sequentially-consistent. 12760b57cec5SDimitry Andric case bitc::ORDERING_SEQCST: return AtomicOrdering::SequentiallyConsistent; 12770b57cec5SDimitry Andric } 12780b57cec5SDimitry Andric } 12790b57cec5SDimitry Andric 12800b57cec5SDimitry Andric static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val) { 12810b57cec5SDimitry Andric switch (Val) { 12820b57cec5SDimitry Andric default: // Map unknown selection kinds to any. 12830b57cec5SDimitry Andric case bitc::COMDAT_SELECTION_KIND_ANY: 12840b57cec5SDimitry Andric return Comdat::Any; 12850b57cec5SDimitry Andric case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH: 12860b57cec5SDimitry Andric return Comdat::ExactMatch; 12870b57cec5SDimitry Andric case bitc::COMDAT_SELECTION_KIND_LARGEST: 12880b57cec5SDimitry Andric return Comdat::Largest; 12890b57cec5SDimitry Andric case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES: 1290fe6060f1SDimitry Andric return Comdat::NoDeduplicate; 12910b57cec5SDimitry Andric case bitc::COMDAT_SELECTION_KIND_SAME_SIZE: 12920b57cec5SDimitry Andric return Comdat::SameSize; 12930b57cec5SDimitry Andric } 12940b57cec5SDimitry Andric } 12950b57cec5SDimitry Andric 12960b57cec5SDimitry Andric static FastMathFlags getDecodedFastMathFlags(unsigned Val) { 12970b57cec5SDimitry Andric FastMathFlags FMF; 12980b57cec5SDimitry Andric if (0 != (Val & bitc::UnsafeAlgebra)) 12990b57cec5SDimitry Andric FMF.setFast(); 13000b57cec5SDimitry Andric if (0 != (Val & bitc::AllowReassoc)) 13010b57cec5SDimitry Andric FMF.setAllowReassoc(); 13020b57cec5SDimitry Andric if (0 != (Val & bitc::NoNaNs)) 13030b57cec5SDimitry Andric FMF.setNoNaNs(); 13040b57cec5SDimitry Andric if (0 != (Val & bitc::NoInfs)) 13050b57cec5SDimitry Andric FMF.setNoInfs(); 13060b57cec5SDimitry Andric if (0 != (Val & bitc::NoSignedZeros)) 13070b57cec5SDimitry Andric FMF.setNoSignedZeros(); 13080b57cec5SDimitry Andric if (0 != (Val & bitc::AllowReciprocal)) 13090b57cec5SDimitry Andric FMF.setAllowReciprocal(); 13100b57cec5SDimitry Andric if (0 != (Val & bitc::AllowContract)) 13110b57cec5SDimitry Andric FMF.setAllowContract(true); 13120b57cec5SDimitry Andric if (0 != (Val & bitc::ApproxFunc)) 13130b57cec5SDimitry Andric FMF.setApproxFunc(); 13140b57cec5SDimitry Andric return FMF; 13150b57cec5SDimitry Andric } 13160b57cec5SDimitry Andric 13170b57cec5SDimitry Andric static void upgradeDLLImportExportLinkage(GlobalValue *GV, unsigned Val) { 1318bdd1243dSDimitry Andric // A GlobalValue with local linkage cannot have a DLL storage class. 1319bdd1243dSDimitry Andric if (GV->hasLocalLinkage()) 1320bdd1243dSDimitry Andric return; 13210b57cec5SDimitry Andric switch (Val) { 13220b57cec5SDimitry Andric case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break; 13230b57cec5SDimitry Andric case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break; 13240b57cec5SDimitry Andric } 13250b57cec5SDimitry Andric } 13260b57cec5SDimitry Andric 1327fe6060f1SDimitry Andric Type *BitcodeReader::getTypeByID(unsigned ID) { 13280b57cec5SDimitry Andric // The type table size is always specified correctly. 13290b57cec5SDimitry Andric if (ID >= TypeList.size()) 13300b57cec5SDimitry Andric return nullptr; 13310b57cec5SDimitry Andric 13320b57cec5SDimitry Andric if (Type *Ty = TypeList[ID]) 13330b57cec5SDimitry Andric return Ty; 13340b57cec5SDimitry Andric 13350b57cec5SDimitry Andric // If we have a forward reference, the only possible case is when it is to a 13360b57cec5SDimitry Andric // named struct. Just create a placeholder for now. 13370b57cec5SDimitry Andric return TypeList[ID] = createIdentifiedStructType(Context); 13380b57cec5SDimitry Andric } 13390b57cec5SDimitry Andric 134081ad6265SDimitry Andric unsigned BitcodeReader::getContainedTypeID(unsigned ID, unsigned Idx) { 134181ad6265SDimitry Andric auto It = ContainedTypeIDs.find(ID); 134281ad6265SDimitry Andric if (It == ContainedTypeIDs.end()) 134381ad6265SDimitry Andric return InvalidTypeID; 134481ad6265SDimitry Andric 134581ad6265SDimitry Andric if (Idx >= It->second.size()) 134681ad6265SDimitry Andric return InvalidTypeID; 134781ad6265SDimitry Andric 134881ad6265SDimitry Andric return It->second[Idx]; 134981ad6265SDimitry Andric } 135081ad6265SDimitry Andric 135181ad6265SDimitry Andric Type *BitcodeReader::getPtrElementTypeByID(unsigned ID) { 135281ad6265SDimitry Andric if (ID >= TypeList.size()) 135381ad6265SDimitry Andric return nullptr; 135481ad6265SDimitry Andric 135581ad6265SDimitry Andric Type *Ty = TypeList[ID]; 135681ad6265SDimitry Andric if (!Ty->isPointerTy()) 135781ad6265SDimitry Andric return nullptr; 135881ad6265SDimitry Andric 1359*fe013be4SDimitry Andric return getTypeByID(getContainedTypeID(ID, 0)); 136081ad6265SDimitry Andric } 136181ad6265SDimitry Andric 136281ad6265SDimitry Andric unsigned BitcodeReader::getVirtualTypeID(Type *Ty, 136381ad6265SDimitry Andric ArrayRef<unsigned> ChildTypeIDs) { 136481ad6265SDimitry Andric unsigned ChildTypeID = ChildTypeIDs.empty() ? InvalidTypeID : ChildTypeIDs[0]; 136581ad6265SDimitry Andric auto CacheKey = std::make_pair(Ty, ChildTypeID); 136681ad6265SDimitry Andric auto It = VirtualTypeIDs.find(CacheKey); 136781ad6265SDimitry Andric if (It != VirtualTypeIDs.end()) { 136881ad6265SDimitry Andric // The cmpxchg return value is the only place we need more than one 136981ad6265SDimitry Andric // contained type ID, however the second one will always be the same (i1), 137081ad6265SDimitry Andric // so we don't need to include it in the cache key. This asserts that the 137181ad6265SDimitry Andric // contained types are indeed as expected and there are no collisions. 137281ad6265SDimitry Andric assert((ChildTypeIDs.empty() || 137381ad6265SDimitry Andric ContainedTypeIDs[It->second] == ChildTypeIDs) && 137481ad6265SDimitry Andric "Incorrect cached contained type IDs"); 137581ad6265SDimitry Andric return It->second; 137681ad6265SDimitry Andric } 137781ad6265SDimitry Andric 137881ad6265SDimitry Andric unsigned TypeID = TypeList.size(); 137981ad6265SDimitry Andric TypeList.push_back(Ty); 138081ad6265SDimitry Andric if (!ChildTypeIDs.empty()) 138181ad6265SDimitry Andric append_range(ContainedTypeIDs[TypeID], ChildTypeIDs); 138281ad6265SDimitry Andric VirtualTypeIDs.insert({CacheKey, TypeID}); 138381ad6265SDimitry Andric return TypeID; 138481ad6265SDimitry Andric } 138581ad6265SDimitry Andric 1386*fe013be4SDimitry Andric static bool isConstExprSupported(const BitcodeConstant *BC) { 1387*fe013be4SDimitry Andric uint8_t Opcode = BC->Opcode; 1388*fe013be4SDimitry Andric 138981ad6265SDimitry Andric // These are not real constant expressions, always consider them supported. 139081ad6265SDimitry Andric if (Opcode >= BitcodeConstant::FirstSpecialOpcode) 139181ad6265SDimitry Andric return true; 139281ad6265SDimitry Andric 1393bdd1243dSDimitry Andric // If -expand-constant-exprs is set, we want to consider all expressions 1394bdd1243dSDimitry Andric // as unsupported. 1395bdd1243dSDimitry Andric if (ExpandConstantExprs) 1396bdd1243dSDimitry Andric return false; 1397bdd1243dSDimitry Andric 1398753f127fSDimitry Andric if (Instruction::isBinaryOp(Opcode)) 1399753f127fSDimitry Andric return ConstantExpr::isSupportedBinOp(Opcode); 1400753f127fSDimitry Andric 1401*fe013be4SDimitry Andric if (Opcode == Instruction::GetElementPtr) 1402*fe013be4SDimitry Andric return ConstantExpr::isSupportedGetElementPtr(BC->SrcElemTy); 1403*fe013be4SDimitry Andric 1404*fe013be4SDimitry Andric switch (Opcode) { 1405*fe013be4SDimitry Andric case Instruction::FNeg: 1406*fe013be4SDimitry Andric case Instruction::Select: 1407*fe013be4SDimitry Andric return false; 1408*fe013be4SDimitry Andric default: 1409*fe013be4SDimitry Andric return true; 1410*fe013be4SDimitry Andric } 141181ad6265SDimitry Andric } 141281ad6265SDimitry Andric 141381ad6265SDimitry Andric Expected<Value *> BitcodeReader::materializeValue(unsigned StartValID, 141481ad6265SDimitry Andric BasicBlock *InsertBB) { 141581ad6265SDimitry Andric // Quickly handle the case where there is no BitcodeConstant to resolve. 141681ad6265SDimitry Andric if (StartValID < ValueList.size() && ValueList[StartValID] && 141781ad6265SDimitry Andric !isa<BitcodeConstant>(ValueList[StartValID])) 141881ad6265SDimitry Andric return ValueList[StartValID]; 141981ad6265SDimitry Andric 142081ad6265SDimitry Andric SmallDenseMap<unsigned, Value *> MaterializedValues; 142181ad6265SDimitry Andric SmallVector<unsigned> Worklist; 142281ad6265SDimitry Andric Worklist.push_back(StartValID); 142381ad6265SDimitry Andric while (!Worklist.empty()) { 142481ad6265SDimitry Andric unsigned ValID = Worklist.back(); 142581ad6265SDimitry Andric if (MaterializedValues.count(ValID)) { 142681ad6265SDimitry Andric // Duplicate expression that was already handled. 142781ad6265SDimitry Andric Worklist.pop_back(); 142881ad6265SDimitry Andric continue; 142981ad6265SDimitry Andric } 143081ad6265SDimitry Andric 143181ad6265SDimitry Andric if (ValID >= ValueList.size() || !ValueList[ValID]) 143281ad6265SDimitry Andric return error("Invalid value ID"); 143381ad6265SDimitry Andric 143481ad6265SDimitry Andric Value *V = ValueList[ValID]; 143581ad6265SDimitry Andric auto *BC = dyn_cast<BitcodeConstant>(V); 143681ad6265SDimitry Andric if (!BC) { 143781ad6265SDimitry Andric MaterializedValues.insert({ValID, V}); 143881ad6265SDimitry Andric Worklist.pop_back(); 143981ad6265SDimitry Andric continue; 144081ad6265SDimitry Andric } 144181ad6265SDimitry Andric 144281ad6265SDimitry Andric // Iterate in reverse, so values will get popped from the worklist in 144381ad6265SDimitry Andric // expected order. 144481ad6265SDimitry Andric SmallVector<Value *> Ops; 144581ad6265SDimitry Andric for (unsigned OpID : reverse(BC->getOperandIDs())) { 144681ad6265SDimitry Andric auto It = MaterializedValues.find(OpID); 144781ad6265SDimitry Andric if (It != MaterializedValues.end()) 144881ad6265SDimitry Andric Ops.push_back(It->second); 144981ad6265SDimitry Andric else 145081ad6265SDimitry Andric Worklist.push_back(OpID); 145181ad6265SDimitry Andric } 145281ad6265SDimitry Andric 145381ad6265SDimitry Andric // Some expressions have not been resolved yet, handle them first and then 145481ad6265SDimitry Andric // revisit this one. 145581ad6265SDimitry Andric if (Ops.size() != BC->getOperandIDs().size()) 145681ad6265SDimitry Andric continue; 145781ad6265SDimitry Andric std::reverse(Ops.begin(), Ops.end()); 145881ad6265SDimitry Andric 145981ad6265SDimitry Andric SmallVector<Constant *> ConstOps; 146081ad6265SDimitry Andric for (Value *Op : Ops) 146181ad6265SDimitry Andric if (auto *C = dyn_cast<Constant>(Op)) 146281ad6265SDimitry Andric ConstOps.push_back(C); 146381ad6265SDimitry Andric 146481ad6265SDimitry Andric // Materialize as constant expression if possible. 1465*fe013be4SDimitry Andric if (isConstExprSupported(BC) && ConstOps.size() == Ops.size()) { 146681ad6265SDimitry Andric Constant *C; 146781ad6265SDimitry Andric if (Instruction::isCast(BC->Opcode)) { 146881ad6265SDimitry Andric C = UpgradeBitCastExpr(BC->Opcode, ConstOps[0], BC->getType()); 146981ad6265SDimitry Andric if (!C) 147081ad6265SDimitry Andric C = ConstantExpr::getCast(BC->Opcode, ConstOps[0], BC->getType()); 147181ad6265SDimitry Andric } else if (Instruction::isBinaryOp(BC->Opcode)) { 147281ad6265SDimitry Andric C = ConstantExpr::get(BC->Opcode, ConstOps[0], ConstOps[1], BC->Flags); 147381ad6265SDimitry Andric } else { 147481ad6265SDimitry Andric switch (BC->Opcode) { 147581ad6265SDimitry Andric case BitcodeConstant::NoCFIOpcode: { 147681ad6265SDimitry Andric auto *GV = dyn_cast<GlobalValue>(ConstOps[0]); 147781ad6265SDimitry Andric if (!GV) 147881ad6265SDimitry Andric return error("no_cfi operand must be GlobalValue"); 147981ad6265SDimitry Andric C = NoCFIValue::get(GV); 148081ad6265SDimitry Andric break; 148181ad6265SDimitry Andric } 148281ad6265SDimitry Andric case BitcodeConstant::DSOLocalEquivalentOpcode: { 148381ad6265SDimitry Andric auto *GV = dyn_cast<GlobalValue>(ConstOps[0]); 148481ad6265SDimitry Andric if (!GV) 148581ad6265SDimitry Andric return error("dso_local operand must be GlobalValue"); 148681ad6265SDimitry Andric C = DSOLocalEquivalent::get(GV); 148781ad6265SDimitry Andric break; 148881ad6265SDimitry Andric } 148981ad6265SDimitry Andric case BitcodeConstant::BlockAddressOpcode: { 149081ad6265SDimitry Andric Function *Fn = dyn_cast<Function>(ConstOps[0]); 149181ad6265SDimitry Andric if (!Fn) 149281ad6265SDimitry Andric return error("blockaddress operand must be a function"); 149381ad6265SDimitry Andric 149481ad6265SDimitry Andric // If the function is already parsed we can insert the block address 149581ad6265SDimitry Andric // right away. 149681ad6265SDimitry Andric BasicBlock *BB; 149781ad6265SDimitry Andric unsigned BBID = BC->Extra; 149881ad6265SDimitry Andric if (!BBID) 149981ad6265SDimitry Andric // Invalid reference to entry block. 150081ad6265SDimitry Andric return error("Invalid ID"); 150181ad6265SDimitry Andric if (!Fn->empty()) { 150281ad6265SDimitry Andric Function::iterator BBI = Fn->begin(), BBE = Fn->end(); 150381ad6265SDimitry Andric for (size_t I = 0, E = BBID; I != E; ++I) { 150481ad6265SDimitry Andric if (BBI == BBE) 150581ad6265SDimitry Andric return error("Invalid ID"); 150681ad6265SDimitry Andric ++BBI; 150781ad6265SDimitry Andric } 150881ad6265SDimitry Andric BB = &*BBI; 150981ad6265SDimitry Andric } else { 151081ad6265SDimitry Andric // Otherwise insert a placeholder and remember it so it can be 151181ad6265SDimitry Andric // inserted when the function is parsed. 151281ad6265SDimitry Andric auto &FwdBBs = BasicBlockFwdRefs[Fn]; 151381ad6265SDimitry Andric if (FwdBBs.empty()) 151481ad6265SDimitry Andric BasicBlockFwdRefQueue.push_back(Fn); 151581ad6265SDimitry Andric if (FwdBBs.size() < BBID + 1) 151681ad6265SDimitry Andric FwdBBs.resize(BBID + 1); 151781ad6265SDimitry Andric if (!FwdBBs[BBID]) 151881ad6265SDimitry Andric FwdBBs[BBID] = BasicBlock::Create(Context); 151981ad6265SDimitry Andric BB = FwdBBs[BBID]; 152081ad6265SDimitry Andric } 152181ad6265SDimitry Andric C = BlockAddress::get(Fn, BB); 152281ad6265SDimitry Andric break; 152381ad6265SDimitry Andric } 152481ad6265SDimitry Andric case BitcodeConstant::ConstantStructOpcode: 152581ad6265SDimitry Andric C = ConstantStruct::get(cast<StructType>(BC->getType()), ConstOps); 152681ad6265SDimitry Andric break; 152781ad6265SDimitry Andric case BitcodeConstant::ConstantArrayOpcode: 152881ad6265SDimitry Andric C = ConstantArray::get(cast<ArrayType>(BC->getType()), ConstOps); 152981ad6265SDimitry Andric break; 153081ad6265SDimitry Andric case BitcodeConstant::ConstantVectorOpcode: 153181ad6265SDimitry Andric C = ConstantVector::get(ConstOps); 153281ad6265SDimitry Andric break; 153381ad6265SDimitry Andric case Instruction::ICmp: 153481ad6265SDimitry Andric case Instruction::FCmp: 153581ad6265SDimitry Andric C = ConstantExpr::getCompare(BC->Flags, ConstOps[0], ConstOps[1]); 153681ad6265SDimitry Andric break; 153781ad6265SDimitry Andric case Instruction::GetElementPtr: 1538bdd1243dSDimitry Andric C = ConstantExpr::getGetElementPtr(BC->SrcElemTy, ConstOps[0], 1539bdd1243dSDimitry Andric ArrayRef(ConstOps).drop_front(), 154081ad6265SDimitry Andric BC->Flags, BC->getInRangeIndex()); 154181ad6265SDimitry Andric break; 154281ad6265SDimitry Andric case Instruction::ExtractElement: 154381ad6265SDimitry Andric C = ConstantExpr::getExtractElement(ConstOps[0], ConstOps[1]); 154481ad6265SDimitry Andric break; 154581ad6265SDimitry Andric case Instruction::InsertElement: 154681ad6265SDimitry Andric C = ConstantExpr::getInsertElement(ConstOps[0], ConstOps[1], 154781ad6265SDimitry Andric ConstOps[2]); 154881ad6265SDimitry Andric break; 154981ad6265SDimitry Andric case Instruction::ShuffleVector: { 155081ad6265SDimitry Andric SmallVector<int, 16> Mask; 155181ad6265SDimitry Andric ShuffleVectorInst::getShuffleMask(ConstOps[2], Mask); 155281ad6265SDimitry Andric C = ConstantExpr::getShuffleVector(ConstOps[0], ConstOps[1], Mask); 155381ad6265SDimitry Andric break; 155481ad6265SDimitry Andric } 155581ad6265SDimitry Andric default: 155681ad6265SDimitry Andric llvm_unreachable("Unhandled bitcode constant"); 155781ad6265SDimitry Andric } 155881ad6265SDimitry Andric } 155981ad6265SDimitry Andric 156081ad6265SDimitry Andric // Cache resolved constant. 156181ad6265SDimitry Andric ValueList.replaceValueWithoutRAUW(ValID, C); 156281ad6265SDimitry Andric MaterializedValues.insert({ValID, C}); 156381ad6265SDimitry Andric Worklist.pop_back(); 156481ad6265SDimitry Andric continue; 156581ad6265SDimitry Andric } 156681ad6265SDimitry Andric 156781ad6265SDimitry Andric if (!InsertBB) 156881ad6265SDimitry Andric return error(Twine("Value referenced by initializer is an unsupported " 156981ad6265SDimitry Andric "constant expression of type ") + 157081ad6265SDimitry Andric BC->getOpcodeName()); 157181ad6265SDimitry Andric 157281ad6265SDimitry Andric // Materialize as instructions if necessary. 157381ad6265SDimitry Andric Instruction *I; 157481ad6265SDimitry Andric if (Instruction::isCast(BC->Opcode)) { 157581ad6265SDimitry Andric I = CastInst::Create((Instruction::CastOps)BC->Opcode, Ops[0], 157681ad6265SDimitry Andric BC->getType(), "constexpr", InsertBB); 157781ad6265SDimitry Andric } else if (Instruction::isUnaryOp(BC->Opcode)) { 157881ad6265SDimitry Andric I = UnaryOperator::Create((Instruction::UnaryOps)BC->Opcode, Ops[0], 157981ad6265SDimitry Andric "constexpr", InsertBB); 158081ad6265SDimitry Andric } else if (Instruction::isBinaryOp(BC->Opcode)) { 158181ad6265SDimitry Andric I = BinaryOperator::Create((Instruction::BinaryOps)BC->Opcode, Ops[0], 158281ad6265SDimitry Andric Ops[1], "constexpr", InsertBB); 158381ad6265SDimitry Andric if (isa<OverflowingBinaryOperator>(I)) { 158481ad6265SDimitry Andric if (BC->Flags & OverflowingBinaryOperator::NoSignedWrap) 158581ad6265SDimitry Andric I->setHasNoSignedWrap(); 158681ad6265SDimitry Andric if (BC->Flags & OverflowingBinaryOperator::NoUnsignedWrap) 158781ad6265SDimitry Andric I->setHasNoUnsignedWrap(); 158881ad6265SDimitry Andric } 158981ad6265SDimitry Andric if (isa<PossiblyExactOperator>(I) && 159081ad6265SDimitry Andric (BC->Flags & PossiblyExactOperator::IsExact)) 159181ad6265SDimitry Andric I->setIsExact(); 159281ad6265SDimitry Andric } else { 159381ad6265SDimitry Andric switch (BC->Opcode) { 159481ad6265SDimitry Andric case BitcodeConstant::ConstantVectorOpcode: { 159581ad6265SDimitry Andric Type *IdxTy = Type::getInt32Ty(BC->getContext()); 159681ad6265SDimitry Andric Value *V = PoisonValue::get(BC->getType()); 159781ad6265SDimitry Andric for (auto Pair : enumerate(Ops)) { 159881ad6265SDimitry Andric Value *Idx = ConstantInt::get(IdxTy, Pair.index()); 159981ad6265SDimitry Andric V = InsertElementInst::Create(V, Pair.value(), Idx, "constexpr.ins", 160081ad6265SDimitry Andric InsertBB); 160181ad6265SDimitry Andric } 160281ad6265SDimitry Andric I = cast<Instruction>(V); 160381ad6265SDimitry Andric break; 160481ad6265SDimitry Andric } 1605bdd1243dSDimitry Andric case BitcodeConstant::ConstantStructOpcode: 1606bdd1243dSDimitry Andric case BitcodeConstant::ConstantArrayOpcode: { 1607bdd1243dSDimitry Andric Value *V = PoisonValue::get(BC->getType()); 1608bdd1243dSDimitry Andric for (auto Pair : enumerate(Ops)) 1609bdd1243dSDimitry Andric V = InsertValueInst::Create(V, Pair.value(), Pair.index(), 1610bdd1243dSDimitry Andric "constexpr.ins", InsertBB); 1611bdd1243dSDimitry Andric I = cast<Instruction>(V); 1612bdd1243dSDimitry Andric break; 1613bdd1243dSDimitry Andric } 161481ad6265SDimitry Andric case Instruction::ICmp: 161581ad6265SDimitry Andric case Instruction::FCmp: 161681ad6265SDimitry Andric I = CmpInst::Create((Instruction::OtherOps)BC->Opcode, 161781ad6265SDimitry Andric (CmpInst::Predicate)BC->Flags, Ops[0], Ops[1], 161881ad6265SDimitry Andric "constexpr", InsertBB); 161981ad6265SDimitry Andric break; 162081ad6265SDimitry Andric case Instruction::GetElementPtr: 162181ad6265SDimitry Andric I = GetElementPtrInst::Create(BC->SrcElemTy, Ops[0], 1622bdd1243dSDimitry Andric ArrayRef(Ops).drop_front(), "constexpr", 1623bdd1243dSDimitry Andric InsertBB); 162481ad6265SDimitry Andric if (BC->Flags) 162581ad6265SDimitry Andric cast<GetElementPtrInst>(I)->setIsInBounds(); 162681ad6265SDimitry Andric break; 162781ad6265SDimitry Andric case Instruction::Select: 162881ad6265SDimitry Andric I = SelectInst::Create(Ops[0], Ops[1], Ops[2], "constexpr", InsertBB); 162981ad6265SDimitry Andric break; 163081ad6265SDimitry Andric case Instruction::ExtractElement: 163181ad6265SDimitry Andric I = ExtractElementInst::Create(Ops[0], Ops[1], "constexpr", InsertBB); 163281ad6265SDimitry Andric break; 163381ad6265SDimitry Andric case Instruction::InsertElement: 163481ad6265SDimitry Andric I = InsertElementInst::Create(Ops[0], Ops[1], Ops[2], "constexpr", 163581ad6265SDimitry Andric InsertBB); 163681ad6265SDimitry Andric break; 163781ad6265SDimitry Andric case Instruction::ShuffleVector: 163881ad6265SDimitry Andric I = new ShuffleVectorInst(Ops[0], Ops[1], Ops[2], "constexpr", 163981ad6265SDimitry Andric InsertBB); 164081ad6265SDimitry Andric break; 164181ad6265SDimitry Andric default: 164281ad6265SDimitry Andric llvm_unreachable("Unhandled bitcode constant"); 164381ad6265SDimitry Andric } 164481ad6265SDimitry Andric } 164581ad6265SDimitry Andric 164681ad6265SDimitry Andric MaterializedValues.insert({ValID, I}); 164781ad6265SDimitry Andric Worklist.pop_back(); 164881ad6265SDimitry Andric } 164981ad6265SDimitry Andric 165081ad6265SDimitry Andric return MaterializedValues[StartValID]; 165181ad6265SDimitry Andric } 165281ad6265SDimitry Andric 165381ad6265SDimitry Andric Expected<Constant *> BitcodeReader::getValueForInitializer(unsigned ID) { 165481ad6265SDimitry Andric Expected<Value *> MaybeV = materializeValue(ID, /* InsertBB */ nullptr); 165581ad6265SDimitry Andric if (!MaybeV) 165681ad6265SDimitry Andric return MaybeV.takeError(); 165781ad6265SDimitry Andric 165881ad6265SDimitry Andric // Result must be Constant if InsertBB is nullptr. 165981ad6265SDimitry Andric return cast<Constant>(MaybeV.get()); 166081ad6265SDimitry Andric } 166181ad6265SDimitry Andric 16620b57cec5SDimitry Andric StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context, 16630b57cec5SDimitry Andric StringRef Name) { 16640b57cec5SDimitry Andric auto *Ret = StructType::create(Context, Name); 16650b57cec5SDimitry Andric IdentifiedStructTypes.push_back(Ret); 16660b57cec5SDimitry Andric return Ret; 16670b57cec5SDimitry Andric } 16680b57cec5SDimitry Andric 16690b57cec5SDimitry Andric StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context) { 16700b57cec5SDimitry Andric auto *Ret = StructType::create(Context); 16710b57cec5SDimitry Andric IdentifiedStructTypes.push_back(Ret); 16720b57cec5SDimitry Andric return Ret; 16730b57cec5SDimitry Andric } 16740b57cec5SDimitry Andric 16750b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 16760b57cec5SDimitry Andric // Functions for parsing blocks from the bitcode file 16770b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 16780b57cec5SDimitry Andric 16790b57cec5SDimitry Andric static uint64_t getRawAttributeMask(Attribute::AttrKind Val) { 16800b57cec5SDimitry Andric switch (Val) { 16810b57cec5SDimitry Andric case Attribute::EndAttrKinds: 16825ffd83dbSDimitry Andric case Attribute::EmptyKey: 16835ffd83dbSDimitry Andric case Attribute::TombstoneKey: 16840b57cec5SDimitry Andric llvm_unreachable("Synthetic enumerators which should never get here"); 16850b57cec5SDimitry Andric 16860b57cec5SDimitry Andric case Attribute::None: return 0; 16870b57cec5SDimitry Andric case Attribute::ZExt: return 1 << 0; 16880b57cec5SDimitry Andric case Attribute::SExt: return 1 << 1; 16890b57cec5SDimitry Andric case Attribute::NoReturn: return 1 << 2; 16900b57cec5SDimitry Andric case Attribute::InReg: return 1 << 3; 16910b57cec5SDimitry Andric case Attribute::StructRet: return 1 << 4; 16920b57cec5SDimitry Andric case Attribute::NoUnwind: return 1 << 5; 16930b57cec5SDimitry Andric case Attribute::NoAlias: return 1 << 6; 16940b57cec5SDimitry Andric case Attribute::ByVal: return 1 << 7; 16950b57cec5SDimitry Andric case Attribute::Nest: return 1 << 8; 16960b57cec5SDimitry Andric case Attribute::ReadNone: return 1 << 9; 16970b57cec5SDimitry Andric case Attribute::ReadOnly: return 1 << 10; 16980b57cec5SDimitry Andric case Attribute::NoInline: return 1 << 11; 16990b57cec5SDimitry Andric case Attribute::AlwaysInline: return 1 << 12; 17000b57cec5SDimitry Andric case Attribute::OptimizeForSize: return 1 << 13; 17010b57cec5SDimitry Andric case Attribute::StackProtect: return 1 << 14; 17020b57cec5SDimitry Andric case Attribute::StackProtectReq: return 1 << 15; 17030b57cec5SDimitry Andric case Attribute::Alignment: return 31 << 16; 17040b57cec5SDimitry Andric case Attribute::NoCapture: return 1 << 21; 17050b57cec5SDimitry Andric case Attribute::NoRedZone: return 1 << 22; 17060b57cec5SDimitry Andric case Attribute::NoImplicitFloat: return 1 << 23; 17070b57cec5SDimitry Andric case Attribute::Naked: return 1 << 24; 17080b57cec5SDimitry Andric case Attribute::InlineHint: return 1 << 25; 17090b57cec5SDimitry Andric case Attribute::StackAlignment: return 7 << 26; 17100b57cec5SDimitry Andric case Attribute::ReturnsTwice: return 1 << 29; 17110b57cec5SDimitry Andric case Attribute::UWTable: return 1 << 30; 17120b57cec5SDimitry Andric case Attribute::NonLazyBind: return 1U << 31; 17130b57cec5SDimitry Andric case Attribute::SanitizeAddress: return 1ULL << 32; 17140b57cec5SDimitry Andric case Attribute::MinSize: return 1ULL << 33; 17150b57cec5SDimitry Andric case Attribute::NoDuplicate: return 1ULL << 34; 17160b57cec5SDimitry Andric case Attribute::StackProtectStrong: return 1ULL << 35; 17170b57cec5SDimitry Andric case Attribute::SanitizeThread: return 1ULL << 36; 17180b57cec5SDimitry Andric case Attribute::SanitizeMemory: return 1ULL << 37; 17190b57cec5SDimitry Andric case Attribute::NoBuiltin: return 1ULL << 38; 17200b57cec5SDimitry Andric case Attribute::Returned: return 1ULL << 39; 17210b57cec5SDimitry Andric case Attribute::Cold: return 1ULL << 40; 17220b57cec5SDimitry Andric case Attribute::Builtin: return 1ULL << 41; 17230b57cec5SDimitry Andric case Attribute::OptimizeNone: return 1ULL << 42; 17240b57cec5SDimitry Andric case Attribute::InAlloca: return 1ULL << 43; 17250b57cec5SDimitry Andric case Attribute::NonNull: return 1ULL << 44; 17260b57cec5SDimitry Andric case Attribute::JumpTable: return 1ULL << 45; 17270b57cec5SDimitry Andric case Attribute::Convergent: return 1ULL << 46; 17280b57cec5SDimitry Andric case Attribute::SafeStack: return 1ULL << 47; 17290b57cec5SDimitry Andric case Attribute::NoRecurse: return 1ULL << 48; 1730bdd1243dSDimitry Andric // 1ULL << 49 is InaccessibleMemOnly, which is upgraded separately. 1731bdd1243dSDimitry Andric // 1ULL << 50 is InaccessibleMemOrArgMemOnly, which is upgraded separately. 17320b57cec5SDimitry Andric case Attribute::SwiftSelf: return 1ULL << 51; 17330b57cec5SDimitry Andric case Attribute::SwiftError: return 1ULL << 52; 17340b57cec5SDimitry Andric case Attribute::WriteOnly: return 1ULL << 53; 17350b57cec5SDimitry Andric case Attribute::Speculatable: return 1ULL << 54; 17360b57cec5SDimitry Andric case Attribute::StrictFP: return 1ULL << 55; 17370b57cec5SDimitry Andric case Attribute::SanitizeHWAddress: return 1ULL << 56; 17380b57cec5SDimitry Andric case Attribute::NoCfCheck: return 1ULL << 57; 17390b57cec5SDimitry Andric case Attribute::OptForFuzzing: return 1ULL << 58; 17400b57cec5SDimitry Andric case Attribute::ShadowCallStack: return 1ULL << 59; 17410b57cec5SDimitry Andric case Attribute::SpeculativeLoadHardening: 17420b57cec5SDimitry Andric return 1ULL << 60; 17430b57cec5SDimitry Andric case Attribute::ImmArg: 17440b57cec5SDimitry Andric return 1ULL << 61; 17450b57cec5SDimitry Andric case Attribute::WillReturn: 17460b57cec5SDimitry Andric return 1ULL << 62; 17470b57cec5SDimitry Andric case Attribute::NoFree: 17480b57cec5SDimitry Andric return 1ULL << 63; 17495ffd83dbSDimitry Andric default: 17505ffd83dbSDimitry Andric // Other attributes are not supported in the raw format, 17515ffd83dbSDimitry Andric // as we ran out of space. 17525ffd83dbSDimitry Andric return 0; 17530b57cec5SDimitry Andric } 17540b57cec5SDimitry Andric llvm_unreachable("Unsupported attribute type"); 17550b57cec5SDimitry Andric } 17560b57cec5SDimitry Andric 17570b57cec5SDimitry Andric static void addRawAttributeValue(AttrBuilder &B, uint64_t Val) { 17580b57cec5SDimitry Andric if (!Val) return; 17590b57cec5SDimitry Andric 17600b57cec5SDimitry Andric for (Attribute::AttrKind I = Attribute::None; I != Attribute::EndAttrKinds; 17610b57cec5SDimitry Andric I = Attribute::AttrKind(I + 1)) { 17620b57cec5SDimitry Andric if (uint64_t A = (Val & getRawAttributeMask(I))) { 17630b57cec5SDimitry Andric if (I == Attribute::Alignment) 17640b57cec5SDimitry Andric B.addAlignmentAttr(1ULL << ((A >> 16) - 1)); 17650b57cec5SDimitry Andric else if (I == Attribute::StackAlignment) 17660b57cec5SDimitry Andric B.addStackAlignmentAttr(1ULL << ((A >> 26)-1)); 1767fe6060f1SDimitry Andric else if (Attribute::isTypeAttrKind(I)) 1768fe6060f1SDimitry Andric B.addTypeAttr(I, nullptr); // Type will be auto-upgraded. 17690b57cec5SDimitry Andric else 17700b57cec5SDimitry Andric B.addAttribute(I); 17710b57cec5SDimitry Andric } 17720b57cec5SDimitry Andric } 17730b57cec5SDimitry Andric } 17740b57cec5SDimitry Andric 17750b57cec5SDimitry Andric /// This fills an AttrBuilder object with the LLVM attributes that have 17760b57cec5SDimitry Andric /// been decoded from the given integer. This function must stay in sync with 17770b57cec5SDimitry Andric /// 'encodeLLVMAttributesForBitcode'. 17780b57cec5SDimitry Andric static void decodeLLVMAttributesForBitcode(AttrBuilder &B, 1779bdd1243dSDimitry Andric uint64_t EncodedAttrs, 1780bdd1243dSDimitry Andric uint64_t AttrIdx) { 17810b57cec5SDimitry Andric // The alignment is stored as a 16-bit raw value from bits 31--16. We shift 17820b57cec5SDimitry Andric // the bits above 31 down by 11 bits. 17830b57cec5SDimitry Andric unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16; 17840b57cec5SDimitry Andric assert((!Alignment || isPowerOf2_32(Alignment)) && 17850b57cec5SDimitry Andric "Alignment must be a power of two."); 17860b57cec5SDimitry Andric 17870b57cec5SDimitry Andric if (Alignment) 17880b57cec5SDimitry Andric B.addAlignmentAttr(Alignment); 1789bdd1243dSDimitry Andric 1790bdd1243dSDimitry Andric uint64_t Attrs = ((EncodedAttrs & (0xfffffULL << 32)) >> 11) | 1791bdd1243dSDimitry Andric (EncodedAttrs & 0xffff); 1792bdd1243dSDimitry Andric 1793bdd1243dSDimitry Andric if (AttrIdx == AttributeList::FunctionIndex) { 1794bdd1243dSDimitry Andric // Upgrade old memory attributes. 1795bdd1243dSDimitry Andric MemoryEffects ME = MemoryEffects::unknown(); 1796bdd1243dSDimitry Andric if (Attrs & (1ULL << 9)) { 1797bdd1243dSDimitry Andric // ReadNone 1798bdd1243dSDimitry Andric Attrs &= ~(1ULL << 9); 1799bdd1243dSDimitry Andric ME &= MemoryEffects::none(); 1800bdd1243dSDimitry Andric } 1801bdd1243dSDimitry Andric if (Attrs & (1ULL << 10)) { 1802bdd1243dSDimitry Andric // ReadOnly 1803bdd1243dSDimitry Andric Attrs &= ~(1ULL << 10); 1804bdd1243dSDimitry Andric ME &= MemoryEffects::readOnly(); 1805bdd1243dSDimitry Andric } 1806bdd1243dSDimitry Andric if (Attrs & (1ULL << 49)) { 1807bdd1243dSDimitry Andric // InaccessibleMemOnly 1808bdd1243dSDimitry Andric Attrs &= ~(1ULL << 49); 1809bdd1243dSDimitry Andric ME &= MemoryEffects::inaccessibleMemOnly(); 1810bdd1243dSDimitry Andric } 1811bdd1243dSDimitry Andric if (Attrs & (1ULL << 50)) { 1812bdd1243dSDimitry Andric // InaccessibleMemOrArgMemOnly 1813bdd1243dSDimitry Andric Attrs &= ~(1ULL << 50); 1814bdd1243dSDimitry Andric ME &= MemoryEffects::inaccessibleOrArgMemOnly(); 1815bdd1243dSDimitry Andric } 1816bdd1243dSDimitry Andric if (Attrs & (1ULL << 53)) { 1817bdd1243dSDimitry Andric // WriteOnly 1818bdd1243dSDimitry Andric Attrs &= ~(1ULL << 53); 1819bdd1243dSDimitry Andric ME &= MemoryEffects::writeOnly(); 1820bdd1243dSDimitry Andric } 1821bdd1243dSDimitry Andric if (ME != MemoryEffects::unknown()) 1822bdd1243dSDimitry Andric B.addMemoryAttr(ME); 1823bdd1243dSDimitry Andric } 1824bdd1243dSDimitry Andric 1825bdd1243dSDimitry Andric addRawAttributeValue(B, Attrs); 18260b57cec5SDimitry Andric } 18270b57cec5SDimitry Andric 18280b57cec5SDimitry Andric Error BitcodeReader::parseAttributeBlock() { 18290b57cec5SDimitry Andric if (Error Err = Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID)) 18300b57cec5SDimitry Andric return Err; 18310b57cec5SDimitry Andric 18320b57cec5SDimitry Andric if (!MAttributes.empty()) 18330b57cec5SDimitry Andric return error("Invalid multiple blocks"); 18340b57cec5SDimitry Andric 18350b57cec5SDimitry Andric SmallVector<uint64_t, 64> Record; 18360b57cec5SDimitry Andric 18370b57cec5SDimitry Andric SmallVector<AttributeList, 8> Attrs; 18380b57cec5SDimitry Andric 18390b57cec5SDimitry Andric // Read all the records. 18400b57cec5SDimitry Andric while (true) { 18410b57cec5SDimitry Andric Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); 18420b57cec5SDimitry Andric if (!MaybeEntry) 18430b57cec5SDimitry Andric return MaybeEntry.takeError(); 18440b57cec5SDimitry Andric BitstreamEntry Entry = MaybeEntry.get(); 18450b57cec5SDimitry Andric 18460b57cec5SDimitry Andric switch (Entry.Kind) { 18470b57cec5SDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already. 18480b57cec5SDimitry Andric case BitstreamEntry::Error: 18490b57cec5SDimitry Andric return error("Malformed block"); 18500b57cec5SDimitry Andric case BitstreamEntry::EndBlock: 18510b57cec5SDimitry Andric return Error::success(); 18520b57cec5SDimitry Andric case BitstreamEntry::Record: 18530b57cec5SDimitry Andric // The interesting case. 18540b57cec5SDimitry Andric break; 18550b57cec5SDimitry Andric } 18560b57cec5SDimitry Andric 18570b57cec5SDimitry Andric // Read a record. 18580b57cec5SDimitry Andric Record.clear(); 18590b57cec5SDimitry Andric Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record); 18600b57cec5SDimitry Andric if (!MaybeRecord) 18610b57cec5SDimitry Andric return MaybeRecord.takeError(); 18620b57cec5SDimitry Andric switch (MaybeRecord.get()) { 18630b57cec5SDimitry Andric default: // Default behavior: ignore. 18640b57cec5SDimitry Andric break; 18650b57cec5SDimitry Andric case bitc::PARAMATTR_CODE_ENTRY_OLD: // ENTRY: [paramidx0, attr0, ...] 18665ffd83dbSDimitry Andric // Deprecated, but still needed to read old bitcode files. 18670b57cec5SDimitry Andric if (Record.size() & 1) 186881ad6265SDimitry Andric return error("Invalid parameter attribute record"); 18690b57cec5SDimitry Andric 18700b57cec5SDimitry Andric for (unsigned i = 0, e = Record.size(); i != e; i += 2) { 187104eeddc0SDimitry Andric AttrBuilder B(Context); 1872bdd1243dSDimitry Andric decodeLLVMAttributesForBitcode(B, Record[i+1], Record[i]); 18730b57cec5SDimitry Andric Attrs.push_back(AttributeList::get(Context, Record[i], B)); 18740b57cec5SDimitry Andric } 18750b57cec5SDimitry Andric 18760b57cec5SDimitry Andric MAttributes.push_back(AttributeList::get(Context, Attrs)); 18770b57cec5SDimitry Andric Attrs.clear(); 18780b57cec5SDimitry Andric break; 18790b57cec5SDimitry Andric case bitc::PARAMATTR_CODE_ENTRY: // ENTRY: [attrgrp0, attrgrp1, ...] 18800b57cec5SDimitry Andric for (unsigned i = 0, e = Record.size(); i != e; ++i) 18810b57cec5SDimitry Andric Attrs.push_back(MAttributeGroups[Record[i]]); 18820b57cec5SDimitry Andric 18830b57cec5SDimitry Andric MAttributes.push_back(AttributeList::get(Context, Attrs)); 18840b57cec5SDimitry Andric Attrs.clear(); 18850b57cec5SDimitry Andric break; 18860b57cec5SDimitry Andric } 18870b57cec5SDimitry Andric } 18880b57cec5SDimitry Andric } 18890b57cec5SDimitry Andric 18900b57cec5SDimitry Andric // Returns Attribute::None on unrecognized codes. 18910b57cec5SDimitry Andric static Attribute::AttrKind getAttrFromCode(uint64_t Code) { 18920b57cec5SDimitry Andric switch (Code) { 18930b57cec5SDimitry Andric default: 18940b57cec5SDimitry Andric return Attribute::None; 18950b57cec5SDimitry Andric case bitc::ATTR_KIND_ALIGNMENT: 18960b57cec5SDimitry Andric return Attribute::Alignment; 18970b57cec5SDimitry Andric case bitc::ATTR_KIND_ALWAYS_INLINE: 18980b57cec5SDimitry Andric return Attribute::AlwaysInline; 18990b57cec5SDimitry Andric case bitc::ATTR_KIND_BUILTIN: 19000b57cec5SDimitry Andric return Attribute::Builtin; 19010b57cec5SDimitry Andric case bitc::ATTR_KIND_BY_VAL: 19020b57cec5SDimitry Andric return Attribute::ByVal; 19030b57cec5SDimitry Andric case bitc::ATTR_KIND_IN_ALLOCA: 19040b57cec5SDimitry Andric return Attribute::InAlloca; 19050b57cec5SDimitry Andric case bitc::ATTR_KIND_COLD: 19060b57cec5SDimitry Andric return Attribute::Cold; 19070b57cec5SDimitry Andric case bitc::ATTR_KIND_CONVERGENT: 19080b57cec5SDimitry Andric return Attribute::Convergent; 1909349cc55cSDimitry Andric case bitc::ATTR_KIND_DISABLE_SANITIZER_INSTRUMENTATION: 1910349cc55cSDimitry Andric return Attribute::DisableSanitizerInstrumentation; 1911fe6060f1SDimitry Andric case bitc::ATTR_KIND_ELEMENTTYPE: 1912fe6060f1SDimitry Andric return Attribute::ElementType; 1913753f127fSDimitry Andric case bitc::ATTR_KIND_FNRETTHUNK_EXTERN: 1914753f127fSDimitry Andric return Attribute::FnRetThunkExtern; 19150b57cec5SDimitry Andric case bitc::ATTR_KIND_INLINE_HINT: 19160b57cec5SDimitry Andric return Attribute::InlineHint; 19170b57cec5SDimitry Andric case bitc::ATTR_KIND_IN_REG: 19180b57cec5SDimitry Andric return Attribute::InReg; 19190b57cec5SDimitry Andric case bitc::ATTR_KIND_JUMP_TABLE: 19200b57cec5SDimitry Andric return Attribute::JumpTable; 1921bdd1243dSDimitry Andric case bitc::ATTR_KIND_MEMORY: 1922bdd1243dSDimitry Andric return Attribute::Memory; 1923*fe013be4SDimitry Andric case bitc::ATTR_KIND_NOFPCLASS: 1924*fe013be4SDimitry Andric return Attribute::NoFPClass; 19250b57cec5SDimitry Andric case bitc::ATTR_KIND_MIN_SIZE: 19260b57cec5SDimitry Andric return Attribute::MinSize; 19270b57cec5SDimitry Andric case bitc::ATTR_KIND_NAKED: 19280b57cec5SDimitry Andric return Attribute::Naked; 19290b57cec5SDimitry Andric case bitc::ATTR_KIND_NEST: 19300b57cec5SDimitry Andric return Attribute::Nest; 19310b57cec5SDimitry Andric case bitc::ATTR_KIND_NO_ALIAS: 19320b57cec5SDimitry Andric return Attribute::NoAlias; 19330b57cec5SDimitry Andric case bitc::ATTR_KIND_NO_BUILTIN: 19340b57cec5SDimitry Andric return Attribute::NoBuiltin; 1935e8d8bef9SDimitry Andric case bitc::ATTR_KIND_NO_CALLBACK: 1936e8d8bef9SDimitry Andric return Attribute::NoCallback; 19370b57cec5SDimitry Andric case bitc::ATTR_KIND_NO_CAPTURE: 19380b57cec5SDimitry Andric return Attribute::NoCapture; 19390b57cec5SDimitry Andric case bitc::ATTR_KIND_NO_DUPLICATE: 19400b57cec5SDimitry Andric return Attribute::NoDuplicate; 19410b57cec5SDimitry Andric case bitc::ATTR_KIND_NOFREE: 19420b57cec5SDimitry Andric return Attribute::NoFree; 19430b57cec5SDimitry Andric case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT: 19440b57cec5SDimitry Andric return Attribute::NoImplicitFloat; 19450b57cec5SDimitry Andric case bitc::ATTR_KIND_NO_INLINE: 19460b57cec5SDimitry Andric return Attribute::NoInline; 19470b57cec5SDimitry Andric case bitc::ATTR_KIND_NO_RECURSE: 19480b57cec5SDimitry Andric return Attribute::NoRecurse; 19495ffd83dbSDimitry Andric case bitc::ATTR_KIND_NO_MERGE: 19505ffd83dbSDimitry Andric return Attribute::NoMerge; 19510b57cec5SDimitry Andric case bitc::ATTR_KIND_NON_LAZY_BIND: 19520b57cec5SDimitry Andric return Attribute::NonLazyBind; 19530b57cec5SDimitry Andric case bitc::ATTR_KIND_NON_NULL: 19540b57cec5SDimitry Andric return Attribute::NonNull; 19550b57cec5SDimitry Andric case bitc::ATTR_KIND_DEREFERENCEABLE: 19560b57cec5SDimitry Andric return Attribute::Dereferenceable; 19570b57cec5SDimitry Andric case bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL: 19580b57cec5SDimitry Andric return Attribute::DereferenceableOrNull; 195981ad6265SDimitry Andric case bitc::ATTR_KIND_ALLOC_ALIGN: 196081ad6265SDimitry Andric return Attribute::AllocAlign; 196181ad6265SDimitry Andric case bitc::ATTR_KIND_ALLOC_KIND: 196281ad6265SDimitry Andric return Attribute::AllocKind; 19630b57cec5SDimitry Andric case bitc::ATTR_KIND_ALLOC_SIZE: 19640b57cec5SDimitry Andric return Attribute::AllocSize; 196581ad6265SDimitry Andric case bitc::ATTR_KIND_ALLOCATED_POINTER: 196681ad6265SDimitry Andric return Attribute::AllocatedPointer; 19670b57cec5SDimitry Andric case bitc::ATTR_KIND_NO_RED_ZONE: 19680b57cec5SDimitry Andric return Attribute::NoRedZone; 19690b57cec5SDimitry Andric case bitc::ATTR_KIND_NO_RETURN: 19700b57cec5SDimitry Andric return Attribute::NoReturn; 19710b57cec5SDimitry Andric case bitc::ATTR_KIND_NOSYNC: 19720b57cec5SDimitry Andric return Attribute::NoSync; 19730b57cec5SDimitry Andric case bitc::ATTR_KIND_NOCF_CHECK: 19740b57cec5SDimitry Andric return Attribute::NoCfCheck; 1975fe6060f1SDimitry Andric case bitc::ATTR_KIND_NO_PROFILE: 1976fe6060f1SDimitry Andric return Attribute::NoProfile; 1977bdd1243dSDimitry Andric case bitc::ATTR_KIND_SKIP_PROFILE: 1978bdd1243dSDimitry Andric return Attribute::SkipProfile; 19790b57cec5SDimitry Andric case bitc::ATTR_KIND_NO_UNWIND: 19800b57cec5SDimitry Andric return Attribute::NoUnwind; 198181ad6265SDimitry Andric case bitc::ATTR_KIND_NO_SANITIZE_BOUNDS: 198281ad6265SDimitry Andric return Attribute::NoSanitizeBounds; 1983fe6060f1SDimitry Andric case bitc::ATTR_KIND_NO_SANITIZE_COVERAGE: 1984fe6060f1SDimitry Andric return Attribute::NoSanitizeCoverage; 19855ffd83dbSDimitry Andric case bitc::ATTR_KIND_NULL_POINTER_IS_VALID: 19865ffd83dbSDimitry Andric return Attribute::NullPointerIsValid; 19870b57cec5SDimitry Andric case bitc::ATTR_KIND_OPT_FOR_FUZZING: 19880b57cec5SDimitry Andric return Attribute::OptForFuzzing; 19890b57cec5SDimitry Andric case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE: 19900b57cec5SDimitry Andric return Attribute::OptimizeForSize; 19910b57cec5SDimitry Andric case bitc::ATTR_KIND_OPTIMIZE_NONE: 19920b57cec5SDimitry Andric return Attribute::OptimizeNone; 19930b57cec5SDimitry Andric case bitc::ATTR_KIND_READ_NONE: 19940b57cec5SDimitry Andric return Attribute::ReadNone; 19950b57cec5SDimitry Andric case bitc::ATTR_KIND_READ_ONLY: 19960b57cec5SDimitry Andric return Attribute::ReadOnly; 19970b57cec5SDimitry Andric case bitc::ATTR_KIND_RETURNED: 19980b57cec5SDimitry Andric return Attribute::Returned; 19990b57cec5SDimitry Andric case bitc::ATTR_KIND_RETURNS_TWICE: 20000b57cec5SDimitry Andric return Attribute::ReturnsTwice; 20010b57cec5SDimitry Andric case bitc::ATTR_KIND_S_EXT: 20020b57cec5SDimitry Andric return Attribute::SExt; 20030b57cec5SDimitry Andric case bitc::ATTR_KIND_SPECULATABLE: 20040b57cec5SDimitry Andric return Attribute::Speculatable; 20050b57cec5SDimitry Andric case bitc::ATTR_KIND_STACK_ALIGNMENT: 20060b57cec5SDimitry Andric return Attribute::StackAlignment; 20070b57cec5SDimitry Andric case bitc::ATTR_KIND_STACK_PROTECT: 20080b57cec5SDimitry Andric return Attribute::StackProtect; 20090b57cec5SDimitry Andric case bitc::ATTR_KIND_STACK_PROTECT_REQ: 20100b57cec5SDimitry Andric return Attribute::StackProtectReq; 20110b57cec5SDimitry Andric case bitc::ATTR_KIND_STACK_PROTECT_STRONG: 20120b57cec5SDimitry Andric return Attribute::StackProtectStrong; 20130b57cec5SDimitry Andric case bitc::ATTR_KIND_SAFESTACK: 20140b57cec5SDimitry Andric return Attribute::SafeStack; 20150b57cec5SDimitry Andric case bitc::ATTR_KIND_SHADOWCALLSTACK: 20160b57cec5SDimitry Andric return Attribute::ShadowCallStack; 20170b57cec5SDimitry Andric case bitc::ATTR_KIND_STRICT_FP: 20180b57cec5SDimitry Andric return Attribute::StrictFP; 20190b57cec5SDimitry Andric case bitc::ATTR_KIND_STRUCT_RET: 20200b57cec5SDimitry Andric return Attribute::StructRet; 20210b57cec5SDimitry Andric case bitc::ATTR_KIND_SANITIZE_ADDRESS: 20220b57cec5SDimitry Andric return Attribute::SanitizeAddress; 20230b57cec5SDimitry Andric case bitc::ATTR_KIND_SANITIZE_HWADDRESS: 20240b57cec5SDimitry Andric return Attribute::SanitizeHWAddress; 20250b57cec5SDimitry Andric case bitc::ATTR_KIND_SANITIZE_THREAD: 20260b57cec5SDimitry Andric return Attribute::SanitizeThread; 20270b57cec5SDimitry Andric case bitc::ATTR_KIND_SANITIZE_MEMORY: 20280b57cec5SDimitry Andric return Attribute::SanitizeMemory; 20290b57cec5SDimitry Andric case bitc::ATTR_KIND_SPECULATIVE_LOAD_HARDENING: 20300b57cec5SDimitry Andric return Attribute::SpeculativeLoadHardening; 20310b57cec5SDimitry Andric case bitc::ATTR_KIND_SWIFT_ERROR: 20320b57cec5SDimitry Andric return Attribute::SwiftError; 20330b57cec5SDimitry Andric case bitc::ATTR_KIND_SWIFT_SELF: 20340b57cec5SDimitry Andric return Attribute::SwiftSelf; 2035fe6060f1SDimitry Andric case bitc::ATTR_KIND_SWIFT_ASYNC: 2036fe6060f1SDimitry Andric return Attribute::SwiftAsync; 20370b57cec5SDimitry Andric case bitc::ATTR_KIND_UW_TABLE: 20380b57cec5SDimitry Andric return Attribute::UWTable; 2039fe6060f1SDimitry Andric case bitc::ATTR_KIND_VSCALE_RANGE: 2040fe6060f1SDimitry Andric return Attribute::VScaleRange; 20410b57cec5SDimitry Andric case bitc::ATTR_KIND_WILLRETURN: 20420b57cec5SDimitry Andric return Attribute::WillReturn; 20430b57cec5SDimitry Andric case bitc::ATTR_KIND_WRITEONLY: 20440b57cec5SDimitry Andric return Attribute::WriteOnly; 20450b57cec5SDimitry Andric case bitc::ATTR_KIND_Z_EXT: 20460b57cec5SDimitry Andric return Attribute::ZExt; 20470b57cec5SDimitry Andric case bitc::ATTR_KIND_IMMARG: 20480b57cec5SDimitry Andric return Attribute::ImmArg; 20490b57cec5SDimitry Andric case bitc::ATTR_KIND_SANITIZE_MEMTAG: 20500b57cec5SDimitry Andric return Attribute::SanitizeMemTag; 20515ffd83dbSDimitry Andric case bitc::ATTR_KIND_PREALLOCATED: 20525ffd83dbSDimitry Andric return Attribute::Preallocated; 20535ffd83dbSDimitry Andric case bitc::ATTR_KIND_NOUNDEF: 20545ffd83dbSDimitry Andric return Attribute::NoUndef; 2055e8d8bef9SDimitry Andric case bitc::ATTR_KIND_BYREF: 2056e8d8bef9SDimitry Andric return Attribute::ByRef; 2057e8d8bef9SDimitry Andric case bitc::ATTR_KIND_MUSTPROGRESS: 2058e8d8bef9SDimitry Andric return Attribute::MustProgress; 2059e8d8bef9SDimitry Andric case bitc::ATTR_KIND_HOT: 2060e8d8bef9SDimitry Andric return Attribute::Hot; 206181ad6265SDimitry Andric case bitc::ATTR_KIND_PRESPLIT_COROUTINE: 206281ad6265SDimitry Andric return Attribute::PresplitCoroutine; 20630b57cec5SDimitry Andric } 20640b57cec5SDimitry Andric } 20650b57cec5SDimitry Andric 20660b57cec5SDimitry Andric Error BitcodeReader::parseAlignmentValue(uint64_t Exponent, 20678bcb0991SDimitry Andric MaybeAlign &Alignment) { 20680b57cec5SDimitry Andric // Note: Alignment in bitcode files is incremented by 1, so that zero 20690b57cec5SDimitry Andric // can be used for default alignment. 20700b57cec5SDimitry Andric if (Exponent > Value::MaxAlignmentExponent + 1) 20710b57cec5SDimitry Andric return error("Invalid alignment value"); 20728bcb0991SDimitry Andric Alignment = decodeMaybeAlign(Exponent); 20730b57cec5SDimitry Andric return Error::success(); 20740b57cec5SDimitry Andric } 20750b57cec5SDimitry Andric 20760b57cec5SDimitry Andric Error BitcodeReader::parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind) { 20770b57cec5SDimitry Andric *Kind = getAttrFromCode(Code); 20780b57cec5SDimitry Andric if (*Kind == Attribute::None) 20790b57cec5SDimitry Andric return error("Unknown attribute kind (" + Twine(Code) + ")"); 20800b57cec5SDimitry Andric return Error::success(); 20810b57cec5SDimitry Andric } 20820b57cec5SDimitry Andric 2083bdd1243dSDimitry Andric static bool upgradeOldMemoryAttribute(MemoryEffects &ME, uint64_t EncodedKind) { 2084bdd1243dSDimitry Andric switch (EncodedKind) { 2085bdd1243dSDimitry Andric case bitc::ATTR_KIND_READ_NONE: 2086bdd1243dSDimitry Andric ME &= MemoryEffects::none(); 2087bdd1243dSDimitry Andric return true; 2088bdd1243dSDimitry Andric case bitc::ATTR_KIND_READ_ONLY: 2089bdd1243dSDimitry Andric ME &= MemoryEffects::readOnly(); 2090bdd1243dSDimitry Andric return true; 2091bdd1243dSDimitry Andric case bitc::ATTR_KIND_WRITEONLY: 2092bdd1243dSDimitry Andric ME &= MemoryEffects::writeOnly(); 2093bdd1243dSDimitry Andric return true; 2094bdd1243dSDimitry Andric case bitc::ATTR_KIND_ARGMEMONLY: 2095bdd1243dSDimitry Andric ME &= MemoryEffects::argMemOnly(); 2096bdd1243dSDimitry Andric return true; 2097bdd1243dSDimitry Andric case bitc::ATTR_KIND_INACCESSIBLEMEM_ONLY: 2098bdd1243dSDimitry Andric ME &= MemoryEffects::inaccessibleMemOnly(); 2099bdd1243dSDimitry Andric return true; 2100bdd1243dSDimitry Andric case bitc::ATTR_KIND_INACCESSIBLEMEM_OR_ARGMEMONLY: 2101bdd1243dSDimitry Andric ME &= MemoryEffects::inaccessibleOrArgMemOnly(); 2102bdd1243dSDimitry Andric return true; 2103bdd1243dSDimitry Andric default: 2104bdd1243dSDimitry Andric return false; 2105bdd1243dSDimitry Andric } 2106bdd1243dSDimitry Andric } 2107bdd1243dSDimitry Andric 21080b57cec5SDimitry Andric Error BitcodeReader::parseAttributeGroupBlock() { 21090b57cec5SDimitry Andric if (Error Err = Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID)) 21100b57cec5SDimitry Andric return Err; 21110b57cec5SDimitry Andric 21120b57cec5SDimitry Andric if (!MAttributeGroups.empty()) 21130b57cec5SDimitry Andric return error("Invalid multiple blocks"); 21140b57cec5SDimitry Andric 21150b57cec5SDimitry Andric SmallVector<uint64_t, 64> Record; 21160b57cec5SDimitry Andric 21170b57cec5SDimitry Andric // Read all the records. 21180b57cec5SDimitry Andric while (true) { 21190b57cec5SDimitry Andric Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); 21200b57cec5SDimitry Andric if (!MaybeEntry) 21210b57cec5SDimitry Andric return MaybeEntry.takeError(); 21220b57cec5SDimitry Andric BitstreamEntry Entry = MaybeEntry.get(); 21230b57cec5SDimitry Andric 21240b57cec5SDimitry Andric switch (Entry.Kind) { 21250b57cec5SDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already. 21260b57cec5SDimitry Andric case BitstreamEntry::Error: 21270b57cec5SDimitry Andric return error("Malformed block"); 21280b57cec5SDimitry Andric case BitstreamEntry::EndBlock: 21290b57cec5SDimitry Andric return Error::success(); 21300b57cec5SDimitry Andric case BitstreamEntry::Record: 21310b57cec5SDimitry Andric // The interesting case. 21320b57cec5SDimitry Andric break; 21330b57cec5SDimitry Andric } 21340b57cec5SDimitry Andric 21350b57cec5SDimitry Andric // Read a record. 21360b57cec5SDimitry Andric Record.clear(); 21370b57cec5SDimitry Andric Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record); 21380b57cec5SDimitry Andric if (!MaybeRecord) 21390b57cec5SDimitry Andric return MaybeRecord.takeError(); 21400b57cec5SDimitry Andric switch (MaybeRecord.get()) { 21410b57cec5SDimitry Andric default: // Default behavior: ignore. 21420b57cec5SDimitry Andric break; 21430b57cec5SDimitry Andric case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...] 21440b57cec5SDimitry Andric if (Record.size() < 3) 214581ad6265SDimitry Andric return error("Invalid grp record"); 21460b57cec5SDimitry Andric 21470b57cec5SDimitry Andric uint64_t GrpID = Record[0]; 21480b57cec5SDimitry Andric uint64_t Idx = Record[1]; // Index of the object this attribute refers to. 21490b57cec5SDimitry Andric 215004eeddc0SDimitry Andric AttrBuilder B(Context); 2151bdd1243dSDimitry Andric MemoryEffects ME = MemoryEffects::unknown(); 21520b57cec5SDimitry Andric for (unsigned i = 2, e = Record.size(); i != e; ++i) { 21530b57cec5SDimitry Andric if (Record[i] == 0) { // Enum attribute 21540b57cec5SDimitry Andric Attribute::AttrKind Kind; 2155bdd1243dSDimitry Andric uint64_t EncodedKind = Record[++i]; 2156bdd1243dSDimitry Andric if (Idx == AttributeList::FunctionIndex && 2157bdd1243dSDimitry Andric upgradeOldMemoryAttribute(ME, EncodedKind)) 2158bdd1243dSDimitry Andric continue; 2159bdd1243dSDimitry Andric 2160bdd1243dSDimitry Andric if (Error Err = parseAttrKind(EncodedKind, &Kind)) 21610b57cec5SDimitry Andric return Err; 21620b57cec5SDimitry Andric 21630b57cec5SDimitry Andric // Upgrade old-style byval attribute to one with a type, even if it's 21640b57cec5SDimitry Andric // nullptr. We will have to insert the real type when we associate 21650b57cec5SDimitry Andric // this AttributeList with a function. 21660b57cec5SDimitry Andric if (Kind == Attribute::ByVal) 21670b57cec5SDimitry Andric B.addByValAttr(nullptr); 2168e8d8bef9SDimitry Andric else if (Kind == Attribute::StructRet) 2169e8d8bef9SDimitry Andric B.addStructRetAttr(nullptr); 2170fe6060f1SDimitry Andric else if (Kind == Attribute::InAlloca) 2171fe6060f1SDimitry Andric B.addInAllocaAttr(nullptr); 217281ad6265SDimitry Andric else if (Kind == Attribute::UWTable) 217381ad6265SDimitry Andric B.addUWTableAttr(UWTableKind::Default); 2174fe6060f1SDimitry Andric else if (Attribute::isEnumAttrKind(Kind)) 21750b57cec5SDimitry Andric B.addAttribute(Kind); 2176fe6060f1SDimitry Andric else 2177fe6060f1SDimitry Andric return error("Not an enum attribute"); 21780b57cec5SDimitry Andric } else if (Record[i] == 1) { // Integer attribute 21790b57cec5SDimitry Andric Attribute::AttrKind Kind; 21800b57cec5SDimitry Andric if (Error Err = parseAttrKind(Record[++i], &Kind)) 21810b57cec5SDimitry Andric return Err; 2182fe6060f1SDimitry Andric if (!Attribute::isIntAttrKind(Kind)) 2183fe6060f1SDimitry Andric return error("Not an int attribute"); 21840b57cec5SDimitry Andric if (Kind == Attribute::Alignment) 21850b57cec5SDimitry Andric B.addAlignmentAttr(Record[++i]); 21860b57cec5SDimitry Andric else if (Kind == Attribute::StackAlignment) 21870b57cec5SDimitry Andric B.addStackAlignmentAttr(Record[++i]); 21880b57cec5SDimitry Andric else if (Kind == Attribute::Dereferenceable) 21890b57cec5SDimitry Andric B.addDereferenceableAttr(Record[++i]); 21900b57cec5SDimitry Andric else if (Kind == Attribute::DereferenceableOrNull) 21910b57cec5SDimitry Andric B.addDereferenceableOrNullAttr(Record[++i]); 21920b57cec5SDimitry Andric else if (Kind == Attribute::AllocSize) 21930b57cec5SDimitry Andric B.addAllocSizeAttrFromRawRepr(Record[++i]); 2194fe6060f1SDimitry Andric else if (Kind == Attribute::VScaleRange) 2195fe6060f1SDimitry Andric B.addVScaleRangeAttrFromRawRepr(Record[++i]); 219681ad6265SDimitry Andric else if (Kind == Attribute::UWTable) 219781ad6265SDimitry Andric B.addUWTableAttr(UWTableKind(Record[++i])); 219881ad6265SDimitry Andric else if (Kind == Attribute::AllocKind) 219981ad6265SDimitry Andric B.addAllocKindAttr(static_cast<AllocFnKind>(Record[++i])); 2200bdd1243dSDimitry Andric else if (Kind == Attribute::Memory) 2201bdd1243dSDimitry Andric B.addMemoryAttr(MemoryEffects::createFromIntValue(Record[++i])); 2202*fe013be4SDimitry Andric else if (Kind == Attribute::NoFPClass) 2203*fe013be4SDimitry Andric B.addNoFPClassAttr( 2204*fe013be4SDimitry Andric static_cast<FPClassTest>(Record[++i] & fcAllFlags)); 22050b57cec5SDimitry Andric } else if (Record[i] == 3 || Record[i] == 4) { // String attribute 22060b57cec5SDimitry Andric bool HasValue = (Record[i++] == 4); 22070b57cec5SDimitry Andric SmallString<64> KindStr; 22080b57cec5SDimitry Andric SmallString<64> ValStr; 22090b57cec5SDimitry Andric 22100b57cec5SDimitry Andric while (Record[i] != 0 && i != e) 22110b57cec5SDimitry Andric KindStr += Record[i++]; 22120b57cec5SDimitry Andric assert(Record[i] == 0 && "Kind string not null terminated"); 22130b57cec5SDimitry Andric 22140b57cec5SDimitry Andric if (HasValue) { 22150b57cec5SDimitry Andric // Has a value associated with it. 22160b57cec5SDimitry Andric ++i; // Skip the '0' that terminates the "kind" string. 22170b57cec5SDimitry Andric while (Record[i] != 0 && i != e) 22180b57cec5SDimitry Andric ValStr += Record[i++]; 22190b57cec5SDimitry Andric assert(Record[i] == 0 && "Value string not null terminated"); 22200b57cec5SDimitry Andric } 22210b57cec5SDimitry Andric 22220b57cec5SDimitry Andric B.addAttribute(KindStr.str(), ValStr.str()); 222381ad6265SDimitry Andric } else if (Record[i] == 5 || Record[i] == 6) { 22240b57cec5SDimitry Andric bool HasType = Record[i] == 6; 22250b57cec5SDimitry Andric Attribute::AttrKind Kind; 22260b57cec5SDimitry Andric if (Error Err = parseAttrKind(Record[++i], &Kind)) 22270b57cec5SDimitry Andric return Err; 2228fe6060f1SDimitry Andric if (!Attribute::isTypeAttrKind(Kind)) 2229fe6060f1SDimitry Andric return error("Not a type attribute"); 2230fe6060f1SDimitry Andric 2231fe6060f1SDimitry Andric B.addTypeAttr(Kind, HasType ? getTypeByID(Record[++i]) : nullptr); 223281ad6265SDimitry Andric } else { 223381ad6265SDimitry Andric return error("Invalid attribute group entry"); 22340b57cec5SDimitry Andric } 22350b57cec5SDimitry Andric } 22360b57cec5SDimitry Andric 2237bdd1243dSDimitry Andric if (ME != MemoryEffects::unknown()) 2238bdd1243dSDimitry Andric B.addMemoryAttr(ME); 2239bdd1243dSDimitry Andric 22405ffd83dbSDimitry Andric UpgradeAttributes(B); 22410b57cec5SDimitry Andric MAttributeGroups[GrpID] = AttributeList::get(Context, Idx, B); 22420b57cec5SDimitry Andric break; 22430b57cec5SDimitry Andric } 22440b57cec5SDimitry Andric } 22450b57cec5SDimitry Andric } 22460b57cec5SDimitry Andric } 22470b57cec5SDimitry Andric 22480b57cec5SDimitry Andric Error BitcodeReader::parseTypeTable() { 22490b57cec5SDimitry Andric if (Error Err = Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW)) 22500b57cec5SDimitry Andric return Err; 22510b57cec5SDimitry Andric 22520b57cec5SDimitry Andric return parseTypeTableBody(); 22530b57cec5SDimitry Andric } 22540b57cec5SDimitry Andric 22550b57cec5SDimitry Andric Error BitcodeReader::parseTypeTableBody() { 22560b57cec5SDimitry Andric if (!TypeList.empty()) 22570b57cec5SDimitry Andric return error("Invalid multiple blocks"); 22580b57cec5SDimitry Andric 22590b57cec5SDimitry Andric SmallVector<uint64_t, 64> Record; 22600b57cec5SDimitry Andric unsigned NumRecords = 0; 22610b57cec5SDimitry Andric 22620b57cec5SDimitry Andric SmallString<64> TypeName; 22630b57cec5SDimitry Andric 22640b57cec5SDimitry Andric // Read all the records for this type table. 22650b57cec5SDimitry Andric while (true) { 22660b57cec5SDimitry Andric Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); 22670b57cec5SDimitry Andric if (!MaybeEntry) 22680b57cec5SDimitry Andric return MaybeEntry.takeError(); 22690b57cec5SDimitry Andric BitstreamEntry Entry = MaybeEntry.get(); 22700b57cec5SDimitry Andric 22710b57cec5SDimitry Andric switch (Entry.Kind) { 22720b57cec5SDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already. 22730b57cec5SDimitry Andric case BitstreamEntry::Error: 22740b57cec5SDimitry Andric return error("Malformed block"); 22750b57cec5SDimitry Andric case BitstreamEntry::EndBlock: 22760b57cec5SDimitry Andric if (NumRecords != TypeList.size()) 22770b57cec5SDimitry Andric return error("Malformed block"); 22780b57cec5SDimitry Andric return Error::success(); 22790b57cec5SDimitry Andric case BitstreamEntry::Record: 22800b57cec5SDimitry Andric // The interesting case. 22810b57cec5SDimitry Andric break; 22820b57cec5SDimitry Andric } 22830b57cec5SDimitry Andric 22840b57cec5SDimitry Andric // Read a record. 22850b57cec5SDimitry Andric Record.clear(); 22860b57cec5SDimitry Andric Type *ResultTy = nullptr; 228781ad6265SDimitry Andric SmallVector<unsigned> ContainedIDs; 22880b57cec5SDimitry Andric Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record); 22890b57cec5SDimitry Andric if (!MaybeRecord) 22900b57cec5SDimitry Andric return MaybeRecord.takeError(); 22910b57cec5SDimitry Andric switch (MaybeRecord.get()) { 22920b57cec5SDimitry Andric default: 22930b57cec5SDimitry Andric return error("Invalid value"); 22940b57cec5SDimitry Andric case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries] 22950b57cec5SDimitry Andric // TYPE_CODE_NUMENTRY contains a count of the number of types in the 22960b57cec5SDimitry Andric // type list. This allows us to reserve space. 2297e8d8bef9SDimitry Andric if (Record.empty()) 229881ad6265SDimitry Andric return error("Invalid numentry record"); 22990b57cec5SDimitry Andric TypeList.resize(Record[0]); 23000b57cec5SDimitry Andric continue; 23010b57cec5SDimitry Andric case bitc::TYPE_CODE_VOID: // VOID 23020b57cec5SDimitry Andric ResultTy = Type::getVoidTy(Context); 23030b57cec5SDimitry Andric break; 23040b57cec5SDimitry Andric case bitc::TYPE_CODE_HALF: // HALF 23050b57cec5SDimitry Andric ResultTy = Type::getHalfTy(Context); 23060b57cec5SDimitry Andric break; 23075ffd83dbSDimitry Andric case bitc::TYPE_CODE_BFLOAT: // BFLOAT 23085ffd83dbSDimitry Andric ResultTy = Type::getBFloatTy(Context); 23095ffd83dbSDimitry Andric break; 23100b57cec5SDimitry Andric case bitc::TYPE_CODE_FLOAT: // FLOAT 23110b57cec5SDimitry Andric ResultTy = Type::getFloatTy(Context); 23120b57cec5SDimitry Andric break; 23130b57cec5SDimitry Andric case bitc::TYPE_CODE_DOUBLE: // DOUBLE 23140b57cec5SDimitry Andric ResultTy = Type::getDoubleTy(Context); 23150b57cec5SDimitry Andric break; 23160b57cec5SDimitry Andric case bitc::TYPE_CODE_X86_FP80: // X86_FP80 23170b57cec5SDimitry Andric ResultTy = Type::getX86_FP80Ty(Context); 23180b57cec5SDimitry Andric break; 23190b57cec5SDimitry Andric case bitc::TYPE_CODE_FP128: // FP128 23200b57cec5SDimitry Andric ResultTy = Type::getFP128Ty(Context); 23210b57cec5SDimitry Andric break; 23220b57cec5SDimitry Andric case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128 23230b57cec5SDimitry Andric ResultTy = Type::getPPC_FP128Ty(Context); 23240b57cec5SDimitry Andric break; 23250b57cec5SDimitry Andric case bitc::TYPE_CODE_LABEL: // LABEL 23260b57cec5SDimitry Andric ResultTy = Type::getLabelTy(Context); 23270b57cec5SDimitry Andric break; 23280b57cec5SDimitry Andric case bitc::TYPE_CODE_METADATA: // METADATA 23290b57cec5SDimitry Andric ResultTy = Type::getMetadataTy(Context); 23300b57cec5SDimitry Andric break; 23310b57cec5SDimitry Andric case bitc::TYPE_CODE_X86_MMX: // X86_MMX 23320b57cec5SDimitry Andric ResultTy = Type::getX86_MMXTy(Context); 23330b57cec5SDimitry Andric break; 2334e8d8bef9SDimitry Andric case bitc::TYPE_CODE_X86_AMX: // X86_AMX 2335e8d8bef9SDimitry Andric ResultTy = Type::getX86_AMXTy(Context); 2336e8d8bef9SDimitry Andric break; 23370b57cec5SDimitry Andric case bitc::TYPE_CODE_TOKEN: // TOKEN 23380b57cec5SDimitry Andric ResultTy = Type::getTokenTy(Context); 23390b57cec5SDimitry Andric break; 23400b57cec5SDimitry Andric case bitc::TYPE_CODE_INTEGER: { // INTEGER: [width] 2341e8d8bef9SDimitry Andric if (Record.empty()) 234281ad6265SDimitry Andric return error("Invalid integer record"); 23430b57cec5SDimitry Andric 23440b57cec5SDimitry Andric uint64_t NumBits = Record[0]; 23450b57cec5SDimitry Andric if (NumBits < IntegerType::MIN_INT_BITS || 23460b57cec5SDimitry Andric NumBits > IntegerType::MAX_INT_BITS) 23470b57cec5SDimitry Andric return error("Bitwidth for integer type out of range"); 23480b57cec5SDimitry Andric ResultTy = IntegerType::get(Context, NumBits); 23490b57cec5SDimitry Andric break; 23500b57cec5SDimitry Andric } 23510b57cec5SDimitry Andric case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or 23520b57cec5SDimitry Andric // [pointee type, address space] 2353e8d8bef9SDimitry Andric if (Record.empty()) 235481ad6265SDimitry Andric return error("Invalid pointer record"); 23550b57cec5SDimitry Andric unsigned AddressSpace = 0; 23560b57cec5SDimitry Andric if (Record.size() == 2) 23570b57cec5SDimitry Andric AddressSpace = Record[1]; 23580b57cec5SDimitry Andric ResultTy = getTypeByID(Record[0]); 23590b57cec5SDimitry Andric if (!ResultTy || 23600b57cec5SDimitry Andric !PointerType::isValidElementType(ResultTy)) 23610b57cec5SDimitry Andric return error("Invalid type"); 236281ad6265SDimitry Andric ContainedIDs.push_back(Record[0]); 23630b57cec5SDimitry Andric ResultTy = PointerType::get(ResultTy, AddressSpace); 23640b57cec5SDimitry Andric break; 23650b57cec5SDimitry Andric } 2366fe6060f1SDimitry Andric case bitc::TYPE_CODE_OPAQUE_POINTER: { // OPAQUE_POINTER: [addrspace] 2367fe6060f1SDimitry Andric if (Record.size() != 1) 236881ad6265SDimitry Andric return error("Invalid opaque pointer record"); 2369fe6060f1SDimitry Andric unsigned AddressSpace = Record[0]; 2370fe6060f1SDimitry Andric ResultTy = PointerType::get(Context, AddressSpace); 2371fe6060f1SDimitry Andric break; 2372fe6060f1SDimitry Andric } 23730b57cec5SDimitry Andric case bitc::TYPE_CODE_FUNCTION_OLD: { 23745ffd83dbSDimitry Andric // Deprecated, but still needed to read old bitcode files. 23750b57cec5SDimitry Andric // FUNCTION: [vararg, attrid, retty, paramty x N] 23760b57cec5SDimitry Andric if (Record.size() < 3) 237781ad6265SDimitry Andric return error("Invalid function record"); 23780b57cec5SDimitry Andric SmallVector<Type*, 8> ArgTys; 23790b57cec5SDimitry Andric for (unsigned i = 3, e = Record.size(); i != e; ++i) { 23800b57cec5SDimitry Andric if (Type *T = getTypeByID(Record[i])) 23810b57cec5SDimitry Andric ArgTys.push_back(T); 23820b57cec5SDimitry Andric else 23830b57cec5SDimitry Andric break; 23840b57cec5SDimitry Andric } 23850b57cec5SDimitry Andric 23860b57cec5SDimitry Andric ResultTy = getTypeByID(Record[2]); 23870b57cec5SDimitry Andric if (!ResultTy || ArgTys.size() < Record.size()-3) 23880b57cec5SDimitry Andric return error("Invalid type"); 23890b57cec5SDimitry Andric 239081ad6265SDimitry Andric ContainedIDs.append(Record.begin() + 2, Record.end()); 23910b57cec5SDimitry Andric ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]); 23920b57cec5SDimitry Andric break; 23930b57cec5SDimitry Andric } 23940b57cec5SDimitry Andric case bitc::TYPE_CODE_FUNCTION: { 23950b57cec5SDimitry Andric // FUNCTION: [vararg, retty, paramty x N] 23960b57cec5SDimitry Andric if (Record.size() < 2) 239781ad6265SDimitry Andric return error("Invalid function record"); 23980b57cec5SDimitry Andric SmallVector<Type*, 8> ArgTys; 23990b57cec5SDimitry Andric for (unsigned i = 2, e = Record.size(); i != e; ++i) { 24000b57cec5SDimitry Andric if (Type *T = getTypeByID(Record[i])) { 24010b57cec5SDimitry Andric if (!FunctionType::isValidArgumentType(T)) 24020b57cec5SDimitry Andric return error("Invalid function argument type"); 24030b57cec5SDimitry Andric ArgTys.push_back(T); 24040b57cec5SDimitry Andric } 24050b57cec5SDimitry Andric else 24060b57cec5SDimitry Andric break; 24070b57cec5SDimitry Andric } 24080b57cec5SDimitry Andric 24090b57cec5SDimitry Andric ResultTy = getTypeByID(Record[1]); 24100b57cec5SDimitry Andric if (!ResultTy || ArgTys.size() < Record.size()-2) 24110b57cec5SDimitry Andric return error("Invalid type"); 24120b57cec5SDimitry Andric 241381ad6265SDimitry Andric ContainedIDs.append(Record.begin() + 1, Record.end()); 24140b57cec5SDimitry Andric ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]); 24150b57cec5SDimitry Andric break; 24160b57cec5SDimitry Andric } 24170b57cec5SDimitry Andric case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N] 2418e8d8bef9SDimitry Andric if (Record.empty()) 241981ad6265SDimitry Andric return error("Invalid anon struct record"); 24200b57cec5SDimitry Andric SmallVector<Type*, 8> EltTys; 24210b57cec5SDimitry Andric for (unsigned i = 1, e = Record.size(); i != e; ++i) { 24220b57cec5SDimitry Andric if (Type *T = getTypeByID(Record[i])) 24230b57cec5SDimitry Andric EltTys.push_back(T); 24240b57cec5SDimitry Andric else 24250b57cec5SDimitry Andric break; 24260b57cec5SDimitry Andric } 24270b57cec5SDimitry Andric if (EltTys.size() != Record.size()-1) 24280b57cec5SDimitry Andric return error("Invalid type"); 242981ad6265SDimitry Andric ContainedIDs.append(Record.begin() + 1, Record.end()); 24300b57cec5SDimitry Andric ResultTy = StructType::get(Context, EltTys, Record[0]); 24310b57cec5SDimitry Andric break; 24320b57cec5SDimitry Andric } 24330b57cec5SDimitry Andric case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N] 24340b57cec5SDimitry Andric if (convertToString(Record, 0, TypeName)) 243581ad6265SDimitry Andric return error("Invalid struct name record"); 24360b57cec5SDimitry Andric continue; 24370b57cec5SDimitry Andric 24380b57cec5SDimitry Andric case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N] 2439e8d8bef9SDimitry Andric if (Record.empty()) 244081ad6265SDimitry Andric return error("Invalid named struct record"); 24410b57cec5SDimitry Andric 24420b57cec5SDimitry Andric if (NumRecords >= TypeList.size()) 24430b57cec5SDimitry Andric return error("Invalid TYPE table"); 24440b57cec5SDimitry Andric 24450b57cec5SDimitry Andric // Check to see if this was forward referenced, if so fill in the temp. 24460b57cec5SDimitry Andric StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]); 24470b57cec5SDimitry Andric if (Res) { 24480b57cec5SDimitry Andric Res->setName(TypeName); 24490b57cec5SDimitry Andric TypeList[NumRecords] = nullptr; 24500b57cec5SDimitry Andric } else // Otherwise, create a new struct. 24510b57cec5SDimitry Andric Res = createIdentifiedStructType(Context, TypeName); 24520b57cec5SDimitry Andric TypeName.clear(); 24530b57cec5SDimitry Andric 24540b57cec5SDimitry Andric SmallVector<Type*, 8> EltTys; 24550b57cec5SDimitry Andric for (unsigned i = 1, e = Record.size(); i != e; ++i) { 24560b57cec5SDimitry Andric if (Type *T = getTypeByID(Record[i])) 24570b57cec5SDimitry Andric EltTys.push_back(T); 24580b57cec5SDimitry Andric else 24590b57cec5SDimitry Andric break; 24600b57cec5SDimitry Andric } 24610b57cec5SDimitry Andric if (EltTys.size() != Record.size()-1) 246281ad6265SDimitry Andric return error("Invalid named struct record"); 24630b57cec5SDimitry Andric Res->setBody(EltTys, Record[0]); 246481ad6265SDimitry Andric ContainedIDs.append(Record.begin() + 1, Record.end()); 24650b57cec5SDimitry Andric ResultTy = Res; 24660b57cec5SDimitry Andric break; 24670b57cec5SDimitry Andric } 24680b57cec5SDimitry Andric case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: [] 24690b57cec5SDimitry Andric if (Record.size() != 1) 247081ad6265SDimitry Andric return error("Invalid opaque type record"); 24710b57cec5SDimitry Andric 24720b57cec5SDimitry Andric if (NumRecords >= TypeList.size()) 24730b57cec5SDimitry Andric return error("Invalid TYPE table"); 24740b57cec5SDimitry Andric 24750b57cec5SDimitry Andric // Check to see if this was forward referenced, if so fill in the temp. 24760b57cec5SDimitry Andric StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]); 24770b57cec5SDimitry Andric if (Res) { 24780b57cec5SDimitry Andric Res->setName(TypeName); 24790b57cec5SDimitry Andric TypeList[NumRecords] = nullptr; 24800b57cec5SDimitry Andric } else // Otherwise, create a new struct with no body. 24810b57cec5SDimitry Andric Res = createIdentifiedStructType(Context, TypeName); 24820b57cec5SDimitry Andric TypeName.clear(); 24830b57cec5SDimitry Andric ResultTy = Res; 24840b57cec5SDimitry Andric break; 24850b57cec5SDimitry Andric } 2486bdd1243dSDimitry Andric case bitc::TYPE_CODE_TARGET_TYPE: { // TARGET_TYPE: [NumTy, Tys..., Ints...] 2487bdd1243dSDimitry Andric if (Record.size() < 1) 2488bdd1243dSDimitry Andric return error("Invalid target extension type record"); 2489bdd1243dSDimitry Andric 2490bdd1243dSDimitry Andric if (NumRecords >= TypeList.size()) 2491bdd1243dSDimitry Andric return error("Invalid TYPE table"); 2492bdd1243dSDimitry Andric 2493bdd1243dSDimitry Andric if (Record[0] >= Record.size()) 2494bdd1243dSDimitry Andric return error("Too many type parameters"); 2495bdd1243dSDimitry Andric 2496bdd1243dSDimitry Andric unsigned NumTys = Record[0]; 2497bdd1243dSDimitry Andric SmallVector<Type *, 4> TypeParams; 2498bdd1243dSDimitry Andric SmallVector<unsigned, 8> IntParams; 2499bdd1243dSDimitry Andric for (unsigned i = 0; i < NumTys; i++) { 2500bdd1243dSDimitry Andric if (Type *T = getTypeByID(Record[i + 1])) 2501bdd1243dSDimitry Andric TypeParams.push_back(T); 2502bdd1243dSDimitry Andric else 2503bdd1243dSDimitry Andric return error("Invalid type"); 2504bdd1243dSDimitry Andric } 2505bdd1243dSDimitry Andric 2506bdd1243dSDimitry Andric for (unsigned i = NumTys + 1, e = Record.size(); i < e; i++) { 2507bdd1243dSDimitry Andric if (Record[i] > UINT_MAX) 2508bdd1243dSDimitry Andric return error("Integer parameter too large"); 2509bdd1243dSDimitry Andric IntParams.push_back(Record[i]); 2510bdd1243dSDimitry Andric } 2511bdd1243dSDimitry Andric ResultTy = TargetExtType::get(Context, TypeName, TypeParams, IntParams); 2512bdd1243dSDimitry Andric TypeName.clear(); 2513bdd1243dSDimitry Andric break; 2514bdd1243dSDimitry Andric } 25150b57cec5SDimitry Andric case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty] 25160b57cec5SDimitry Andric if (Record.size() < 2) 251781ad6265SDimitry Andric return error("Invalid array type record"); 25180b57cec5SDimitry Andric ResultTy = getTypeByID(Record[1]); 25190b57cec5SDimitry Andric if (!ResultTy || !ArrayType::isValidElementType(ResultTy)) 25200b57cec5SDimitry Andric return error("Invalid type"); 252181ad6265SDimitry Andric ContainedIDs.push_back(Record[1]); 25220b57cec5SDimitry Andric ResultTy = ArrayType::get(ResultTy, Record[0]); 25230b57cec5SDimitry Andric break; 25240b57cec5SDimitry Andric case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty] or 25250b57cec5SDimitry Andric // [numelts, eltty, scalable] 25260b57cec5SDimitry Andric if (Record.size() < 2) 252781ad6265SDimitry Andric return error("Invalid vector type record"); 25280b57cec5SDimitry Andric if (Record[0] == 0) 25290b57cec5SDimitry Andric return error("Invalid vector length"); 25300b57cec5SDimitry Andric ResultTy = getTypeByID(Record[1]); 2531349cc55cSDimitry Andric if (!ResultTy || !VectorType::isValidElementType(ResultTy)) 25320b57cec5SDimitry Andric return error("Invalid type"); 25330b57cec5SDimitry Andric bool Scalable = Record.size() > 2 ? Record[2] : false; 253481ad6265SDimitry Andric ContainedIDs.push_back(Record[1]); 25350b57cec5SDimitry Andric ResultTy = VectorType::get(ResultTy, Record[0], Scalable); 25360b57cec5SDimitry Andric break; 25370b57cec5SDimitry Andric } 25380b57cec5SDimitry Andric 25390b57cec5SDimitry Andric if (NumRecords >= TypeList.size()) 25400b57cec5SDimitry Andric return error("Invalid TYPE table"); 25410b57cec5SDimitry Andric if (TypeList[NumRecords]) 25420b57cec5SDimitry Andric return error( 25430b57cec5SDimitry Andric "Invalid TYPE table: Only named structs can be forward referenced"); 25440b57cec5SDimitry Andric assert(ResultTy && "Didn't read a type?"); 254581ad6265SDimitry Andric TypeList[NumRecords] = ResultTy; 254681ad6265SDimitry Andric if (!ContainedIDs.empty()) 254781ad6265SDimitry Andric ContainedTypeIDs[NumRecords] = std::move(ContainedIDs); 254881ad6265SDimitry Andric ++NumRecords; 25490b57cec5SDimitry Andric } 25500b57cec5SDimitry Andric } 25510b57cec5SDimitry Andric 25520b57cec5SDimitry Andric Error BitcodeReader::parseOperandBundleTags() { 25530b57cec5SDimitry Andric if (Error Err = Stream.EnterSubBlock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID)) 25540b57cec5SDimitry Andric return Err; 25550b57cec5SDimitry Andric 25560b57cec5SDimitry Andric if (!BundleTags.empty()) 25570b57cec5SDimitry Andric return error("Invalid multiple blocks"); 25580b57cec5SDimitry Andric 25590b57cec5SDimitry Andric SmallVector<uint64_t, 64> Record; 25600b57cec5SDimitry Andric 25610b57cec5SDimitry Andric while (true) { 25620b57cec5SDimitry Andric Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); 25630b57cec5SDimitry Andric if (!MaybeEntry) 25640b57cec5SDimitry Andric return MaybeEntry.takeError(); 25650b57cec5SDimitry Andric BitstreamEntry Entry = MaybeEntry.get(); 25660b57cec5SDimitry Andric 25670b57cec5SDimitry Andric switch (Entry.Kind) { 25680b57cec5SDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already. 25690b57cec5SDimitry Andric case BitstreamEntry::Error: 25700b57cec5SDimitry Andric return error("Malformed block"); 25710b57cec5SDimitry Andric case BitstreamEntry::EndBlock: 25720b57cec5SDimitry Andric return Error::success(); 25730b57cec5SDimitry Andric case BitstreamEntry::Record: 25740b57cec5SDimitry Andric // The interesting case. 25750b57cec5SDimitry Andric break; 25760b57cec5SDimitry Andric } 25770b57cec5SDimitry Andric 25780b57cec5SDimitry Andric // Tags are implicitly mapped to integers by their order. 25790b57cec5SDimitry Andric 25800b57cec5SDimitry Andric Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record); 25810b57cec5SDimitry Andric if (!MaybeRecord) 25820b57cec5SDimitry Andric return MaybeRecord.takeError(); 25830b57cec5SDimitry Andric if (MaybeRecord.get() != bitc::OPERAND_BUNDLE_TAG) 258481ad6265SDimitry Andric return error("Invalid operand bundle record"); 25850b57cec5SDimitry Andric 25860b57cec5SDimitry Andric // OPERAND_BUNDLE_TAG: [strchr x N] 25870b57cec5SDimitry Andric BundleTags.emplace_back(); 25880b57cec5SDimitry Andric if (convertToString(Record, 0, BundleTags.back())) 258981ad6265SDimitry Andric return error("Invalid operand bundle record"); 25900b57cec5SDimitry Andric Record.clear(); 25910b57cec5SDimitry Andric } 25920b57cec5SDimitry Andric } 25930b57cec5SDimitry Andric 25940b57cec5SDimitry Andric Error BitcodeReader::parseSyncScopeNames() { 25950b57cec5SDimitry Andric if (Error Err = Stream.EnterSubBlock(bitc::SYNC_SCOPE_NAMES_BLOCK_ID)) 25960b57cec5SDimitry Andric return Err; 25970b57cec5SDimitry Andric 25980b57cec5SDimitry Andric if (!SSIDs.empty()) 25990b57cec5SDimitry Andric return error("Invalid multiple synchronization scope names blocks"); 26000b57cec5SDimitry Andric 26010b57cec5SDimitry Andric SmallVector<uint64_t, 64> Record; 26020b57cec5SDimitry Andric while (true) { 26030b57cec5SDimitry Andric Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); 26040b57cec5SDimitry Andric if (!MaybeEntry) 26050b57cec5SDimitry Andric return MaybeEntry.takeError(); 26060b57cec5SDimitry Andric BitstreamEntry Entry = MaybeEntry.get(); 26070b57cec5SDimitry Andric 26080b57cec5SDimitry Andric switch (Entry.Kind) { 26090b57cec5SDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already. 26100b57cec5SDimitry Andric case BitstreamEntry::Error: 26110b57cec5SDimitry Andric return error("Malformed block"); 26120b57cec5SDimitry Andric case BitstreamEntry::EndBlock: 26130b57cec5SDimitry Andric if (SSIDs.empty()) 26140b57cec5SDimitry Andric return error("Invalid empty synchronization scope names block"); 26150b57cec5SDimitry Andric return Error::success(); 26160b57cec5SDimitry Andric case BitstreamEntry::Record: 26170b57cec5SDimitry Andric // The interesting case. 26180b57cec5SDimitry Andric break; 26190b57cec5SDimitry Andric } 26200b57cec5SDimitry Andric 26210b57cec5SDimitry Andric // Synchronization scope names are implicitly mapped to synchronization 26220b57cec5SDimitry Andric // scope IDs by their order. 26230b57cec5SDimitry Andric 26240b57cec5SDimitry Andric Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record); 26250b57cec5SDimitry Andric if (!MaybeRecord) 26260b57cec5SDimitry Andric return MaybeRecord.takeError(); 26270b57cec5SDimitry Andric if (MaybeRecord.get() != bitc::SYNC_SCOPE_NAME) 262881ad6265SDimitry Andric return error("Invalid sync scope record"); 26290b57cec5SDimitry Andric 26300b57cec5SDimitry Andric SmallString<16> SSN; 26310b57cec5SDimitry Andric if (convertToString(Record, 0, SSN)) 263281ad6265SDimitry Andric return error("Invalid sync scope record"); 26330b57cec5SDimitry Andric 26340b57cec5SDimitry Andric SSIDs.push_back(Context.getOrInsertSyncScopeID(SSN)); 26350b57cec5SDimitry Andric Record.clear(); 26360b57cec5SDimitry Andric } 26370b57cec5SDimitry Andric } 26380b57cec5SDimitry Andric 26390b57cec5SDimitry Andric /// Associate a value with its name from the given index in the provided record. 26400b57cec5SDimitry Andric Expected<Value *> BitcodeReader::recordValue(SmallVectorImpl<uint64_t> &Record, 26410b57cec5SDimitry Andric unsigned NameIndex, Triple &TT) { 26420b57cec5SDimitry Andric SmallString<128> ValueName; 26430b57cec5SDimitry Andric if (convertToString(Record, NameIndex, ValueName)) 26440b57cec5SDimitry Andric return error("Invalid record"); 26450b57cec5SDimitry Andric unsigned ValueID = Record[0]; 26460b57cec5SDimitry Andric if (ValueID >= ValueList.size() || !ValueList[ValueID]) 26470b57cec5SDimitry Andric return error("Invalid record"); 26480b57cec5SDimitry Andric Value *V = ValueList[ValueID]; 26490b57cec5SDimitry Andric 26500b57cec5SDimitry Andric StringRef NameStr(ValueName.data(), ValueName.size()); 26510b57cec5SDimitry Andric if (NameStr.find_first_of(0) != StringRef::npos) 26520b57cec5SDimitry Andric return error("Invalid value name"); 26530b57cec5SDimitry Andric V->setName(NameStr); 26540b57cec5SDimitry Andric auto *GO = dyn_cast<GlobalObject>(V); 26550eae32dcSDimitry Andric if (GO && ImplicitComdatObjects.contains(GO) && TT.supportsCOMDAT()) 26560b57cec5SDimitry Andric GO->setComdat(TheModule->getOrInsertComdat(V->getName())); 26570b57cec5SDimitry Andric return V; 26580b57cec5SDimitry Andric } 26590b57cec5SDimitry Andric 26600b57cec5SDimitry Andric /// Helper to note and return the current location, and jump to the given 26610b57cec5SDimitry Andric /// offset. 26620b57cec5SDimitry Andric static Expected<uint64_t> jumpToValueSymbolTable(uint64_t Offset, 26630b57cec5SDimitry Andric BitstreamCursor &Stream) { 26640b57cec5SDimitry Andric // Save the current parsing location so we can jump back at the end 26650b57cec5SDimitry Andric // of the VST read. 26660b57cec5SDimitry Andric uint64_t CurrentBit = Stream.GetCurrentBitNo(); 26670b57cec5SDimitry Andric if (Error JumpFailed = Stream.JumpToBit(Offset * 32)) 26680b57cec5SDimitry Andric return std::move(JumpFailed); 26690b57cec5SDimitry Andric Expected<BitstreamEntry> MaybeEntry = Stream.advance(); 26700b57cec5SDimitry Andric if (!MaybeEntry) 26710b57cec5SDimitry Andric return MaybeEntry.takeError(); 267281ad6265SDimitry Andric if (MaybeEntry.get().Kind != BitstreamEntry::SubBlock || 267381ad6265SDimitry Andric MaybeEntry.get().ID != bitc::VALUE_SYMTAB_BLOCK_ID) 267481ad6265SDimitry Andric return error("Expected value symbol table subblock"); 26750b57cec5SDimitry Andric return CurrentBit; 26760b57cec5SDimitry Andric } 26770b57cec5SDimitry Andric 26780b57cec5SDimitry Andric void BitcodeReader::setDeferredFunctionInfo(unsigned FuncBitcodeOffsetDelta, 26790b57cec5SDimitry Andric Function *F, 26800b57cec5SDimitry Andric ArrayRef<uint64_t> Record) { 26810b57cec5SDimitry Andric // Note that we subtract 1 here because the offset is relative to one word 26820b57cec5SDimitry Andric // before the start of the identification or module block, which was 26830b57cec5SDimitry Andric // historically always the start of the regular bitcode header. 26840b57cec5SDimitry Andric uint64_t FuncWordOffset = Record[1] - 1; 26850b57cec5SDimitry Andric uint64_t FuncBitOffset = FuncWordOffset * 32; 26860b57cec5SDimitry Andric DeferredFunctionInfo[F] = FuncBitOffset + FuncBitcodeOffsetDelta; 26870b57cec5SDimitry Andric // Set the LastFunctionBlockBit to point to the last function block. 26880b57cec5SDimitry Andric // Later when parsing is resumed after function materialization, 26890b57cec5SDimitry Andric // we can simply skip that last function block. 26900b57cec5SDimitry Andric if (FuncBitOffset > LastFunctionBlockBit) 26910b57cec5SDimitry Andric LastFunctionBlockBit = FuncBitOffset; 26920b57cec5SDimitry Andric } 26930b57cec5SDimitry Andric 26940b57cec5SDimitry Andric /// Read a new-style GlobalValue symbol table. 26950b57cec5SDimitry Andric Error BitcodeReader::parseGlobalValueSymbolTable() { 26960b57cec5SDimitry Andric unsigned FuncBitcodeOffsetDelta = 26970b57cec5SDimitry Andric Stream.getAbbrevIDWidth() + bitc::BlockIDWidth; 26980b57cec5SDimitry Andric 26990b57cec5SDimitry Andric if (Error Err = Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID)) 27000b57cec5SDimitry Andric return Err; 27010b57cec5SDimitry Andric 27020b57cec5SDimitry Andric SmallVector<uint64_t, 64> Record; 27030b57cec5SDimitry Andric while (true) { 27040b57cec5SDimitry Andric Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); 27050b57cec5SDimitry Andric if (!MaybeEntry) 27060b57cec5SDimitry Andric return MaybeEntry.takeError(); 27070b57cec5SDimitry Andric BitstreamEntry Entry = MaybeEntry.get(); 27080b57cec5SDimitry Andric 27090b57cec5SDimitry Andric switch (Entry.Kind) { 27100b57cec5SDimitry Andric case BitstreamEntry::SubBlock: 27110b57cec5SDimitry Andric case BitstreamEntry::Error: 27120b57cec5SDimitry Andric return error("Malformed block"); 27130b57cec5SDimitry Andric case BitstreamEntry::EndBlock: 27140b57cec5SDimitry Andric return Error::success(); 27150b57cec5SDimitry Andric case BitstreamEntry::Record: 27160b57cec5SDimitry Andric break; 27170b57cec5SDimitry Andric } 27180b57cec5SDimitry Andric 27190b57cec5SDimitry Andric Record.clear(); 27200b57cec5SDimitry Andric Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record); 27210b57cec5SDimitry Andric if (!MaybeRecord) 27220b57cec5SDimitry Andric return MaybeRecord.takeError(); 27230b57cec5SDimitry Andric switch (MaybeRecord.get()) { 272481ad6265SDimitry Andric case bitc::VST_CODE_FNENTRY: { // [valueid, offset] 272581ad6265SDimitry Andric unsigned ValueID = Record[0]; 272681ad6265SDimitry Andric if (ValueID >= ValueList.size() || !ValueList[ValueID]) 272781ad6265SDimitry Andric return error("Invalid value reference in symbol table"); 27280b57cec5SDimitry Andric setDeferredFunctionInfo(FuncBitcodeOffsetDelta, 272981ad6265SDimitry Andric cast<Function>(ValueList[ValueID]), Record); 27300b57cec5SDimitry Andric break; 27310b57cec5SDimitry Andric } 27320b57cec5SDimitry Andric } 27330b57cec5SDimitry Andric } 273481ad6265SDimitry Andric } 27350b57cec5SDimitry Andric 27360b57cec5SDimitry Andric /// Parse the value symbol table at either the current parsing location or 27370b57cec5SDimitry Andric /// at the given bit offset if provided. 27380b57cec5SDimitry Andric Error BitcodeReader::parseValueSymbolTable(uint64_t Offset) { 27390b57cec5SDimitry Andric uint64_t CurrentBit; 27400b57cec5SDimitry Andric // Pass in the Offset to distinguish between calling for the module-level 27410b57cec5SDimitry Andric // VST (where we want to jump to the VST offset) and the function-level 27420b57cec5SDimitry Andric // VST (where we don't). 27430b57cec5SDimitry Andric if (Offset > 0) { 27440b57cec5SDimitry Andric Expected<uint64_t> MaybeCurrentBit = jumpToValueSymbolTable(Offset, Stream); 27450b57cec5SDimitry Andric if (!MaybeCurrentBit) 27460b57cec5SDimitry Andric return MaybeCurrentBit.takeError(); 27470b57cec5SDimitry Andric CurrentBit = MaybeCurrentBit.get(); 27480b57cec5SDimitry Andric // If this module uses a string table, read this as a module-level VST. 27490b57cec5SDimitry Andric if (UseStrtab) { 27500b57cec5SDimitry Andric if (Error Err = parseGlobalValueSymbolTable()) 27510b57cec5SDimitry Andric return Err; 27520b57cec5SDimitry Andric if (Error JumpFailed = Stream.JumpToBit(CurrentBit)) 27530b57cec5SDimitry Andric return JumpFailed; 27540b57cec5SDimitry Andric return Error::success(); 27550b57cec5SDimitry Andric } 27560b57cec5SDimitry Andric // Otherwise, the VST will be in a similar format to a function-level VST, 27570b57cec5SDimitry Andric // and will contain symbol names. 27580b57cec5SDimitry Andric } 27590b57cec5SDimitry Andric 27600b57cec5SDimitry Andric // Compute the delta between the bitcode indices in the VST (the word offset 27610b57cec5SDimitry Andric // to the word-aligned ENTER_SUBBLOCK for the function block, and that 27620b57cec5SDimitry Andric // expected by the lazy reader. The reader's EnterSubBlock expects to have 27630b57cec5SDimitry Andric // already read the ENTER_SUBBLOCK code (size getAbbrevIDWidth) and BlockID 27640b57cec5SDimitry Andric // (size BlockIDWidth). Note that we access the stream's AbbrevID width here 27650b57cec5SDimitry Andric // just before entering the VST subblock because: 1) the EnterSubBlock 27660b57cec5SDimitry Andric // changes the AbbrevID width; 2) the VST block is nested within the same 27670b57cec5SDimitry Andric // outer MODULE_BLOCK as the FUNCTION_BLOCKs and therefore have the same 27680b57cec5SDimitry Andric // AbbrevID width before calling EnterSubBlock; and 3) when we want to 27690b57cec5SDimitry Andric // jump to the FUNCTION_BLOCK using this offset later, we don't want 27700b57cec5SDimitry Andric // to rely on the stream's AbbrevID width being that of the MODULE_BLOCK. 27710b57cec5SDimitry Andric unsigned FuncBitcodeOffsetDelta = 27720b57cec5SDimitry Andric Stream.getAbbrevIDWidth() + bitc::BlockIDWidth; 27730b57cec5SDimitry Andric 27740b57cec5SDimitry Andric if (Error Err = Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID)) 27750b57cec5SDimitry Andric return Err; 27760b57cec5SDimitry Andric 27770b57cec5SDimitry Andric SmallVector<uint64_t, 64> Record; 27780b57cec5SDimitry Andric 27790b57cec5SDimitry Andric Triple TT(TheModule->getTargetTriple()); 27800b57cec5SDimitry Andric 27810b57cec5SDimitry Andric // Read all the records for this value table. 27820b57cec5SDimitry Andric SmallString<128> ValueName; 27830b57cec5SDimitry Andric 27840b57cec5SDimitry Andric while (true) { 27850b57cec5SDimitry Andric Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); 27860b57cec5SDimitry Andric if (!MaybeEntry) 27870b57cec5SDimitry Andric return MaybeEntry.takeError(); 27880b57cec5SDimitry Andric BitstreamEntry Entry = MaybeEntry.get(); 27890b57cec5SDimitry Andric 27900b57cec5SDimitry Andric switch (Entry.Kind) { 27910b57cec5SDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already. 27920b57cec5SDimitry Andric case BitstreamEntry::Error: 27930b57cec5SDimitry Andric return error("Malformed block"); 27940b57cec5SDimitry Andric case BitstreamEntry::EndBlock: 27950b57cec5SDimitry Andric if (Offset > 0) 27960b57cec5SDimitry Andric if (Error JumpFailed = Stream.JumpToBit(CurrentBit)) 27970b57cec5SDimitry Andric return JumpFailed; 27980b57cec5SDimitry Andric return Error::success(); 27990b57cec5SDimitry Andric case BitstreamEntry::Record: 28000b57cec5SDimitry Andric // The interesting case. 28010b57cec5SDimitry Andric break; 28020b57cec5SDimitry Andric } 28030b57cec5SDimitry Andric 28040b57cec5SDimitry Andric // Read a record. 28050b57cec5SDimitry Andric Record.clear(); 28060b57cec5SDimitry Andric Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record); 28070b57cec5SDimitry Andric if (!MaybeRecord) 28080b57cec5SDimitry Andric return MaybeRecord.takeError(); 28090b57cec5SDimitry Andric switch (MaybeRecord.get()) { 28100b57cec5SDimitry Andric default: // Default behavior: unknown type. 28110b57cec5SDimitry Andric break; 28120b57cec5SDimitry Andric case bitc::VST_CODE_ENTRY: { // VST_CODE_ENTRY: [valueid, namechar x N] 28130b57cec5SDimitry Andric Expected<Value *> ValOrErr = recordValue(Record, 1, TT); 28140b57cec5SDimitry Andric if (Error Err = ValOrErr.takeError()) 28150b57cec5SDimitry Andric return Err; 28160b57cec5SDimitry Andric ValOrErr.get(); 28170b57cec5SDimitry Andric break; 28180b57cec5SDimitry Andric } 28190b57cec5SDimitry Andric case bitc::VST_CODE_FNENTRY: { 28200b57cec5SDimitry Andric // VST_CODE_FNENTRY: [valueid, offset, namechar x N] 28210b57cec5SDimitry Andric Expected<Value *> ValOrErr = recordValue(Record, 2, TT); 28220b57cec5SDimitry Andric if (Error Err = ValOrErr.takeError()) 28230b57cec5SDimitry Andric return Err; 28240b57cec5SDimitry Andric Value *V = ValOrErr.get(); 28250b57cec5SDimitry Andric 28260b57cec5SDimitry Andric // Ignore function offsets emitted for aliases of functions in older 28270b57cec5SDimitry Andric // versions of LLVM. 28280b57cec5SDimitry Andric if (auto *F = dyn_cast<Function>(V)) 28290b57cec5SDimitry Andric setDeferredFunctionInfo(FuncBitcodeOffsetDelta, F, Record); 28300b57cec5SDimitry Andric break; 28310b57cec5SDimitry Andric } 28320b57cec5SDimitry Andric case bitc::VST_CODE_BBENTRY: { 28330b57cec5SDimitry Andric if (convertToString(Record, 1, ValueName)) 283481ad6265SDimitry Andric return error("Invalid bbentry record"); 28350b57cec5SDimitry Andric BasicBlock *BB = getBasicBlock(Record[0]); 28360b57cec5SDimitry Andric if (!BB) 283781ad6265SDimitry Andric return error("Invalid bbentry record"); 28380b57cec5SDimitry Andric 28390b57cec5SDimitry Andric BB->setName(StringRef(ValueName.data(), ValueName.size())); 28400b57cec5SDimitry Andric ValueName.clear(); 28410b57cec5SDimitry Andric break; 28420b57cec5SDimitry Andric } 28430b57cec5SDimitry Andric } 28440b57cec5SDimitry Andric } 28450b57cec5SDimitry Andric } 28460b57cec5SDimitry Andric 28470b57cec5SDimitry Andric /// Decode a signed value stored with the sign bit in the LSB for dense VBR 28480b57cec5SDimitry Andric /// encoding. 28490b57cec5SDimitry Andric uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) { 28500b57cec5SDimitry Andric if ((V & 1) == 0) 28510b57cec5SDimitry Andric return V >> 1; 28520b57cec5SDimitry Andric if (V != 1) 28530b57cec5SDimitry Andric return -(V >> 1); 28540b57cec5SDimitry Andric // There is no such thing as -0 with integers. "-0" really means MININT. 28550b57cec5SDimitry Andric return 1ULL << 63; 28560b57cec5SDimitry Andric } 28570b57cec5SDimitry Andric 28580b57cec5SDimitry Andric /// Resolve all of the initializers for global values and aliases that we can. 28590b57cec5SDimitry Andric Error BitcodeReader::resolveGlobalAndIndirectSymbolInits() { 28600b57cec5SDimitry Andric std::vector<std::pair<GlobalVariable *, unsigned>> GlobalInitWorklist; 2861349cc55cSDimitry Andric std::vector<std::pair<GlobalValue *, unsigned>> IndirectSymbolInitWorklist; 2862349cc55cSDimitry Andric std::vector<FunctionOperandInfo> FunctionOperandWorklist; 28630b57cec5SDimitry Andric 28640b57cec5SDimitry Andric GlobalInitWorklist.swap(GlobalInits); 28650b57cec5SDimitry Andric IndirectSymbolInitWorklist.swap(IndirectSymbolInits); 2866349cc55cSDimitry Andric FunctionOperandWorklist.swap(FunctionOperands); 28670b57cec5SDimitry Andric 28680b57cec5SDimitry Andric while (!GlobalInitWorklist.empty()) { 28690b57cec5SDimitry Andric unsigned ValID = GlobalInitWorklist.back().second; 28700b57cec5SDimitry Andric if (ValID >= ValueList.size()) { 28710b57cec5SDimitry Andric // Not ready to resolve this yet, it requires something later in the file. 28720b57cec5SDimitry Andric GlobalInits.push_back(GlobalInitWorklist.back()); 28730b57cec5SDimitry Andric } else { 287481ad6265SDimitry Andric Expected<Constant *> MaybeC = getValueForInitializer(ValID); 287581ad6265SDimitry Andric if (!MaybeC) 287681ad6265SDimitry Andric return MaybeC.takeError(); 287781ad6265SDimitry Andric GlobalInitWorklist.back().first->setInitializer(MaybeC.get()); 28780b57cec5SDimitry Andric } 28790b57cec5SDimitry Andric GlobalInitWorklist.pop_back(); 28800b57cec5SDimitry Andric } 28810b57cec5SDimitry Andric 28820b57cec5SDimitry Andric while (!IndirectSymbolInitWorklist.empty()) { 28830b57cec5SDimitry Andric unsigned ValID = IndirectSymbolInitWorklist.back().second; 28840b57cec5SDimitry Andric if (ValID >= ValueList.size()) { 28850b57cec5SDimitry Andric IndirectSymbolInits.push_back(IndirectSymbolInitWorklist.back()); 28860b57cec5SDimitry Andric } else { 288781ad6265SDimitry Andric Expected<Constant *> MaybeC = getValueForInitializer(ValID); 288881ad6265SDimitry Andric if (!MaybeC) 288981ad6265SDimitry Andric return MaybeC.takeError(); 289081ad6265SDimitry Andric Constant *C = MaybeC.get(); 2891349cc55cSDimitry Andric GlobalValue *GV = IndirectSymbolInitWorklist.back().first; 2892349cc55cSDimitry Andric if (auto *GA = dyn_cast<GlobalAlias>(GV)) { 2893349cc55cSDimitry Andric if (C->getType() != GV->getType()) 28940b57cec5SDimitry Andric return error("Alias and aliasee types don't match"); 2895349cc55cSDimitry Andric GA->setAliasee(C); 2896349cc55cSDimitry Andric } else if (auto *GI = dyn_cast<GlobalIFunc>(GV)) { 2897349cc55cSDimitry Andric Type *ResolverFTy = 2898349cc55cSDimitry Andric GlobalIFunc::getResolverFunctionType(GI->getValueType()); 2899bdd1243dSDimitry Andric // Transparently fix up the type for compatibility with older bitcode 2900bdd1243dSDimitry Andric GI->setResolver(ConstantExpr::getBitCast( 2901bdd1243dSDimitry Andric C, ResolverFTy->getPointerTo(GI->getAddressSpace()))); 2902349cc55cSDimitry Andric } else { 2903349cc55cSDimitry Andric return error("Expected an alias or an ifunc"); 2904349cc55cSDimitry Andric } 29050b57cec5SDimitry Andric } 29060b57cec5SDimitry Andric IndirectSymbolInitWorklist.pop_back(); 29070b57cec5SDimitry Andric } 29080b57cec5SDimitry Andric 2909349cc55cSDimitry Andric while (!FunctionOperandWorklist.empty()) { 2910349cc55cSDimitry Andric FunctionOperandInfo &Info = FunctionOperandWorklist.back(); 2911349cc55cSDimitry Andric if (Info.PersonalityFn) { 2912349cc55cSDimitry Andric unsigned ValID = Info.PersonalityFn - 1; 2913349cc55cSDimitry Andric if (ValID < ValueList.size()) { 291481ad6265SDimitry Andric Expected<Constant *> MaybeC = getValueForInitializer(ValID); 291581ad6265SDimitry Andric if (!MaybeC) 291681ad6265SDimitry Andric return MaybeC.takeError(); 291781ad6265SDimitry Andric Info.F->setPersonalityFn(MaybeC.get()); 2918349cc55cSDimitry Andric Info.PersonalityFn = 0; 29190b57cec5SDimitry Andric } 29200b57cec5SDimitry Andric } 2921349cc55cSDimitry Andric if (Info.Prefix) { 2922349cc55cSDimitry Andric unsigned ValID = Info.Prefix - 1; 2923349cc55cSDimitry Andric if (ValID < ValueList.size()) { 292481ad6265SDimitry Andric Expected<Constant *> MaybeC = getValueForInitializer(ValID); 292581ad6265SDimitry Andric if (!MaybeC) 292681ad6265SDimitry Andric return MaybeC.takeError(); 292781ad6265SDimitry Andric Info.F->setPrefixData(MaybeC.get()); 2928349cc55cSDimitry Andric Info.Prefix = 0; 29290b57cec5SDimitry Andric } 29300b57cec5SDimitry Andric } 2931349cc55cSDimitry Andric if (Info.Prologue) { 2932349cc55cSDimitry Andric unsigned ValID = Info.Prologue - 1; 2933349cc55cSDimitry Andric if (ValID < ValueList.size()) { 293481ad6265SDimitry Andric Expected<Constant *> MaybeC = getValueForInitializer(ValID); 293581ad6265SDimitry Andric if (!MaybeC) 293681ad6265SDimitry Andric return MaybeC.takeError(); 293781ad6265SDimitry Andric Info.F->setPrologueData(MaybeC.get()); 2938349cc55cSDimitry Andric Info.Prologue = 0; 29390b57cec5SDimitry Andric } 2940349cc55cSDimitry Andric } 2941349cc55cSDimitry Andric if (Info.PersonalityFn || Info.Prefix || Info.Prologue) 2942349cc55cSDimitry Andric FunctionOperands.push_back(Info); 2943349cc55cSDimitry Andric FunctionOperandWorklist.pop_back(); 29440b57cec5SDimitry Andric } 29450b57cec5SDimitry Andric 29460b57cec5SDimitry Andric return Error::success(); 29470b57cec5SDimitry Andric } 29480b57cec5SDimitry Andric 29495ffd83dbSDimitry Andric APInt llvm::readWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) { 29500b57cec5SDimitry Andric SmallVector<uint64_t, 8> Words(Vals.size()); 29510b57cec5SDimitry Andric transform(Vals, Words.begin(), 29520b57cec5SDimitry Andric BitcodeReader::decodeSignRotatedValue); 29530b57cec5SDimitry Andric 29540b57cec5SDimitry Andric return APInt(TypeBits, Words); 29550b57cec5SDimitry Andric } 29560b57cec5SDimitry Andric 29570b57cec5SDimitry Andric Error BitcodeReader::parseConstants() { 29580b57cec5SDimitry Andric if (Error Err = Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID)) 29590b57cec5SDimitry Andric return Err; 29600b57cec5SDimitry Andric 29610b57cec5SDimitry Andric SmallVector<uint64_t, 64> Record; 29620b57cec5SDimitry Andric 29630b57cec5SDimitry Andric // Read all the records for this value table. 29640b57cec5SDimitry Andric Type *CurTy = Type::getInt32Ty(Context); 296581ad6265SDimitry Andric unsigned Int32TyID = getVirtualTypeID(CurTy); 296681ad6265SDimitry Andric unsigned CurTyID = Int32TyID; 296781ad6265SDimitry Andric Type *CurElemTy = nullptr; 29680b57cec5SDimitry Andric unsigned NextCstNo = ValueList.size(); 29690b57cec5SDimitry Andric 29700b57cec5SDimitry Andric while (true) { 29710b57cec5SDimitry Andric Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); 29720b57cec5SDimitry Andric if (!MaybeEntry) 29730b57cec5SDimitry Andric return MaybeEntry.takeError(); 29740b57cec5SDimitry Andric BitstreamEntry Entry = MaybeEntry.get(); 29750b57cec5SDimitry Andric 29760b57cec5SDimitry Andric switch (Entry.Kind) { 29770b57cec5SDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already. 29780b57cec5SDimitry Andric case BitstreamEntry::Error: 29790b57cec5SDimitry Andric return error("Malformed block"); 29800b57cec5SDimitry Andric case BitstreamEntry::EndBlock: 29810b57cec5SDimitry Andric if (NextCstNo != ValueList.size()) 29820b57cec5SDimitry Andric return error("Invalid constant reference"); 29830b57cec5SDimitry Andric return Error::success(); 29840b57cec5SDimitry Andric case BitstreamEntry::Record: 29850b57cec5SDimitry Andric // The interesting case. 29860b57cec5SDimitry Andric break; 29870b57cec5SDimitry Andric } 29880b57cec5SDimitry Andric 29890b57cec5SDimitry Andric // Read a record. 29900b57cec5SDimitry Andric Record.clear(); 29910b57cec5SDimitry Andric Type *VoidType = Type::getVoidTy(Context); 29920b57cec5SDimitry Andric Value *V = nullptr; 29930b57cec5SDimitry Andric Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record); 29940b57cec5SDimitry Andric if (!MaybeBitCode) 29950b57cec5SDimitry Andric return MaybeBitCode.takeError(); 29960b57cec5SDimitry Andric switch (unsigned BitCode = MaybeBitCode.get()) { 29970b57cec5SDimitry Andric default: // Default behavior: unknown constant 29980b57cec5SDimitry Andric case bitc::CST_CODE_UNDEF: // UNDEF 29990b57cec5SDimitry Andric V = UndefValue::get(CurTy); 30000b57cec5SDimitry Andric break; 3001e8d8bef9SDimitry Andric case bitc::CST_CODE_POISON: // POISON 3002e8d8bef9SDimitry Andric V = PoisonValue::get(CurTy); 3003e8d8bef9SDimitry Andric break; 30040b57cec5SDimitry Andric case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid] 30050b57cec5SDimitry Andric if (Record.empty()) 300681ad6265SDimitry Andric return error("Invalid settype record"); 30070b57cec5SDimitry Andric if (Record[0] >= TypeList.size() || !TypeList[Record[0]]) 300881ad6265SDimitry Andric return error("Invalid settype record"); 30090b57cec5SDimitry Andric if (TypeList[Record[0]] == VoidType) 30100b57cec5SDimitry Andric return error("Invalid constant type"); 301181ad6265SDimitry Andric CurTyID = Record[0]; 301281ad6265SDimitry Andric CurTy = TypeList[CurTyID]; 301381ad6265SDimitry Andric CurElemTy = getPtrElementTypeByID(CurTyID); 30140b57cec5SDimitry Andric continue; // Skip the ValueList manipulation. 30150b57cec5SDimitry Andric case bitc::CST_CODE_NULL: // NULL 30168bcb0991SDimitry Andric if (CurTy->isVoidTy() || CurTy->isFunctionTy() || CurTy->isLabelTy()) 30178bcb0991SDimitry Andric return error("Invalid type for a constant null value"); 3018bdd1243dSDimitry Andric if (auto *TETy = dyn_cast<TargetExtType>(CurTy)) 3019bdd1243dSDimitry Andric if (!TETy->hasProperty(TargetExtType::HasZeroInit)) 3020bdd1243dSDimitry Andric return error("Invalid type for a constant null value"); 30210b57cec5SDimitry Andric V = Constant::getNullValue(CurTy); 30220b57cec5SDimitry Andric break; 30230b57cec5SDimitry Andric case bitc::CST_CODE_INTEGER: // INTEGER: [intval] 30240b57cec5SDimitry Andric if (!CurTy->isIntegerTy() || Record.empty()) 302581ad6265SDimitry Andric return error("Invalid integer const record"); 30260b57cec5SDimitry Andric V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0])); 30270b57cec5SDimitry Andric break; 30280b57cec5SDimitry Andric case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval] 30290b57cec5SDimitry Andric if (!CurTy->isIntegerTy() || Record.empty()) 303081ad6265SDimitry Andric return error("Invalid wide integer const record"); 30310b57cec5SDimitry Andric 30320b57cec5SDimitry Andric APInt VInt = 30330b57cec5SDimitry Andric readWideAPInt(Record, cast<IntegerType>(CurTy)->getBitWidth()); 30340b57cec5SDimitry Andric V = ConstantInt::get(Context, VInt); 30350b57cec5SDimitry Andric 30360b57cec5SDimitry Andric break; 30370b57cec5SDimitry Andric } 30380b57cec5SDimitry Andric case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval] 30390b57cec5SDimitry Andric if (Record.empty()) 304081ad6265SDimitry Andric return error("Invalid float const record"); 30410b57cec5SDimitry Andric if (CurTy->isHalfTy()) 30420b57cec5SDimitry Andric V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf(), 30430b57cec5SDimitry Andric APInt(16, (uint16_t)Record[0]))); 30445ffd83dbSDimitry Andric else if (CurTy->isBFloatTy()) 30455ffd83dbSDimitry Andric V = ConstantFP::get(Context, APFloat(APFloat::BFloat(), 30465ffd83dbSDimitry Andric APInt(16, (uint32_t)Record[0]))); 30470b57cec5SDimitry Andric else if (CurTy->isFloatTy()) 30480b57cec5SDimitry Andric V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle(), 30490b57cec5SDimitry Andric APInt(32, (uint32_t)Record[0]))); 30500b57cec5SDimitry Andric else if (CurTy->isDoubleTy()) 30510b57cec5SDimitry Andric V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble(), 30520b57cec5SDimitry Andric APInt(64, Record[0]))); 30530b57cec5SDimitry Andric else if (CurTy->isX86_FP80Ty()) { 30540b57cec5SDimitry Andric // Bits are not stored the same way as a normal i80 APInt, compensate. 30550b57cec5SDimitry Andric uint64_t Rearrange[2]; 30560b57cec5SDimitry Andric Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16); 30570b57cec5SDimitry Andric Rearrange[1] = Record[0] >> 48; 30580b57cec5SDimitry Andric V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended(), 30590b57cec5SDimitry Andric APInt(80, Rearrange))); 30600b57cec5SDimitry Andric } else if (CurTy->isFP128Ty()) 30610b57cec5SDimitry Andric V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad(), 30620b57cec5SDimitry Andric APInt(128, Record))); 30630b57cec5SDimitry Andric else if (CurTy->isPPC_FP128Ty()) 30640b57cec5SDimitry Andric V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble(), 30650b57cec5SDimitry Andric APInt(128, Record))); 30660b57cec5SDimitry Andric else 30670b57cec5SDimitry Andric V = UndefValue::get(CurTy); 30680b57cec5SDimitry Andric break; 30690b57cec5SDimitry Andric } 30700b57cec5SDimitry Andric 30710b57cec5SDimitry Andric case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number] 30720b57cec5SDimitry Andric if (Record.empty()) 307381ad6265SDimitry Andric return error("Invalid aggregate record"); 30740b57cec5SDimitry Andric 30750b57cec5SDimitry Andric unsigned Size = Record.size(); 307681ad6265SDimitry Andric SmallVector<unsigned, 16> Elts; 307781ad6265SDimitry Andric for (unsigned i = 0; i != Size; ++i) 307881ad6265SDimitry Andric Elts.push_back(Record[i]); 30790b57cec5SDimitry Andric 308081ad6265SDimitry Andric if (isa<StructType>(CurTy)) { 308181ad6265SDimitry Andric V = BitcodeConstant::create( 308281ad6265SDimitry Andric Alloc, CurTy, BitcodeConstant::ConstantStructOpcode, Elts); 308381ad6265SDimitry Andric } else if (isa<ArrayType>(CurTy)) { 308481ad6265SDimitry Andric V = BitcodeConstant::create(Alloc, CurTy, 308581ad6265SDimitry Andric BitcodeConstant::ConstantArrayOpcode, Elts); 308681ad6265SDimitry Andric } else if (isa<VectorType>(CurTy)) { 308781ad6265SDimitry Andric V = BitcodeConstant::create( 308881ad6265SDimitry Andric Alloc, CurTy, BitcodeConstant::ConstantVectorOpcode, Elts); 30890b57cec5SDimitry Andric } else { 30900b57cec5SDimitry Andric V = UndefValue::get(CurTy); 30910b57cec5SDimitry Andric } 30920b57cec5SDimitry Andric break; 30930b57cec5SDimitry Andric } 30940b57cec5SDimitry Andric case bitc::CST_CODE_STRING: // STRING: [values] 30950b57cec5SDimitry Andric case bitc::CST_CODE_CSTRING: { // CSTRING: [values] 30960b57cec5SDimitry Andric if (Record.empty()) 309781ad6265SDimitry Andric return error("Invalid string record"); 30980b57cec5SDimitry Andric 30990b57cec5SDimitry Andric SmallString<16> Elts(Record.begin(), Record.end()); 31000b57cec5SDimitry Andric V = ConstantDataArray::getString(Context, Elts, 31010b57cec5SDimitry Andric BitCode == bitc::CST_CODE_CSTRING); 31020b57cec5SDimitry Andric break; 31030b57cec5SDimitry Andric } 31040b57cec5SDimitry Andric case bitc::CST_CODE_DATA: {// DATA: [n x value] 31050b57cec5SDimitry Andric if (Record.empty()) 310681ad6265SDimitry Andric return error("Invalid data record"); 31070b57cec5SDimitry Andric 31085ffd83dbSDimitry Andric Type *EltTy; 31095ffd83dbSDimitry Andric if (auto *Array = dyn_cast<ArrayType>(CurTy)) 31105ffd83dbSDimitry Andric EltTy = Array->getElementType(); 31115ffd83dbSDimitry Andric else 31125ffd83dbSDimitry Andric EltTy = cast<VectorType>(CurTy)->getElementType(); 31130b57cec5SDimitry Andric if (EltTy->isIntegerTy(8)) { 31140b57cec5SDimitry Andric SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end()); 31150b57cec5SDimitry Andric if (isa<VectorType>(CurTy)) 31160b57cec5SDimitry Andric V = ConstantDataVector::get(Context, Elts); 31170b57cec5SDimitry Andric else 31180b57cec5SDimitry Andric V = ConstantDataArray::get(Context, Elts); 31190b57cec5SDimitry Andric } else if (EltTy->isIntegerTy(16)) { 31200b57cec5SDimitry Andric SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end()); 31210b57cec5SDimitry Andric if (isa<VectorType>(CurTy)) 31220b57cec5SDimitry Andric V = ConstantDataVector::get(Context, Elts); 31230b57cec5SDimitry Andric else 31240b57cec5SDimitry Andric V = ConstantDataArray::get(Context, Elts); 31250b57cec5SDimitry Andric } else if (EltTy->isIntegerTy(32)) { 31260b57cec5SDimitry Andric SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end()); 31270b57cec5SDimitry Andric if (isa<VectorType>(CurTy)) 31280b57cec5SDimitry Andric V = ConstantDataVector::get(Context, Elts); 31290b57cec5SDimitry Andric else 31300b57cec5SDimitry Andric V = ConstantDataArray::get(Context, Elts); 31310b57cec5SDimitry Andric } else if (EltTy->isIntegerTy(64)) { 31320b57cec5SDimitry Andric SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end()); 31330b57cec5SDimitry Andric if (isa<VectorType>(CurTy)) 31340b57cec5SDimitry Andric V = ConstantDataVector::get(Context, Elts); 31350b57cec5SDimitry Andric else 31360b57cec5SDimitry Andric V = ConstantDataArray::get(Context, Elts); 31370b57cec5SDimitry Andric } else if (EltTy->isHalfTy()) { 31380b57cec5SDimitry Andric SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end()); 31390b57cec5SDimitry Andric if (isa<VectorType>(CurTy)) 31405ffd83dbSDimitry Andric V = ConstantDataVector::getFP(EltTy, Elts); 31410b57cec5SDimitry Andric else 31425ffd83dbSDimitry Andric V = ConstantDataArray::getFP(EltTy, Elts); 31435ffd83dbSDimitry Andric } else if (EltTy->isBFloatTy()) { 31445ffd83dbSDimitry Andric SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end()); 31455ffd83dbSDimitry Andric if (isa<VectorType>(CurTy)) 31465ffd83dbSDimitry Andric V = ConstantDataVector::getFP(EltTy, Elts); 31475ffd83dbSDimitry Andric else 31485ffd83dbSDimitry Andric V = ConstantDataArray::getFP(EltTy, Elts); 31490b57cec5SDimitry Andric } else if (EltTy->isFloatTy()) { 31500b57cec5SDimitry Andric SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end()); 31510b57cec5SDimitry Andric if (isa<VectorType>(CurTy)) 31525ffd83dbSDimitry Andric V = ConstantDataVector::getFP(EltTy, Elts); 31530b57cec5SDimitry Andric else 31545ffd83dbSDimitry Andric V = ConstantDataArray::getFP(EltTy, Elts); 31550b57cec5SDimitry Andric } else if (EltTy->isDoubleTy()) { 31560b57cec5SDimitry Andric SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end()); 31570b57cec5SDimitry Andric if (isa<VectorType>(CurTy)) 31585ffd83dbSDimitry Andric V = ConstantDataVector::getFP(EltTy, Elts); 31590b57cec5SDimitry Andric else 31605ffd83dbSDimitry Andric V = ConstantDataArray::getFP(EltTy, Elts); 31610b57cec5SDimitry Andric } else { 31620b57cec5SDimitry Andric return error("Invalid type for value"); 31630b57cec5SDimitry Andric } 31640b57cec5SDimitry Andric break; 31650b57cec5SDimitry Andric } 31660b57cec5SDimitry Andric case bitc::CST_CODE_CE_UNOP: { // CE_UNOP: [opcode, opval] 31670b57cec5SDimitry Andric if (Record.size() < 2) 316881ad6265SDimitry Andric return error("Invalid unary op constexpr record"); 31690b57cec5SDimitry Andric int Opc = getDecodedUnaryOpcode(Record[0], CurTy); 31700b57cec5SDimitry Andric if (Opc < 0) { 31710b57cec5SDimitry Andric V = UndefValue::get(CurTy); // Unknown unop. 31720b57cec5SDimitry Andric } else { 317381ad6265SDimitry Andric V = BitcodeConstant::create(Alloc, CurTy, Opc, (unsigned)Record[1]); 31740b57cec5SDimitry Andric } 31750b57cec5SDimitry Andric break; 31760b57cec5SDimitry Andric } 31770b57cec5SDimitry Andric case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval] 31780b57cec5SDimitry Andric if (Record.size() < 3) 317981ad6265SDimitry Andric return error("Invalid binary op constexpr record"); 31800b57cec5SDimitry Andric int Opc = getDecodedBinaryOpcode(Record[0], CurTy); 31810b57cec5SDimitry Andric if (Opc < 0) { 31820b57cec5SDimitry Andric V = UndefValue::get(CurTy); // Unknown binop. 31830b57cec5SDimitry Andric } else { 318481ad6265SDimitry Andric uint8_t Flags = 0; 31850b57cec5SDimitry Andric if (Record.size() >= 4) { 31860b57cec5SDimitry Andric if (Opc == Instruction::Add || 31870b57cec5SDimitry Andric Opc == Instruction::Sub || 31880b57cec5SDimitry Andric Opc == Instruction::Mul || 31890b57cec5SDimitry Andric Opc == Instruction::Shl) { 31900b57cec5SDimitry Andric if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP)) 31910b57cec5SDimitry Andric Flags |= OverflowingBinaryOperator::NoSignedWrap; 31920b57cec5SDimitry Andric if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP)) 31930b57cec5SDimitry Andric Flags |= OverflowingBinaryOperator::NoUnsignedWrap; 31940b57cec5SDimitry Andric } else if (Opc == Instruction::SDiv || 31950b57cec5SDimitry Andric Opc == Instruction::UDiv || 31960b57cec5SDimitry Andric Opc == Instruction::LShr || 31970b57cec5SDimitry Andric Opc == Instruction::AShr) { 31980b57cec5SDimitry Andric if (Record[3] & (1 << bitc::PEO_EXACT)) 31990b57cec5SDimitry Andric Flags |= SDivOperator::IsExact; 32000b57cec5SDimitry Andric } 32010b57cec5SDimitry Andric } 320281ad6265SDimitry Andric V = BitcodeConstant::create(Alloc, CurTy, {(uint8_t)Opc, Flags}, 320381ad6265SDimitry Andric {(unsigned)Record[1], (unsigned)Record[2]}); 32040b57cec5SDimitry Andric } 32050b57cec5SDimitry Andric break; 32060b57cec5SDimitry Andric } 32070b57cec5SDimitry Andric case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval] 32080b57cec5SDimitry Andric if (Record.size() < 3) 320981ad6265SDimitry Andric return error("Invalid cast constexpr record"); 32100b57cec5SDimitry Andric int Opc = getDecodedCastOpcode(Record[0]); 32110b57cec5SDimitry Andric if (Opc < 0) { 32120b57cec5SDimitry Andric V = UndefValue::get(CurTy); // Unknown cast. 32130b57cec5SDimitry Andric } else { 321481ad6265SDimitry Andric unsigned OpTyID = Record[1]; 321581ad6265SDimitry Andric Type *OpTy = getTypeByID(OpTyID); 32160b57cec5SDimitry Andric if (!OpTy) 321781ad6265SDimitry Andric return error("Invalid cast constexpr record"); 321881ad6265SDimitry Andric V = BitcodeConstant::create(Alloc, CurTy, Opc, (unsigned)Record[2]); 32190b57cec5SDimitry Andric } 32200b57cec5SDimitry Andric break; 32210b57cec5SDimitry Andric } 32220b57cec5SDimitry Andric case bitc::CST_CODE_CE_INBOUNDS_GEP: // [ty, n x operands] 32230b57cec5SDimitry Andric case bitc::CST_CODE_CE_GEP: // [ty, n x operands] 32240b57cec5SDimitry Andric case bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX: { // [ty, flags, n x 32250b57cec5SDimitry Andric // operands] 322681ad6265SDimitry Andric if (Record.size() < 2) 322781ad6265SDimitry Andric return error("Constant GEP record must have at least two elements"); 32280b57cec5SDimitry Andric unsigned OpNum = 0; 32290b57cec5SDimitry Andric Type *PointeeType = nullptr; 32300b57cec5SDimitry Andric if (BitCode == bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX || 32310b57cec5SDimitry Andric Record.size() % 2) 32320b57cec5SDimitry Andric PointeeType = getTypeByID(Record[OpNum++]); 32330b57cec5SDimitry Andric 32340b57cec5SDimitry Andric bool InBounds = false; 3235bdd1243dSDimitry Andric std::optional<unsigned> InRangeIndex; 32360b57cec5SDimitry Andric if (BitCode == bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX) { 32370b57cec5SDimitry Andric uint64_t Op = Record[OpNum++]; 32380b57cec5SDimitry Andric InBounds = Op & 1; 32390b57cec5SDimitry Andric InRangeIndex = Op >> 1; 32400b57cec5SDimitry Andric } else if (BitCode == bitc::CST_CODE_CE_INBOUNDS_GEP) 32410b57cec5SDimitry Andric InBounds = true; 32420b57cec5SDimitry Andric 324381ad6265SDimitry Andric SmallVector<unsigned, 16> Elts; 324481ad6265SDimitry Andric unsigned BaseTypeID = Record[OpNum]; 32450b57cec5SDimitry Andric while (OpNum != Record.size()) { 324681ad6265SDimitry Andric unsigned ElTyID = Record[OpNum++]; 324781ad6265SDimitry Andric Type *ElTy = getTypeByID(ElTyID); 32480b57cec5SDimitry Andric if (!ElTy) 324981ad6265SDimitry Andric return error("Invalid getelementptr constexpr record"); 325081ad6265SDimitry Andric Elts.push_back(Record[OpNum++]); 32510b57cec5SDimitry Andric } 32520b57cec5SDimitry Andric 32530b57cec5SDimitry Andric if (Elts.size() < 1) 32540b57cec5SDimitry Andric return error("Invalid gep with no operands"); 32550b57cec5SDimitry Andric 325681ad6265SDimitry Andric Type *BaseType = getTypeByID(BaseTypeID); 325781ad6265SDimitry Andric if (isa<VectorType>(BaseType)) { 325881ad6265SDimitry Andric BaseTypeID = getContainedTypeID(BaseTypeID, 0); 325981ad6265SDimitry Andric BaseType = getTypeByID(BaseTypeID); 326081ad6265SDimitry Andric } 326181ad6265SDimitry Andric 326281ad6265SDimitry Andric PointerType *OrigPtrTy = dyn_cast_or_null<PointerType>(BaseType); 326381ad6265SDimitry Andric if (!OrigPtrTy) 326481ad6265SDimitry Andric return error("GEP base operand must be pointer or vector of pointer"); 326581ad6265SDimitry Andric 326681ad6265SDimitry Andric if (!PointeeType) { 326781ad6265SDimitry Andric PointeeType = getPtrElementTypeByID(BaseTypeID); 32680b57cec5SDimitry Andric if (!PointeeType) 326981ad6265SDimitry Andric return error("Missing element type for old-style constant GEP"); 3270*fe013be4SDimitry Andric } 32710b57cec5SDimitry Andric 327281ad6265SDimitry Andric V = BitcodeConstant::create(Alloc, CurTy, 327381ad6265SDimitry Andric {Instruction::GetElementPtr, InBounds, 327481ad6265SDimitry Andric InRangeIndex.value_or(-1), PointeeType}, 327581ad6265SDimitry Andric Elts); 32760b57cec5SDimitry Andric break; 32770b57cec5SDimitry Andric } 32780b57cec5SDimitry Andric case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#] 32790b57cec5SDimitry Andric if (Record.size() < 3) 328081ad6265SDimitry Andric return error("Invalid select constexpr record"); 32810b57cec5SDimitry Andric 328281ad6265SDimitry Andric V = BitcodeConstant::create( 328381ad6265SDimitry Andric Alloc, CurTy, Instruction::Select, 328481ad6265SDimitry Andric {(unsigned)Record[0], (unsigned)Record[1], (unsigned)Record[2]}); 328581ad6265SDimitry Andric break; 32860b57cec5SDimitry Andric } 32870b57cec5SDimitry Andric case bitc::CST_CODE_CE_EXTRACTELT 32880b57cec5SDimitry Andric : { // CE_EXTRACTELT: [opty, opval, opty, opval] 32890b57cec5SDimitry Andric if (Record.size() < 3) 329081ad6265SDimitry Andric return error("Invalid extractelement constexpr record"); 329181ad6265SDimitry Andric unsigned OpTyID = Record[0]; 32920b57cec5SDimitry Andric VectorType *OpTy = 329381ad6265SDimitry Andric dyn_cast_or_null<VectorType>(getTypeByID(OpTyID)); 32940b57cec5SDimitry Andric if (!OpTy) 329581ad6265SDimitry Andric return error("Invalid extractelement constexpr record"); 329681ad6265SDimitry Andric unsigned IdxRecord; 32970b57cec5SDimitry Andric if (Record.size() == 4) { 329881ad6265SDimitry Andric unsigned IdxTyID = Record[2]; 329981ad6265SDimitry Andric Type *IdxTy = getTypeByID(IdxTyID); 33000b57cec5SDimitry Andric if (!IdxTy) 330181ad6265SDimitry Andric return error("Invalid extractelement constexpr record"); 330281ad6265SDimitry Andric IdxRecord = Record[3]; 33035ffd83dbSDimitry Andric } else { 33045ffd83dbSDimitry Andric // Deprecated, but still needed to read old bitcode files. 330581ad6265SDimitry Andric IdxRecord = Record[2]; 33065ffd83dbSDimitry Andric } 330781ad6265SDimitry Andric V = BitcodeConstant::create(Alloc, CurTy, Instruction::ExtractElement, 330881ad6265SDimitry Andric {(unsigned)Record[1], IdxRecord}); 33090b57cec5SDimitry Andric break; 33100b57cec5SDimitry Andric } 33110b57cec5SDimitry Andric case bitc::CST_CODE_CE_INSERTELT 33120b57cec5SDimitry Andric : { // CE_INSERTELT: [opval, opval, opty, opval] 33130b57cec5SDimitry Andric VectorType *OpTy = dyn_cast<VectorType>(CurTy); 33140b57cec5SDimitry Andric if (Record.size() < 3 || !OpTy) 331581ad6265SDimitry Andric return error("Invalid insertelement constexpr record"); 331681ad6265SDimitry Andric unsigned IdxRecord; 33170b57cec5SDimitry Andric if (Record.size() == 4) { 331881ad6265SDimitry Andric unsigned IdxTyID = Record[2]; 331981ad6265SDimitry Andric Type *IdxTy = getTypeByID(IdxTyID); 33200b57cec5SDimitry Andric if (!IdxTy) 332181ad6265SDimitry Andric return error("Invalid insertelement constexpr record"); 332281ad6265SDimitry Andric IdxRecord = Record[3]; 33235ffd83dbSDimitry Andric } else { 33245ffd83dbSDimitry Andric // Deprecated, but still needed to read old bitcode files. 332581ad6265SDimitry Andric IdxRecord = Record[2]; 33265ffd83dbSDimitry Andric } 332781ad6265SDimitry Andric V = BitcodeConstant::create( 332881ad6265SDimitry Andric Alloc, CurTy, Instruction::InsertElement, 332981ad6265SDimitry Andric {(unsigned)Record[0], (unsigned)Record[1], IdxRecord}); 33300b57cec5SDimitry Andric break; 33310b57cec5SDimitry Andric } 33320b57cec5SDimitry Andric case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval] 33330b57cec5SDimitry Andric VectorType *OpTy = dyn_cast<VectorType>(CurTy); 33340b57cec5SDimitry Andric if (Record.size() < 3 || !OpTy) 333581ad6265SDimitry Andric return error("Invalid shufflevector constexpr record"); 333681ad6265SDimitry Andric V = BitcodeConstant::create( 333781ad6265SDimitry Andric Alloc, CurTy, Instruction::ShuffleVector, 333881ad6265SDimitry Andric {(unsigned)Record[0], (unsigned)Record[1], (unsigned)Record[2]}); 333981ad6265SDimitry Andric break; 33400b57cec5SDimitry Andric } 33410b57cec5SDimitry Andric case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval] 33420b57cec5SDimitry Andric VectorType *RTy = dyn_cast<VectorType>(CurTy); 33430b57cec5SDimitry Andric VectorType *OpTy = 33440b57cec5SDimitry Andric dyn_cast_or_null<VectorType>(getTypeByID(Record[0])); 33450b57cec5SDimitry Andric if (Record.size() < 4 || !RTy || !OpTy) 334681ad6265SDimitry Andric return error("Invalid shufflevector constexpr record"); 334781ad6265SDimitry Andric V = BitcodeConstant::create( 334881ad6265SDimitry Andric Alloc, CurTy, Instruction::ShuffleVector, 334981ad6265SDimitry Andric {(unsigned)Record[1], (unsigned)Record[2], (unsigned)Record[3]}); 335081ad6265SDimitry Andric break; 33510b57cec5SDimitry Andric } 33520b57cec5SDimitry Andric case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred] 33530b57cec5SDimitry Andric if (Record.size() < 4) 335481ad6265SDimitry Andric return error("Invalid cmp constexpt record"); 335581ad6265SDimitry Andric unsigned OpTyID = Record[0]; 335681ad6265SDimitry Andric Type *OpTy = getTypeByID(OpTyID); 33570b57cec5SDimitry Andric if (!OpTy) 335881ad6265SDimitry Andric return error("Invalid cmp constexpr record"); 335981ad6265SDimitry Andric V = BitcodeConstant::create( 336081ad6265SDimitry Andric Alloc, CurTy, 336181ad6265SDimitry Andric {(uint8_t)(OpTy->isFPOrFPVectorTy() ? Instruction::FCmp 336281ad6265SDimitry Andric : Instruction::ICmp), 336381ad6265SDimitry Andric (uint8_t)Record[3]}, 336481ad6265SDimitry Andric {(unsigned)Record[1], (unsigned)Record[2]}); 33650b57cec5SDimitry Andric break; 33660b57cec5SDimitry Andric } 33670b57cec5SDimitry Andric // This maintains backward compatibility, pre-asm dialect keywords. 33685ffd83dbSDimitry Andric // Deprecated, but still needed to read old bitcode files. 33690b57cec5SDimitry Andric case bitc::CST_CODE_INLINEASM_OLD: { 33700b57cec5SDimitry Andric if (Record.size() < 2) 337181ad6265SDimitry Andric return error("Invalid inlineasm record"); 33720b57cec5SDimitry Andric std::string AsmStr, ConstrStr; 33730b57cec5SDimitry Andric bool HasSideEffects = Record[0] & 1; 33740b57cec5SDimitry Andric bool IsAlignStack = Record[0] >> 1; 33750b57cec5SDimitry Andric unsigned AsmStrSize = Record[1]; 33760b57cec5SDimitry Andric if (2+AsmStrSize >= Record.size()) 337781ad6265SDimitry Andric return error("Invalid inlineasm record"); 33780b57cec5SDimitry Andric unsigned ConstStrSize = Record[2+AsmStrSize]; 33790b57cec5SDimitry Andric if (3+AsmStrSize+ConstStrSize > Record.size()) 338081ad6265SDimitry Andric return error("Invalid inlineasm record"); 33810b57cec5SDimitry Andric 33820b57cec5SDimitry Andric for (unsigned i = 0; i != AsmStrSize; ++i) 33830b57cec5SDimitry Andric AsmStr += (char)Record[2+i]; 33840b57cec5SDimitry Andric for (unsigned i = 0; i != ConstStrSize; ++i) 33850b57cec5SDimitry Andric ConstrStr += (char)Record[3+AsmStrSize+i]; 33860b57cec5SDimitry Andric UpgradeInlineAsmString(&AsmStr); 338781ad6265SDimitry Andric if (!CurElemTy) 338881ad6265SDimitry Andric return error("Missing element type for old-style inlineasm"); 338981ad6265SDimitry Andric V = InlineAsm::get(cast<FunctionType>(CurElemTy), AsmStr, ConstrStr, 339081ad6265SDimitry Andric HasSideEffects, IsAlignStack); 33910b57cec5SDimitry Andric break; 33920b57cec5SDimitry Andric } 33930b57cec5SDimitry Andric // This version adds support for the asm dialect keywords (e.g., 33940b57cec5SDimitry Andric // inteldialect). 3395fe6060f1SDimitry Andric case bitc::CST_CODE_INLINEASM_OLD2: { 33960b57cec5SDimitry Andric if (Record.size() < 2) 339781ad6265SDimitry Andric return error("Invalid inlineasm record"); 33980b57cec5SDimitry Andric std::string AsmStr, ConstrStr; 33990b57cec5SDimitry Andric bool HasSideEffects = Record[0] & 1; 34000b57cec5SDimitry Andric bool IsAlignStack = (Record[0] >> 1) & 1; 34010b57cec5SDimitry Andric unsigned AsmDialect = Record[0] >> 2; 34020b57cec5SDimitry Andric unsigned AsmStrSize = Record[1]; 34030b57cec5SDimitry Andric if (2+AsmStrSize >= Record.size()) 340481ad6265SDimitry Andric return error("Invalid inlineasm record"); 34050b57cec5SDimitry Andric unsigned ConstStrSize = Record[2+AsmStrSize]; 34060b57cec5SDimitry Andric if (3+AsmStrSize+ConstStrSize > Record.size()) 340781ad6265SDimitry Andric return error("Invalid inlineasm record"); 34080b57cec5SDimitry Andric 34090b57cec5SDimitry Andric for (unsigned i = 0; i != AsmStrSize; ++i) 34100b57cec5SDimitry Andric AsmStr += (char)Record[2+i]; 34110b57cec5SDimitry Andric for (unsigned i = 0; i != ConstStrSize; ++i) 34120b57cec5SDimitry Andric ConstrStr += (char)Record[3+AsmStrSize+i]; 34130b57cec5SDimitry Andric UpgradeInlineAsmString(&AsmStr); 341481ad6265SDimitry Andric if (!CurElemTy) 341581ad6265SDimitry Andric return error("Missing element type for old-style inlineasm"); 341681ad6265SDimitry Andric V = InlineAsm::get(cast<FunctionType>(CurElemTy), AsmStr, ConstrStr, 341781ad6265SDimitry Andric HasSideEffects, IsAlignStack, 34180b57cec5SDimitry Andric InlineAsm::AsmDialect(AsmDialect)); 34190b57cec5SDimitry Andric break; 34200b57cec5SDimitry Andric } 3421fe6060f1SDimitry Andric // This version adds support for the unwind keyword. 342204eeddc0SDimitry Andric case bitc::CST_CODE_INLINEASM_OLD3: { 3423fe6060f1SDimitry Andric if (Record.size() < 2) 342481ad6265SDimitry Andric return error("Invalid inlineasm record"); 342504eeddc0SDimitry Andric unsigned OpNum = 0; 3426fe6060f1SDimitry Andric std::string AsmStr, ConstrStr; 342704eeddc0SDimitry Andric bool HasSideEffects = Record[OpNum] & 1; 342804eeddc0SDimitry Andric bool IsAlignStack = (Record[OpNum] >> 1) & 1; 342904eeddc0SDimitry Andric unsigned AsmDialect = (Record[OpNum] >> 2) & 1; 343004eeddc0SDimitry Andric bool CanThrow = (Record[OpNum] >> 3) & 1; 343104eeddc0SDimitry Andric ++OpNum; 343204eeddc0SDimitry Andric unsigned AsmStrSize = Record[OpNum]; 343304eeddc0SDimitry Andric ++OpNum; 343404eeddc0SDimitry Andric if (OpNum + AsmStrSize >= Record.size()) 343581ad6265SDimitry Andric return error("Invalid inlineasm record"); 343604eeddc0SDimitry Andric unsigned ConstStrSize = Record[OpNum + AsmStrSize]; 343704eeddc0SDimitry Andric if (OpNum + 1 + AsmStrSize + ConstStrSize > Record.size()) 343881ad6265SDimitry Andric return error("Invalid inlineasm record"); 3439fe6060f1SDimitry Andric 3440fe6060f1SDimitry Andric for (unsigned i = 0; i != AsmStrSize; ++i) 344104eeddc0SDimitry Andric AsmStr += (char)Record[OpNum + i]; 344204eeddc0SDimitry Andric ++OpNum; 3443fe6060f1SDimitry Andric for (unsigned i = 0; i != ConstStrSize; ++i) 344404eeddc0SDimitry Andric ConstrStr += (char)Record[OpNum + AsmStrSize + i]; 3445fe6060f1SDimitry Andric UpgradeInlineAsmString(&AsmStr); 344681ad6265SDimitry Andric if (!CurElemTy) 344781ad6265SDimitry Andric return error("Missing element type for old-style inlineasm"); 344881ad6265SDimitry Andric V = InlineAsm::get(cast<FunctionType>(CurElemTy), AsmStr, ConstrStr, 344981ad6265SDimitry Andric HasSideEffects, IsAlignStack, 3450fe6060f1SDimitry Andric InlineAsm::AsmDialect(AsmDialect), CanThrow); 3451fe6060f1SDimitry Andric break; 3452fe6060f1SDimitry Andric } 345304eeddc0SDimitry Andric // This version adds explicit function type. 345404eeddc0SDimitry Andric case bitc::CST_CODE_INLINEASM: { 345504eeddc0SDimitry Andric if (Record.size() < 3) 345681ad6265SDimitry Andric return error("Invalid inlineasm record"); 345704eeddc0SDimitry Andric unsigned OpNum = 0; 345804eeddc0SDimitry Andric auto *FnTy = dyn_cast_or_null<FunctionType>(getTypeByID(Record[OpNum])); 345904eeddc0SDimitry Andric ++OpNum; 346004eeddc0SDimitry Andric if (!FnTy) 346181ad6265SDimitry Andric return error("Invalid inlineasm record"); 346204eeddc0SDimitry Andric std::string AsmStr, ConstrStr; 346304eeddc0SDimitry Andric bool HasSideEffects = Record[OpNum] & 1; 346404eeddc0SDimitry Andric bool IsAlignStack = (Record[OpNum] >> 1) & 1; 346504eeddc0SDimitry Andric unsigned AsmDialect = (Record[OpNum] >> 2) & 1; 346604eeddc0SDimitry Andric bool CanThrow = (Record[OpNum] >> 3) & 1; 346704eeddc0SDimitry Andric ++OpNum; 346804eeddc0SDimitry Andric unsigned AsmStrSize = Record[OpNum]; 346904eeddc0SDimitry Andric ++OpNum; 347004eeddc0SDimitry Andric if (OpNum + AsmStrSize >= Record.size()) 347181ad6265SDimitry Andric return error("Invalid inlineasm record"); 347204eeddc0SDimitry Andric unsigned ConstStrSize = Record[OpNum + AsmStrSize]; 347304eeddc0SDimitry Andric if (OpNum + 1 + AsmStrSize + ConstStrSize > Record.size()) 347481ad6265SDimitry Andric return error("Invalid inlineasm record"); 347504eeddc0SDimitry Andric 347604eeddc0SDimitry Andric for (unsigned i = 0; i != AsmStrSize; ++i) 347704eeddc0SDimitry Andric AsmStr += (char)Record[OpNum + i]; 347804eeddc0SDimitry Andric ++OpNum; 347904eeddc0SDimitry Andric for (unsigned i = 0; i != ConstStrSize; ++i) 348004eeddc0SDimitry Andric ConstrStr += (char)Record[OpNum + AsmStrSize + i]; 348104eeddc0SDimitry Andric UpgradeInlineAsmString(&AsmStr); 348204eeddc0SDimitry Andric V = InlineAsm::get(FnTy, AsmStr, ConstrStr, HasSideEffects, IsAlignStack, 348304eeddc0SDimitry Andric InlineAsm::AsmDialect(AsmDialect), CanThrow); 348404eeddc0SDimitry Andric break; 348504eeddc0SDimitry Andric } 34860b57cec5SDimitry Andric case bitc::CST_CODE_BLOCKADDRESS:{ 34870b57cec5SDimitry Andric if (Record.size() < 3) 348881ad6265SDimitry Andric return error("Invalid blockaddress record"); 348981ad6265SDimitry Andric unsigned FnTyID = Record[0]; 349081ad6265SDimitry Andric Type *FnTy = getTypeByID(FnTyID); 34910b57cec5SDimitry Andric if (!FnTy) 349281ad6265SDimitry Andric return error("Invalid blockaddress record"); 349381ad6265SDimitry Andric V = BitcodeConstant::create( 349481ad6265SDimitry Andric Alloc, CurTy, 349581ad6265SDimitry Andric {BitcodeConstant::BlockAddressOpcode, 0, (unsigned)Record[2]}, 349681ad6265SDimitry Andric Record[1]); 34970b57cec5SDimitry Andric break; 34980b57cec5SDimitry Andric } 3499fe6060f1SDimitry Andric case bitc::CST_CODE_DSO_LOCAL_EQUIVALENT: { 3500fe6060f1SDimitry Andric if (Record.size() < 2) 350181ad6265SDimitry Andric return error("Invalid dso_local record"); 350281ad6265SDimitry Andric unsigned GVTyID = Record[0]; 350381ad6265SDimitry Andric Type *GVTy = getTypeByID(GVTyID); 3504fe6060f1SDimitry Andric if (!GVTy) 350581ad6265SDimitry Andric return error("Invalid dso_local record"); 350681ad6265SDimitry Andric V = BitcodeConstant::create( 350781ad6265SDimitry Andric Alloc, CurTy, BitcodeConstant::DSOLocalEquivalentOpcode, Record[1]); 3508fe6060f1SDimitry Andric break; 3509fe6060f1SDimitry Andric } 35100eae32dcSDimitry Andric case bitc::CST_CODE_NO_CFI_VALUE: { 35110eae32dcSDimitry Andric if (Record.size() < 2) 351281ad6265SDimitry Andric return error("Invalid no_cfi record"); 351381ad6265SDimitry Andric unsigned GVTyID = Record[0]; 351481ad6265SDimitry Andric Type *GVTy = getTypeByID(GVTyID); 35150eae32dcSDimitry Andric if (!GVTy) 351681ad6265SDimitry Andric return error("Invalid no_cfi record"); 351781ad6265SDimitry Andric V = BitcodeConstant::create(Alloc, CurTy, BitcodeConstant::NoCFIOpcode, 351881ad6265SDimitry Andric Record[1]); 35190eae32dcSDimitry Andric break; 35200eae32dcSDimitry Andric } 35210b57cec5SDimitry Andric } 35220b57cec5SDimitry Andric 352381ad6265SDimitry Andric assert(V->getType() == getTypeByID(CurTyID) && "Incorrect result type ID"); 352481ad6265SDimitry Andric if (Error Err = ValueList.assignValue(NextCstNo, V, CurTyID)) 352581ad6265SDimitry Andric return Err; 35260b57cec5SDimitry Andric ++NextCstNo; 35270b57cec5SDimitry Andric } 35280b57cec5SDimitry Andric } 35290b57cec5SDimitry Andric 35300b57cec5SDimitry Andric Error BitcodeReader::parseUseLists() { 35310b57cec5SDimitry Andric if (Error Err = Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID)) 35320b57cec5SDimitry Andric return Err; 35330b57cec5SDimitry Andric 35340b57cec5SDimitry Andric // Read all the records. 35350b57cec5SDimitry Andric SmallVector<uint64_t, 64> Record; 35360b57cec5SDimitry Andric 35370b57cec5SDimitry Andric while (true) { 35380b57cec5SDimitry Andric Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); 35390b57cec5SDimitry Andric if (!MaybeEntry) 35400b57cec5SDimitry Andric return MaybeEntry.takeError(); 35410b57cec5SDimitry Andric BitstreamEntry Entry = MaybeEntry.get(); 35420b57cec5SDimitry Andric 35430b57cec5SDimitry Andric switch (Entry.Kind) { 35440b57cec5SDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already. 35450b57cec5SDimitry Andric case BitstreamEntry::Error: 35460b57cec5SDimitry Andric return error("Malformed block"); 35470b57cec5SDimitry Andric case BitstreamEntry::EndBlock: 35480b57cec5SDimitry Andric return Error::success(); 35490b57cec5SDimitry Andric case BitstreamEntry::Record: 35500b57cec5SDimitry Andric // The interesting case. 35510b57cec5SDimitry Andric break; 35520b57cec5SDimitry Andric } 35530b57cec5SDimitry Andric 35540b57cec5SDimitry Andric // Read a use list record. 35550b57cec5SDimitry Andric Record.clear(); 35560b57cec5SDimitry Andric bool IsBB = false; 35570b57cec5SDimitry Andric Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record); 35580b57cec5SDimitry Andric if (!MaybeRecord) 35590b57cec5SDimitry Andric return MaybeRecord.takeError(); 35600b57cec5SDimitry Andric switch (MaybeRecord.get()) { 35610b57cec5SDimitry Andric default: // Default behavior: unknown type. 35620b57cec5SDimitry Andric break; 35630b57cec5SDimitry Andric case bitc::USELIST_CODE_BB: 35640b57cec5SDimitry Andric IsBB = true; 3565bdd1243dSDimitry Andric [[fallthrough]]; 35660b57cec5SDimitry Andric case bitc::USELIST_CODE_DEFAULT: { 35670b57cec5SDimitry Andric unsigned RecordLength = Record.size(); 35680b57cec5SDimitry Andric if (RecordLength < 3) 35690b57cec5SDimitry Andric // Records should have at least an ID and two indexes. 35700b57cec5SDimitry Andric return error("Invalid record"); 3571e8d8bef9SDimitry Andric unsigned ID = Record.pop_back_val(); 35720b57cec5SDimitry Andric 35730b57cec5SDimitry Andric Value *V; 35740b57cec5SDimitry Andric if (IsBB) { 35750b57cec5SDimitry Andric assert(ID < FunctionBBs.size() && "Basic block not found"); 35760b57cec5SDimitry Andric V = FunctionBBs[ID]; 35770b57cec5SDimitry Andric } else 35780b57cec5SDimitry Andric V = ValueList[ID]; 35790b57cec5SDimitry Andric unsigned NumUses = 0; 35800b57cec5SDimitry Andric SmallDenseMap<const Use *, unsigned, 16> Order; 35810b57cec5SDimitry Andric for (const Use &U : V->materialized_uses()) { 35820b57cec5SDimitry Andric if (++NumUses > Record.size()) 35830b57cec5SDimitry Andric break; 35840b57cec5SDimitry Andric Order[&U] = Record[NumUses - 1]; 35850b57cec5SDimitry Andric } 35860b57cec5SDimitry Andric if (Order.size() != Record.size() || NumUses > Record.size()) 35870b57cec5SDimitry Andric // Mismatches can happen if the functions are being materialized lazily 35880b57cec5SDimitry Andric // (out-of-order), or a value has been upgraded. 35890b57cec5SDimitry Andric break; 35900b57cec5SDimitry Andric 35910b57cec5SDimitry Andric V->sortUseList([&](const Use &L, const Use &R) { 35920b57cec5SDimitry Andric return Order.lookup(&L) < Order.lookup(&R); 35930b57cec5SDimitry Andric }); 35940b57cec5SDimitry Andric break; 35950b57cec5SDimitry Andric } 35960b57cec5SDimitry Andric } 35970b57cec5SDimitry Andric } 35980b57cec5SDimitry Andric } 35990b57cec5SDimitry Andric 36000b57cec5SDimitry Andric /// When we see the block for metadata, remember where it is and then skip it. 36010b57cec5SDimitry Andric /// This lets us lazily deserialize the metadata. 36020b57cec5SDimitry Andric Error BitcodeReader::rememberAndSkipMetadata() { 36030b57cec5SDimitry Andric // Save the current stream state. 36040b57cec5SDimitry Andric uint64_t CurBit = Stream.GetCurrentBitNo(); 36050b57cec5SDimitry Andric DeferredMetadataInfo.push_back(CurBit); 36060b57cec5SDimitry Andric 36070b57cec5SDimitry Andric // Skip over the block for now. 36080b57cec5SDimitry Andric if (Error Err = Stream.SkipBlock()) 36090b57cec5SDimitry Andric return Err; 36100b57cec5SDimitry Andric return Error::success(); 36110b57cec5SDimitry Andric } 36120b57cec5SDimitry Andric 36130b57cec5SDimitry Andric Error BitcodeReader::materializeMetadata() { 36140b57cec5SDimitry Andric for (uint64_t BitPos : DeferredMetadataInfo) { 36150b57cec5SDimitry Andric // Move the bit stream to the saved position. 36160b57cec5SDimitry Andric if (Error JumpFailed = Stream.JumpToBit(BitPos)) 36170b57cec5SDimitry Andric return JumpFailed; 36180b57cec5SDimitry Andric if (Error Err = MDLoader->parseModuleMetadata()) 36190b57cec5SDimitry Andric return Err; 36200b57cec5SDimitry Andric } 36210b57cec5SDimitry Andric 36220b57cec5SDimitry Andric // Upgrade "Linker Options" module flag to "llvm.linker.options" module-level 3623e8d8bef9SDimitry Andric // metadata. Only upgrade if the new option doesn't exist to avoid upgrade 3624e8d8bef9SDimitry Andric // multiple times. 3625e8d8bef9SDimitry Andric if (!TheModule->getNamedMetadata("llvm.linker.options")) { 36260b57cec5SDimitry Andric if (Metadata *Val = TheModule->getModuleFlag("Linker Options")) { 36270b57cec5SDimitry Andric NamedMDNode *LinkerOpts = 36280b57cec5SDimitry Andric TheModule->getOrInsertNamedMetadata("llvm.linker.options"); 36290b57cec5SDimitry Andric for (const MDOperand &MDOptions : cast<MDNode>(Val)->operands()) 36300b57cec5SDimitry Andric LinkerOpts->addOperand(cast<MDNode>(MDOptions)); 36310b57cec5SDimitry Andric } 3632e8d8bef9SDimitry Andric } 36330b57cec5SDimitry Andric 36340b57cec5SDimitry Andric DeferredMetadataInfo.clear(); 36350b57cec5SDimitry Andric return Error::success(); 36360b57cec5SDimitry Andric } 36370b57cec5SDimitry Andric 36380b57cec5SDimitry Andric void BitcodeReader::setStripDebugInfo() { StripDebugInfo = true; } 36390b57cec5SDimitry Andric 36400b57cec5SDimitry Andric /// When we see the block for a function body, remember where it is and then 36410b57cec5SDimitry Andric /// skip it. This lets us lazily deserialize the functions. 36420b57cec5SDimitry Andric Error BitcodeReader::rememberAndSkipFunctionBody() { 36430b57cec5SDimitry Andric // Get the function we are talking about. 36440b57cec5SDimitry Andric if (FunctionsWithBodies.empty()) 36450b57cec5SDimitry Andric return error("Insufficient function protos"); 36460b57cec5SDimitry Andric 36470b57cec5SDimitry Andric Function *Fn = FunctionsWithBodies.back(); 36480b57cec5SDimitry Andric FunctionsWithBodies.pop_back(); 36490b57cec5SDimitry Andric 36500b57cec5SDimitry Andric // Save the current stream state. 36510b57cec5SDimitry Andric uint64_t CurBit = Stream.GetCurrentBitNo(); 36520b57cec5SDimitry Andric assert( 36530b57cec5SDimitry Andric (DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo[Fn] == CurBit) && 36540b57cec5SDimitry Andric "Mismatch between VST and scanned function offsets"); 36550b57cec5SDimitry Andric DeferredFunctionInfo[Fn] = CurBit; 36560b57cec5SDimitry Andric 36570b57cec5SDimitry Andric // Skip over the function block for now. 36580b57cec5SDimitry Andric if (Error Err = Stream.SkipBlock()) 36590b57cec5SDimitry Andric return Err; 36600b57cec5SDimitry Andric return Error::success(); 36610b57cec5SDimitry Andric } 36620b57cec5SDimitry Andric 36630b57cec5SDimitry Andric Error BitcodeReader::globalCleanup() { 36640b57cec5SDimitry Andric // Patch the initializers for globals and aliases up. 36650b57cec5SDimitry Andric if (Error Err = resolveGlobalAndIndirectSymbolInits()) 36660b57cec5SDimitry Andric return Err; 36670b57cec5SDimitry Andric if (!GlobalInits.empty() || !IndirectSymbolInits.empty()) 36680b57cec5SDimitry Andric return error("Malformed global initializer set"); 36690b57cec5SDimitry Andric 36700b57cec5SDimitry Andric // Look for intrinsic functions which need to be upgraded at some point 36715ffd83dbSDimitry Andric // and functions that need to have their function attributes upgraded. 36720b57cec5SDimitry Andric for (Function &F : *TheModule) { 36730b57cec5SDimitry Andric MDLoader->upgradeDebugIntrinsics(F); 36740b57cec5SDimitry Andric Function *NewFn; 36750b57cec5SDimitry Andric if (UpgradeIntrinsicFunction(&F, NewFn)) 36760b57cec5SDimitry Andric UpgradedIntrinsics[&F] = NewFn; 36775ffd83dbSDimitry Andric // Look for functions that rely on old function attribute behavior. 36785ffd83dbSDimitry Andric UpgradeFunctionAttributes(F); 36790b57cec5SDimitry Andric } 36800b57cec5SDimitry Andric 36810b57cec5SDimitry Andric // Look for global variables which need to be renamed. 36820b57cec5SDimitry Andric std::vector<std::pair<GlobalVariable *, GlobalVariable *>> UpgradedVariables; 36830b57cec5SDimitry Andric for (GlobalVariable &GV : TheModule->globals()) 36840b57cec5SDimitry Andric if (GlobalVariable *Upgraded = UpgradeGlobalVariable(&GV)) 36850b57cec5SDimitry Andric UpgradedVariables.emplace_back(&GV, Upgraded); 36860b57cec5SDimitry Andric for (auto &Pair : UpgradedVariables) { 36870b57cec5SDimitry Andric Pair.first->eraseFromParent(); 3688*fe013be4SDimitry Andric TheModule->insertGlobalVariable(Pair.second); 36890b57cec5SDimitry Andric } 36900b57cec5SDimitry Andric 36910b57cec5SDimitry Andric // Force deallocation of memory for these vectors to favor the client that 36920b57cec5SDimitry Andric // want lazy deserialization. 36930b57cec5SDimitry Andric std::vector<std::pair<GlobalVariable *, unsigned>>().swap(GlobalInits); 3694349cc55cSDimitry Andric std::vector<std::pair<GlobalValue *, unsigned>>().swap(IndirectSymbolInits); 36950b57cec5SDimitry Andric return Error::success(); 36960b57cec5SDimitry Andric } 36970b57cec5SDimitry Andric 36980b57cec5SDimitry Andric /// Support for lazy parsing of function bodies. This is required if we 36990b57cec5SDimitry Andric /// either have an old bitcode file without a VST forward declaration record, 37000b57cec5SDimitry Andric /// or if we have an anonymous function being materialized, since anonymous 37010b57cec5SDimitry Andric /// functions do not have a name and are therefore not in the VST. 37020b57cec5SDimitry Andric Error BitcodeReader::rememberAndSkipFunctionBodies() { 37030b57cec5SDimitry Andric if (Error JumpFailed = Stream.JumpToBit(NextUnreadBit)) 37040b57cec5SDimitry Andric return JumpFailed; 37050b57cec5SDimitry Andric 37060b57cec5SDimitry Andric if (Stream.AtEndOfStream()) 37070b57cec5SDimitry Andric return error("Could not find function in stream"); 37080b57cec5SDimitry Andric 37090b57cec5SDimitry Andric if (!SeenFirstFunctionBody) 37100b57cec5SDimitry Andric return error("Trying to materialize functions before seeing function blocks"); 37110b57cec5SDimitry Andric 37120b57cec5SDimitry Andric // An old bitcode file with the symbol table at the end would have 37130b57cec5SDimitry Andric // finished the parse greedily. 37140b57cec5SDimitry Andric assert(SeenValueSymbolTable); 37150b57cec5SDimitry Andric 37160b57cec5SDimitry Andric SmallVector<uint64_t, 64> Record; 37170b57cec5SDimitry Andric 37180b57cec5SDimitry Andric while (true) { 37190b57cec5SDimitry Andric Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance(); 37200b57cec5SDimitry Andric if (!MaybeEntry) 37210b57cec5SDimitry Andric return MaybeEntry.takeError(); 37220b57cec5SDimitry Andric llvm::BitstreamEntry Entry = MaybeEntry.get(); 37230b57cec5SDimitry Andric 37240b57cec5SDimitry Andric switch (Entry.Kind) { 37250b57cec5SDimitry Andric default: 37260b57cec5SDimitry Andric return error("Expect SubBlock"); 37270b57cec5SDimitry Andric case BitstreamEntry::SubBlock: 37280b57cec5SDimitry Andric switch (Entry.ID) { 37290b57cec5SDimitry Andric default: 37300b57cec5SDimitry Andric return error("Expect function block"); 37310b57cec5SDimitry Andric case bitc::FUNCTION_BLOCK_ID: 37320b57cec5SDimitry Andric if (Error Err = rememberAndSkipFunctionBody()) 37330b57cec5SDimitry Andric return Err; 37340b57cec5SDimitry Andric NextUnreadBit = Stream.GetCurrentBitNo(); 37350b57cec5SDimitry Andric return Error::success(); 37360b57cec5SDimitry Andric } 37370b57cec5SDimitry Andric } 37380b57cec5SDimitry Andric } 37390b57cec5SDimitry Andric } 37400b57cec5SDimitry Andric 374181ad6265SDimitry Andric Error BitcodeReaderBase::readBlockInfo() { 3742bdd1243dSDimitry Andric Expected<std::optional<BitstreamBlockInfo>> MaybeNewBlockInfo = 37430b57cec5SDimitry Andric Stream.ReadBlockInfoBlock(); 37440b57cec5SDimitry Andric if (!MaybeNewBlockInfo) 374581ad6265SDimitry Andric return MaybeNewBlockInfo.takeError(); 3746bdd1243dSDimitry Andric std::optional<BitstreamBlockInfo> NewBlockInfo = 37470b57cec5SDimitry Andric std::move(MaybeNewBlockInfo.get()); 37480b57cec5SDimitry Andric if (!NewBlockInfo) 374981ad6265SDimitry Andric return error("Malformed block"); 37500b57cec5SDimitry Andric BlockInfo = std::move(*NewBlockInfo); 375181ad6265SDimitry Andric return Error::success(); 37520b57cec5SDimitry Andric } 37530b57cec5SDimitry Andric 37540b57cec5SDimitry Andric Error BitcodeReader::parseComdatRecord(ArrayRef<uint64_t> Record) { 37550b57cec5SDimitry Andric // v1: [selection_kind, name] 37560b57cec5SDimitry Andric // v2: [strtab_offset, strtab_size, selection_kind] 37570b57cec5SDimitry Andric StringRef Name; 37580b57cec5SDimitry Andric std::tie(Name, Record) = readNameFromStrtab(Record); 37590b57cec5SDimitry Andric 37600b57cec5SDimitry Andric if (Record.empty()) 37610b57cec5SDimitry Andric return error("Invalid record"); 37620b57cec5SDimitry Andric Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]); 37630b57cec5SDimitry Andric std::string OldFormatName; 37640b57cec5SDimitry Andric if (!UseStrtab) { 37650b57cec5SDimitry Andric if (Record.size() < 2) 37660b57cec5SDimitry Andric return error("Invalid record"); 37670b57cec5SDimitry Andric unsigned ComdatNameSize = Record[1]; 376881ad6265SDimitry Andric if (ComdatNameSize > Record.size() - 2) 376981ad6265SDimitry Andric return error("Comdat name size too large"); 37700b57cec5SDimitry Andric OldFormatName.reserve(ComdatNameSize); 37710b57cec5SDimitry Andric for (unsigned i = 0; i != ComdatNameSize; ++i) 37720b57cec5SDimitry Andric OldFormatName += (char)Record[2 + i]; 37730b57cec5SDimitry Andric Name = OldFormatName; 37740b57cec5SDimitry Andric } 37750b57cec5SDimitry Andric Comdat *C = TheModule->getOrInsertComdat(Name); 37760b57cec5SDimitry Andric C->setSelectionKind(SK); 37770b57cec5SDimitry Andric ComdatList.push_back(C); 37780b57cec5SDimitry Andric return Error::success(); 37790b57cec5SDimitry Andric } 37800b57cec5SDimitry Andric 37810b57cec5SDimitry Andric static void inferDSOLocal(GlobalValue *GV) { 37820b57cec5SDimitry Andric // infer dso_local from linkage and visibility if it is not encoded. 37830b57cec5SDimitry Andric if (GV->hasLocalLinkage() || 37840b57cec5SDimitry Andric (!GV->hasDefaultVisibility() && !GV->hasExternalWeakLinkage())) 37850b57cec5SDimitry Andric GV->setDSOLocal(true); 37860b57cec5SDimitry Andric } 37870b57cec5SDimitry Andric 378881ad6265SDimitry Andric GlobalValue::SanitizerMetadata deserializeSanitizerMetadata(unsigned V) { 378981ad6265SDimitry Andric GlobalValue::SanitizerMetadata Meta; 379081ad6265SDimitry Andric if (V & (1 << 0)) 379181ad6265SDimitry Andric Meta.NoAddress = true; 379281ad6265SDimitry Andric if (V & (1 << 1)) 379381ad6265SDimitry Andric Meta.NoHWAddress = true; 379481ad6265SDimitry Andric if (V & (1 << 2)) 3795753f127fSDimitry Andric Meta.Memtag = true; 379681ad6265SDimitry Andric if (V & (1 << 3)) 379781ad6265SDimitry Andric Meta.IsDynInit = true; 379881ad6265SDimitry Andric return Meta; 379981ad6265SDimitry Andric } 380081ad6265SDimitry Andric 38010b57cec5SDimitry Andric Error BitcodeReader::parseGlobalVarRecord(ArrayRef<uint64_t> Record) { 38020b57cec5SDimitry Andric // v1: [pointer type, isconst, initid, linkage, alignment, section, 38030b57cec5SDimitry Andric // visibility, threadlocal, unnamed_addr, externally_initialized, 38040b57cec5SDimitry Andric // dllstorageclass, comdat, attributes, preemption specifier, 38050b57cec5SDimitry Andric // partition strtab offset, partition strtab size] (name in VST) 38060b57cec5SDimitry Andric // v2: [strtab_offset, strtab_size, v1] 38070b57cec5SDimitry Andric StringRef Name; 38080b57cec5SDimitry Andric std::tie(Name, Record) = readNameFromStrtab(Record); 38090b57cec5SDimitry Andric 38100b57cec5SDimitry Andric if (Record.size() < 6) 38110b57cec5SDimitry Andric return error("Invalid record"); 381281ad6265SDimitry Andric unsigned TyID = Record[0]; 381381ad6265SDimitry Andric Type *Ty = getTypeByID(TyID); 38140b57cec5SDimitry Andric if (!Ty) 38150b57cec5SDimitry Andric return error("Invalid record"); 38160b57cec5SDimitry Andric bool isConstant = Record[1] & 1; 38170b57cec5SDimitry Andric bool explicitType = Record[1] & 2; 38180b57cec5SDimitry Andric unsigned AddressSpace; 38190b57cec5SDimitry Andric if (explicitType) { 38200b57cec5SDimitry Andric AddressSpace = Record[1] >> 2; 38210b57cec5SDimitry Andric } else { 38220b57cec5SDimitry Andric if (!Ty->isPointerTy()) 38230b57cec5SDimitry Andric return error("Invalid type for value"); 38240b57cec5SDimitry Andric AddressSpace = cast<PointerType>(Ty)->getAddressSpace(); 382581ad6265SDimitry Andric TyID = getContainedTypeID(TyID); 382681ad6265SDimitry Andric Ty = getTypeByID(TyID); 382781ad6265SDimitry Andric if (!Ty) 382881ad6265SDimitry Andric return error("Missing element type for old-style global"); 38290b57cec5SDimitry Andric } 38300b57cec5SDimitry Andric 38310b57cec5SDimitry Andric uint64_t RawLinkage = Record[3]; 38320b57cec5SDimitry Andric GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage); 38338bcb0991SDimitry Andric MaybeAlign Alignment; 38340b57cec5SDimitry Andric if (Error Err = parseAlignmentValue(Record[4], Alignment)) 38350b57cec5SDimitry Andric return Err; 38360b57cec5SDimitry Andric std::string Section; 38370b57cec5SDimitry Andric if (Record[5]) { 38380b57cec5SDimitry Andric if (Record[5] - 1 >= SectionTable.size()) 38390b57cec5SDimitry Andric return error("Invalid ID"); 38400b57cec5SDimitry Andric Section = SectionTable[Record[5] - 1]; 38410b57cec5SDimitry Andric } 38420b57cec5SDimitry Andric GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility; 38430b57cec5SDimitry Andric // Local linkage must have default visibility. 38445ffd83dbSDimitry Andric // auto-upgrade `hidden` and `protected` for old bitcode. 38450b57cec5SDimitry Andric if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage)) 38460b57cec5SDimitry Andric Visibility = getDecodedVisibility(Record[6]); 38470b57cec5SDimitry Andric 38480b57cec5SDimitry Andric GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal; 38490b57cec5SDimitry Andric if (Record.size() > 7) 38500b57cec5SDimitry Andric TLM = getDecodedThreadLocalMode(Record[7]); 38510b57cec5SDimitry Andric 38520b57cec5SDimitry Andric GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None; 38530b57cec5SDimitry Andric if (Record.size() > 8) 38540b57cec5SDimitry Andric UnnamedAddr = getDecodedUnnamedAddrType(Record[8]); 38550b57cec5SDimitry Andric 38560b57cec5SDimitry Andric bool ExternallyInitialized = false; 38570b57cec5SDimitry Andric if (Record.size() > 9) 38580b57cec5SDimitry Andric ExternallyInitialized = Record[9]; 38590b57cec5SDimitry Andric 38600b57cec5SDimitry Andric GlobalVariable *NewGV = 38610b57cec5SDimitry Andric new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, Name, 38620b57cec5SDimitry Andric nullptr, TLM, AddressSpace, ExternallyInitialized); 3863*fe013be4SDimitry Andric if (Alignment) 3864*fe013be4SDimitry Andric NewGV->setAlignment(*Alignment); 38650b57cec5SDimitry Andric if (!Section.empty()) 38660b57cec5SDimitry Andric NewGV->setSection(Section); 38670b57cec5SDimitry Andric NewGV->setVisibility(Visibility); 38680b57cec5SDimitry Andric NewGV->setUnnamedAddr(UnnamedAddr); 38690b57cec5SDimitry Andric 3870bdd1243dSDimitry Andric if (Record.size() > 10) { 3871bdd1243dSDimitry Andric // A GlobalValue with local linkage cannot have a DLL storage class. 3872bdd1243dSDimitry Andric if (!NewGV->hasLocalLinkage()) { 38730b57cec5SDimitry Andric NewGV->setDLLStorageClass(getDecodedDLLStorageClass(Record[10])); 3874bdd1243dSDimitry Andric } 3875bdd1243dSDimitry Andric } else { 38760b57cec5SDimitry Andric upgradeDLLImportExportLinkage(NewGV, RawLinkage); 3877bdd1243dSDimitry Andric } 38780b57cec5SDimitry Andric 387981ad6265SDimitry Andric ValueList.push_back(NewGV, getVirtualTypeID(NewGV->getType(), TyID)); 38800b57cec5SDimitry Andric 38810b57cec5SDimitry Andric // Remember which value to use for the global initializer. 38820b57cec5SDimitry Andric if (unsigned InitID = Record[2]) 38830b57cec5SDimitry Andric GlobalInits.push_back(std::make_pair(NewGV, InitID - 1)); 38840b57cec5SDimitry Andric 38850b57cec5SDimitry Andric if (Record.size() > 11) { 38860b57cec5SDimitry Andric if (unsigned ComdatID = Record[11]) { 38870b57cec5SDimitry Andric if (ComdatID > ComdatList.size()) 38880b57cec5SDimitry Andric return error("Invalid global variable comdat ID"); 38890b57cec5SDimitry Andric NewGV->setComdat(ComdatList[ComdatID - 1]); 38900b57cec5SDimitry Andric } 38910b57cec5SDimitry Andric } else if (hasImplicitComdat(RawLinkage)) { 38920eae32dcSDimitry Andric ImplicitComdatObjects.insert(NewGV); 38930b57cec5SDimitry Andric } 38940b57cec5SDimitry Andric 38950b57cec5SDimitry Andric if (Record.size() > 12) { 3896349cc55cSDimitry Andric auto AS = getAttributes(Record[12]).getFnAttrs(); 38970b57cec5SDimitry Andric NewGV->setAttributes(AS); 38980b57cec5SDimitry Andric } 38990b57cec5SDimitry Andric 39000b57cec5SDimitry Andric if (Record.size() > 13) { 39010b57cec5SDimitry Andric NewGV->setDSOLocal(getDecodedDSOLocal(Record[13])); 39020b57cec5SDimitry Andric } 39030b57cec5SDimitry Andric inferDSOLocal(NewGV); 39040b57cec5SDimitry Andric 39050b57cec5SDimitry Andric // Check whether we have enough values to read a partition name. 39060b57cec5SDimitry Andric if (Record.size() > 15) 39070b57cec5SDimitry Andric NewGV->setPartition(StringRef(Strtab.data() + Record[14], Record[15])); 39080b57cec5SDimitry Andric 390981ad6265SDimitry Andric if (Record.size() > 16 && Record[16]) { 391081ad6265SDimitry Andric llvm::GlobalValue::SanitizerMetadata Meta = 391181ad6265SDimitry Andric deserializeSanitizerMetadata(Record[16]); 391281ad6265SDimitry Andric NewGV->setSanitizerMetadata(Meta); 391381ad6265SDimitry Andric } 391481ad6265SDimitry Andric 39150b57cec5SDimitry Andric return Error::success(); 39160b57cec5SDimitry Andric } 39170b57cec5SDimitry Andric 3918bdd1243dSDimitry Andric void BitcodeReader::callValueTypeCallback(Value *F, unsigned TypeID) { 3919bdd1243dSDimitry Andric if (ValueTypeCallback) { 3920bdd1243dSDimitry Andric (*ValueTypeCallback)( 3921bdd1243dSDimitry Andric F, TypeID, [this](unsigned I) { return getTypeByID(I); }, 3922bdd1243dSDimitry Andric [this](unsigned I, unsigned J) { return getContainedTypeID(I, J); }); 3923bdd1243dSDimitry Andric } 3924bdd1243dSDimitry Andric } 3925bdd1243dSDimitry Andric 39260b57cec5SDimitry Andric Error BitcodeReader::parseFunctionRecord(ArrayRef<uint64_t> Record) { 39270b57cec5SDimitry Andric // v1: [type, callingconv, isproto, linkage, paramattr, alignment, section, 39280b57cec5SDimitry Andric // visibility, gc, unnamed_addr, prologuedata, dllstorageclass, comdat, 39290b57cec5SDimitry Andric // prefixdata, personalityfn, preemption specifier, addrspace] (name in VST) 39300b57cec5SDimitry Andric // v2: [strtab_offset, strtab_size, v1] 39310b57cec5SDimitry Andric StringRef Name; 39320b57cec5SDimitry Andric std::tie(Name, Record) = readNameFromStrtab(Record); 39330b57cec5SDimitry Andric 39340b57cec5SDimitry Andric if (Record.size() < 8) 39350b57cec5SDimitry Andric return error("Invalid record"); 393681ad6265SDimitry Andric unsigned FTyID = Record[0]; 393781ad6265SDimitry Andric Type *FTy = getTypeByID(FTyID); 39380b57cec5SDimitry Andric if (!FTy) 39390b57cec5SDimitry Andric return error("Invalid record"); 394081ad6265SDimitry Andric if (isa<PointerType>(FTy)) { 394181ad6265SDimitry Andric FTyID = getContainedTypeID(FTyID, 0); 394281ad6265SDimitry Andric FTy = getTypeByID(FTyID); 394381ad6265SDimitry Andric if (!FTy) 394481ad6265SDimitry Andric return error("Missing element type for old-style function"); 394581ad6265SDimitry Andric } 39460b57cec5SDimitry Andric 39470b57cec5SDimitry Andric if (!isa<FunctionType>(FTy)) 39480b57cec5SDimitry Andric return error("Invalid type for value"); 39490b57cec5SDimitry Andric auto CC = static_cast<CallingConv::ID>(Record[1]); 39500b57cec5SDimitry Andric if (CC & ~CallingConv::MaxID) 39510b57cec5SDimitry Andric return error("Invalid calling convention ID"); 39520b57cec5SDimitry Andric 39530b57cec5SDimitry Andric unsigned AddrSpace = TheModule->getDataLayout().getProgramAddressSpace(); 39540b57cec5SDimitry Andric if (Record.size() > 16) 39550b57cec5SDimitry Andric AddrSpace = Record[16]; 39560b57cec5SDimitry Andric 39570b57cec5SDimitry Andric Function *Func = 39580b57cec5SDimitry Andric Function::Create(cast<FunctionType>(FTy), GlobalValue::ExternalLinkage, 39590b57cec5SDimitry Andric AddrSpace, Name, TheModule); 39600b57cec5SDimitry Andric 3961fe6060f1SDimitry Andric assert(Func->getFunctionType() == FTy && 39620b57cec5SDimitry Andric "Incorrect fully specified type provided for function"); 396381ad6265SDimitry Andric FunctionTypeIDs[Func] = FTyID; 39640b57cec5SDimitry Andric 39650b57cec5SDimitry Andric Func->setCallingConv(CC); 39660b57cec5SDimitry Andric bool isProto = Record[2]; 39670b57cec5SDimitry Andric uint64_t RawLinkage = Record[3]; 39680b57cec5SDimitry Andric Func->setLinkage(getDecodedLinkage(RawLinkage)); 39690b57cec5SDimitry Andric Func->setAttributes(getAttributes(Record[4])); 3970bdd1243dSDimitry Andric callValueTypeCallback(Func, FTyID); 39710b57cec5SDimitry Andric 3972e8d8bef9SDimitry Andric // Upgrade any old-style byval or sret without a type by propagating the 3973e8d8bef9SDimitry Andric // argument's pointee type. There should be no opaque pointers where the byval 3974e8d8bef9SDimitry Andric // type is implicit. 39750b57cec5SDimitry Andric for (unsigned i = 0; i != Func->arg_size(); ++i) { 3976fe6060f1SDimitry Andric for (Attribute::AttrKind Kind : {Attribute::ByVal, Attribute::StructRet, 3977fe6060f1SDimitry Andric Attribute::InAlloca}) { 3978e8d8bef9SDimitry Andric if (!Func->hasParamAttribute(i, Kind)) 39790b57cec5SDimitry Andric continue; 39800b57cec5SDimitry Andric 3981fe6060f1SDimitry Andric if (Func->getParamAttribute(i, Kind).getValueAsType()) 3982fe6060f1SDimitry Andric continue; 3983fe6060f1SDimitry Andric 3984e8d8bef9SDimitry Andric Func->removeParamAttr(i, Kind); 3985e8d8bef9SDimitry Andric 398681ad6265SDimitry Andric unsigned ParamTypeID = getContainedTypeID(FTyID, i + 1); 398781ad6265SDimitry Andric Type *PtrEltTy = getPtrElementTypeByID(ParamTypeID); 398881ad6265SDimitry Andric if (!PtrEltTy) 398981ad6265SDimitry Andric return error("Missing param element type for attribute upgrade"); 399081ad6265SDimitry Andric 3991fe6060f1SDimitry Andric Attribute NewAttr; 3992fe6060f1SDimitry Andric switch (Kind) { 3993fe6060f1SDimitry Andric case Attribute::ByVal: 3994fe6060f1SDimitry Andric NewAttr = Attribute::getWithByValType(Context, PtrEltTy); 3995fe6060f1SDimitry Andric break; 3996fe6060f1SDimitry Andric case Attribute::StructRet: 3997fe6060f1SDimitry Andric NewAttr = Attribute::getWithStructRetType(Context, PtrEltTy); 3998fe6060f1SDimitry Andric break; 3999fe6060f1SDimitry Andric case Attribute::InAlloca: 4000fe6060f1SDimitry Andric NewAttr = Attribute::getWithInAllocaType(Context, PtrEltTy); 4001fe6060f1SDimitry Andric break; 4002fe6060f1SDimitry Andric default: 4003fe6060f1SDimitry Andric llvm_unreachable("not an upgraded type attribute"); 4004fe6060f1SDimitry Andric } 4005fe6060f1SDimitry Andric 4006e8d8bef9SDimitry Andric Func->addParamAttr(i, NewAttr); 4007e8d8bef9SDimitry Andric } 40080b57cec5SDimitry Andric } 40090b57cec5SDimitry Andric 401081ad6265SDimitry Andric if (Func->getCallingConv() == CallingConv::X86_INTR && 401181ad6265SDimitry Andric !Func->arg_empty() && !Func->hasParamAttribute(0, Attribute::ByVal)) { 401281ad6265SDimitry Andric unsigned ParamTypeID = getContainedTypeID(FTyID, 1); 401381ad6265SDimitry Andric Type *ByValTy = getPtrElementTypeByID(ParamTypeID); 401481ad6265SDimitry Andric if (!ByValTy) 401581ad6265SDimitry Andric return error("Missing param element type for x86_intrcc upgrade"); 401681ad6265SDimitry Andric Attribute NewAttr = Attribute::getWithByValType(Context, ByValTy); 401781ad6265SDimitry Andric Func->addParamAttr(0, NewAttr); 401881ad6265SDimitry Andric } 401981ad6265SDimitry Andric 40208bcb0991SDimitry Andric MaybeAlign Alignment; 40210b57cec5SDimitry Andric if (Error Err = parseAlignmentValue(Record[5], Alignment)) 40220b57cec5SDimitry Andric return Err; 4023*fe013be4SDimitry Andric if (Alignment) 4024*fe013be4SDimitry Andric Func->setAlignment(*Alignment); 40250b57cec5SDimitry Andric if (Record[6]) { 40260b57cec5SDimitry Andric if (Record[6] - 1 >= SectionTable.size()) 40270b57cec5SDimitry Andric return error("Invalid ID"); 40280b57cec5SDimitry Andric Func->setSection(SectionTable[Record[6] - 1]); 40290b57cec5SDimitry Andric } 40300b57cec5SDimitry Andric // Local linkage must have default visibility. 40315ffd83dbSDimitry Andric // auto-upgrade `hidden` and `protected` for old bitcode. 40320b57cec5SDimitry Andric if (!Func->hasLocalLinkage()) 40330b57cec5SDimitry Andric Func->setVisibility(getDecodedVisibility(Record[7])); 40340b57cec5SDimitry Andric if (Record.size() > 8 && Record[8]) { 40350b57cec5SDimitry Andric if (Record[8] - 1 >= GCTable.size()) 40360b57cec5SDimitry Andric return error("Invalid ID"); 40370b57cec5SDimitry Andric Func->setGC(GCTable[Record[8] - 1]); 40380b57cec5SDimitry Andric } 40390b57cec5SDimitry Andric GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None; 40400b57cec5SDimitry Andric if (Record.size() > 9) 40410b57cec5SDimitry Andric UnnamedAddr = getDecodedUnnamedAddrType(Record[9]); 40420b57cec5SDimitry Andric Func->setUnnamedAddr(UnnamedAddr); 4043349cc55cSDimitry Andric 4044349cc55cSDimitry Andric FunctionOperandInfo OperandInfo = {Func, 0, 0, 0}; 4045349cc55cSDimitry Andric if (Record.size() > 10) 4046349cc55cSDimitry Andric OperandInfo.Prologue = Record[10]; 40470b57cec5SDimitry Andric 4048bdd1243dSDimitry Andric if (Record.size() > 11) { 4049bdd1243dSDimitry Andric // A GlobalValue with local linkage cannot have a DLL storage class. 4050bdd1243dSDimitry Andric if (!Func->hasLocalLinkage()) { 40510b57cec5SDimitry Andric Func->setDLLStorageClass(getDecodedDLLStorageClass(Record[11])); 4052bdd1243dSDimitry Andric } 4053bdd1243dSDimitry Andric } else { 40540b57cec5SDimitry Andric upgradeDLLImportExportLinkage(Func, RawLinkage); 4055bdd1243dSDimitry Andric } 40560b57cec5SDimitry Andric 40570b57cec5SDimitry Andric if (Record.size() > 12) { 40580b57cec5SDimitry Andric if (unsigned ComdatID = Record[12]) { 40590b57cec5SDimitry Andric if (ComdatID > ComdatList.size()) 40600b57cec5SDimitry Andric return error("Invalid function comdat ID"); 40610b57cec5SDimitry Andric Func->setComdat(ComdatList[ComdatID - 1]); 40620b57cec5SDimitry Andric } 40630b57cec5SDimitry Andric } else if (hasImplicitComdat(RawLinkage)) { 40640eae32dcSDimitry Andric ImplicitComdatObjects.insert(Func); 40650b57cec5SDimitry Andric } 40660b57cec5SDimitry Andric 4067349cc55cSDimitry Andric if (Record.size() > 13) 4068349cc55cSDimitry Andric OperandInfo.Prefix = Record[13]; 40690b57cec5SDimitry Andric 4070349cc55cSDimitry Andric if (Record.size() > 14) 4071349cc55cSDimitry Andric OperandInfo.PersonalityFn = Record[14]; 40720b57cec5SDimitry Andric 40730b57cec5SDimitry Andric if (Record.size() > 15) { 40740b57cec5SDimitry Andric Func->setDSOLocal(getDecodedDSOLocal(Record[15])); 40750b57cec5SDimitry Andric } 40760b57cec5SDimitry Andric inferDSOLocal(Func); 40770b57cec5SDimitry Andric 40780b57cec5SDimitry Andric // Record[16] is the address space number. 40790b57cec5SDimitry Andric 4080fe6060f1SDimitry Andric // Check whether we have enough values to read a partition name. Also make 4081fe6060f1SDimitry Andric // sure Strtab has enough values. 4082fe6060f1SDimitry Andric if (Record.size() > 18 && Strtab.data() && 4083fe6060f1SDimitry Andric Record[17] + Record[18] <= Strtab.size()) { 40840b57cec5SDimitry Andric Func->setPartition(StringRef(Strtab.data() + Record[17], Record[18])); 4085fe6060f1SDimitry Andric } 40860b57cec5SDimitry Andric 408781ad6265SDimitry Andric ValueList.push_back(Func, getVirtualTypeID(Func->getType(), FTyID)); 40880b57cec5SDimitry Andric 4089349cc55cSDimitry Andric if (OperandInfo.PersonalityFn || OperandInfo.Prefix || OperandInfo.Prologue) 4090349cc55cSDimitry Andric FunctionOperands.push_back(OperandInfo); 4091349cc55cSDimitry Andric 40920b57cec5SDimitry Andric // If this is a function with a body, remember the prototype we are 40930b57cec5SDimitry Andric // creating now, so that we can match up the body with them later. 40940b57cec5SDimitry Andric if (!isProto) { 40950b57cec5SDimitry Andric Func->setIsMaterializable(true); 40960b57cec5SDimitry Andric FunctionsWithBodies.push_back(Func); 40970b57cec5SDimitry Andric DeferredFunctionInfo[Func] = 0; 40980b57cec5SDimitry Andric } 40990b57cec5SDimitry Andric return Error::success(); 41000b57cec5SDimitry Andric } 41010b57cec5SDimitry Andric 41020b57cec5SDimitry Andric Error BitcodeReader::parseGlobalIndirectSymbolRecord( 41030b57cec5SDimitry Andric unsigned BitCode, ArrayRef<uint64_t> Record) { 41040b57cec5SDimitry Andric // v1 ALIAS_OLD: [alias type, aliasee val#, linkage] (name in VST) 41050b57cec5SDimitry Andric // v1 ALIAS: [alias type, addrspace, aliasee val#, linkage, visibility, 41060b57cec5SDimitry Andric // dllstorageclass, threadlocal, unnamed_addr, 41070b57cec5SDimitry Andric // preemption specifier] (name in VST) 41080b57cec5SDimitry Andric // v1 IFUNC: [alias type, addrspace, aliasee val#, linkage, 41090b57cec5SDimitry Andric // visibility, dllstorageclass, threadlocal, unnamed_addr, 41100b57cec5SDimitry Andric // preemption specifier] (name in VST) 41110b57cec5SDimitry Andric // v2: [strtab_offset, strtab_size, v1] 41120b57cec5SDimitry Andric StringRef Name; 41130b57cec5SDimitry Andric std::tie(Name, Record) = readNameFromStrtab(Record); 41140b57cec5SDimitry Andric 41150b57cec5SDimitry Andric bool NewRecord = BitCode != bitc::MODULE_CODE_ALIAS_OLD; 41160b57cec5SDimitry Andric if (Record.size() < (3 + (unsigned)NewRecord)) 41170b57cec5SDimitry Andric return error("Invalid record"); 41180b57cec5SDimitry Andric unsigned OpNum = 0; 411981ad6265SDimitry Andric unsigned TypeID = Record[OpNum++]; 412081ad6265SDimitry Andric Type *Ty = getTypeByID(TypeID); 41210b57cec5SDimitry Andric if (!Ty) 41220b57cec5SDimitry Andric return error("Invalid record"); 41230b57cec5SDimitry Andric 41240b57cec5SDimitry Andric unsigned AddrSpace; 41250b57cec5SDimitry Andric if (!NewRecord) { 41260b57cec5SDimitry Andric auto *PTy = dyn_cast<PointerType>(Ty); 41270b57cec5SDimitry Andric if (!PTy) 41280b57cec5SDimitry Andric return error("Invalid type for value"); 41290b57cec5SDimitry Andric AddrSpace = PTy->getAddressSpace(); 413081ad6265SDimitry Andric TypeID = getContainedTypeID(TypeID); 413181ad6265SDimitry Andric Ty = getTypeByID(TypeID); 413281ad6265SDimitry Andric if (!Ty) 413381ad6265SDimitry Andric return error("Missing element type for old-style indirect symbol"); 41340b57cec5SDimitry Andric } else { 41350b57cec5SDimitry Andric AddrSpace = Record[OpNum++]; 41360b57cec5SDimitry Andric } 41370b57cec5SDimitry Andric 41380b57cec5SDimitry Andric auto Val = Record[OpNum++]; 41390b57cec5SDimitry Andric auto Linkage = Record[OpNum++]; 4140349cc55cSDimitry Andric GlobalValue *NewGA; 41410b57cec5SDimitry Andric if (BitCode == bitc::MODULE_CODE_ALIAS || 41420b57cec5SDimitry Andric BitCode == bitc::MODULE_CODE_ALIAS_OLD) 41430b57cec5SDimitry Andric NewGA = GlobalAlias::create(Ty, AddrSpace, getDecodedLinkage(Linkage), Name, 41440b57cec5SDimitry Andric TheModule); 41450b57cec5SDimitry Andric else 41460b57cec5SDimitry Andric NewGA = GlobalIFunc::create(Ty, AddrSpace, getDecodedLinkage(Linkage), Name, 41470b57cec5SDimitry Andric nullptr, TheModule); 41480b57cec5SDimitry Andric 41490b57cec5SDimitry Andric // Local linkage must have default visibility. 41505ffd83dbSDimitry Andric // auto-upgrade `hidden` and `protected` for old bitcode. 41510b57cec5SDimitry Andric if (OpNum != Record.size()) { 41520b57cec5SDimitry Andric auto VisInd = OpNum++; 41530b57cec5SDimitry Andric if (!NewGA->hasLocalLinkage()) 41540b57cec5SDimitry Andric NewGA->setVisibility(getDecodedVisibility(Record[VisInd])); 41550b57cec5SDimitry Andric } 41560b57cec5SDimitry Andric if (BitCode == bitc::MODULE_CODE_ALIAS || 41570b57cec5SDimitry Andric BitCode == bitc::MODULE_CODE_ALIAS_OLD) { 4158bdd1243dSDimitry Andric if (OpNum != Record.size()) { 4159bdd1243dSDimitry Andric auto S = Record[OpNum++]; 4160bdd1243dSDimitry Andric // A GlobalValue with local linkage cannot have a DLL storage class. 4161bdd1243dSDimitry Andric if (!NewGA->hasLocalLinkage()) 4162bdd1243dSDimitry Andric NewGA->setDLLStorageClass(getDecodedDLLStorageClass(S)); 4163bdd1243dSDimitry Andric } 41640b57cec5SDimitry Andric else 41650b57cec5SDimitry Andric upgradeDLLImportExportLinkage(NewGA, Linkage); 41660b57cec5SDimitry Andric if (OpNum != Record.size()) 41670b57cec5SDimitry Andric NewGA->setThreadLocalMode(getDecodedThreadLocalMode(Record[OpNum++])); 41680b57cec5SDimitry Andric if (OpNum != Record.size()) 41690b57cec5SDimitry Andric NewGA->setUnnamedAddr(getDecodedUnnamedAddrType(Record[OpNum++])); 41700b57cec5SDimitry Andric } 41710b57cec5SDimitry Andric if (OpNum != Record.size()) 41720b57cec5SDimitry Andric NewGA->setDSOLocal(getDecodedDSOLocal(Record[OpNum++])); 41730b57cec5SDimitry Andric inferDSOLocal(NewGA); 41740b57cec5SDimitry Andric 41750b57cec5SDimitry Andric // Check whether we have enough values to read a partition name. 41760b57cec5SDimitry Andric if (OpNum + 1 < Record.size()) { 41770b57cec5SDimitry Andric NewGA->setPartition( 41780b57cec5SDimitry Andric StringRef(Strtab.data() + Record[OpNum], Record[OpNum + 1])); 41790b57cec5SDimitry Andric OpNum += 2; 41800b57cec5SDimitry Andric } 41810b57cec5SDimitry Andric 418281ad6265SDimitry Andric ValueList.push_back(NewGA, getVirtualTypeID(NewGA->getType(), TypeID)); 41830b57cec5SDimitry Andric IndirectSymbolInits.push_back(std::make_pair(NewGA, Val)); 41840b57cec5SDimitry Andric return Error::success(); 41850b57cec5SDimitry Andric } 41860b57cec5SDimitry Andric 41870b57cec5SDimitry Andric Error BitcodeReader::parseModule(uint64_t ResumeBit, 41885ffd83dbSDimitry Andric bool ShouldLazyLoadMetadata, 4189bdd1243dSDimitry Andric ParserCallbacks Callbacks) { 4190bdd1243dSDimitry Andric this->ValueTypeCallback = std::move(Callbacks.ValueType); 41910b57cec5SDimitry Andric if (ResumeBit) { 41920b57cec5SDimitry Andric if (Error JumpFailed = Stream.JumpToBit(ResumeBit)) 41930b57cec5SDimitry Andric return JumpFailed; 41940b57cec5SDimitry Andric } else if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID)) 41950b57cec5SDimitry Andric return Err; 41960b57cec5SDimitry Andric 41970b57cec5SDimitry Andric SmallVector<uint64_t, 64> Record; 41980b57cec5SDimitry Andric 41995ffd83dbSDimitry Andric // Parts of bitcode parsing depend on the datalayout. Make sure we 42005ffd83dbSDimitry Andric // finalize the datalayout before we run any of that code. 42015ffd83dbSDimitry Andric bool ResolvedDataLayout = false; 4202bdd1243dSDimitry Andric // In order to support importing modules with illegal data layout strings, 4203bdd1243dSDimitry Andric // delay parsing the data layout string until after upgrades and overrides 4204bdd1243dSDimitry Andric // have been applied, allowing to fix illegal data layout strings. 4205bdd1243dSDimitry Andric // Initialize to the current module's layout string in case none is specified. 4206bdd1243dSDimitry Andric std::string TentativeDataLayoutStr = TheModule->getDataLayoutStr(); 42075ffd83dbSDimitry Andric 4208bdd1243dSDimitry Andric auto ResolveDataLayout = [&]() -> Error { 4209bdd1243dSDimitry Andric if (ResolvedDataLayout) 4210bdd1243dSDimitry Andric return Error::success(); 4211bdd1243dSDimitry Andric 4212bdd1243dSDimitry Andric // Datalayout and triple can't be parsed after this point. 42135ffd83dbSDimitry Andric ResolvedDataLayout = true; 42145ffd83dbSDimitry Andric 4215bdd1243dSDimitry Andric // Auto-upgrade the layout string 4216bdd1243dSDimitry Andric TentativeDataLayoutStr = llvm::UpgradeDataLayoutString( 4217bdd1243dSDimitry Andric TentativeDataLayoutStr, TheModule->getTargetTriple()); 42185ffd83dbSDimitry Andric 4219bdd1243dSDimitry Andric // Apply override 4220bdd1243dSDimitry Andric if (Callbacks.DataLayout) { 4221bdd1243dSDimitry Andric if (auto LayoutOverride = (*Callbacks.DataLayout)( 4222bdd1243dSDimitry Andric TheModule->getTargetTriple(), TentativeDataLayoutStr)) 4223bdd1243dSDimitry Andric TentativeDataLayoutStr = *LayoutOverride; 4224bdd1243dSDimitry Andric } 4225bdd1243dSDimitry Andric 4226bdd1243dSDimitry Andric // Now the layout string is finalized in TentativeDataLayoutStr. Parse it. 4227bdd1243dSDimitry Andric Expected<DataLayout> MaybeDL = DataLayout::parse(TentativeDataLayoutStr); 4228bdd1243dSDimitry Andric if (!MaybeDL) 4229bdd1243dSDimitry Andric return MaybeDL.takeError(); 4230bdd1243dSDimitry Andric 4231bdd1243dSDimitry Andric TheModule->setDataLayout(MaybeDL.get()); 4232bdd1243dSDimitry Andric return Error::success(); 42335ffd83dbSDimitry Andric }; 42345ffd83dbSDimitry Andric 42350b57cec5SDimitry Andric // Read all the records for this module. 42360b57cec5SDimitry Andric while (true) { 42370b57cec5SDimitry Andric Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance(); 42380b57cec5SDimitry Andric if (!MaybeEntry) 42390b57cec5SDimitry Andric return MaybeEntry.takeError(); 42400b57cec5SDimitry Andric llvm::BitstreamEntry Entry = MaybeEntry.get(); 42410b57cec5SDimitry Andric 42420b57cec5SDimitry Andric switch (Entry.Kind) { 42430b57cec5SDimitry Andric case BitstreamEntry::Error: 42440b57cec5SDimitry Andric return error("Malformed block"); 42450b57cec5SDimitry Andric case BitstreamEntry::EndBlock: 4246bdd1243dSDimitry Andric if (Error Err = ResolveDataLayout()) 4247bdd1243dSDimitry Andric return Err; 42480b57cec5SDimitry Andric return globalCleanup(); 42490b57cec5SDimitry Andric 42500b57cec5SDimitry Andric case BitstreamEntry::SubBlock: 42510b57cec5SDimitry Andric switch (Entry.ID) { 42520b57cec5SDimitry Andric default: // Skip unknown content. 42530b57cec5SDimitry Andric if (Error Err = Stream.SkipBlock()) 42540b57cec5SDimitry Andric return Err; 42550b57cec5SDimitry Andric break; 42560b57cec5SDimitry Andric case bitc::BLOCKINFO_BLOCK_ID: 425781ad6265SDimitry Andric if (Error Err = readBlockInfo()) 425881ad6265SDimitry Andric return Err; 42590b57cec5SDimitry Andric break; 42600b57cec5SDimitry Andric case bitc::PARAMATTR_BLOCK_ID: 42610b57cec5SDimitry Andric if (Error Err = parseAttributeBlock()) 42620b57cec5SDimitry Andric return Err; 42630b57cec5SDimitry Andric break; 42640b57cec5SDimitry Andric case bitc::PARAMATTR_GROUP_BLOCK_ID: 42650b57cec5SDimitry Andric if (Error Err = parseAttributeGroupBlock()) 42660b57cec5SDimitry Andric return Err; 42670b57cec5SDimitry Andric break; 42680b57cec5SDimitry Andric case bitc::TYPE_BLOCK_ID_NEW: 42690b57cec5SDimitry Andric if (Error Err = parseTypeTable()) 42700b57cec5SDimitry Andric return Err; 42710b57cec5SDimitry Andric break; 42720b57cec5SDimitry Andric case bitc::VALUE_SYMTAB_BLOCK_ID: 42730b57cec5SDimitry Andric if (!SeenValueSymbolTable) { 42740b57cec5SDimitry Andric // Either this is an old form VST without function index and an 42750b57cec5SDimitry Andric // associated VST forward declaration record (which would have caused 42760b57cec5SDimitry Andric // the VST to be jumped to and parsed before it was encountered 42770b57cec5SDimitry Andric // normally in the stream), or there were no function blocks to 42780b57cec5SDimitry Andric // trigger an earlier parsing of the VST. 42790b57cec5SDimitry Andric assert(VSTOffset == 0 || FunctionsWithBodies.empty()); 42800b57cec5SDimitry Andric if (Error Err = parseValueSymbolTable()) 42810b57cec5SDimitry Andric return Err; 42820b57cec5SDimitry Andric SeenValueSymbolTable = true; 42830b57cec5SDimitry Andric } else { 42840b57cec5SDimitry Andric // We must have had a VST forward declaration record, which caused 42850b57cec5SDimitry Andric // the parser to jump to and parse the VST earlier. 42860b57cec5SDimitry Andric assert(VSTOffset > 0); 42870b57cec5SDimitry Andric if (Error Err = Stream.SkipBlock()) 42880b57cec5SDimitry Andric return Err; 42890b57cec5SDimitry Andric } 42900b57cec5SDimitry Andric break; 42910b57cec5SDimitry Andric case bitc::CONSTANTS_BLOCK_ID: 42920b57cec5SDimitry Andric if (Error Err = parseConstants()) 42930b57cec5SDimitry Andric return Err; 42940b57cec5SDimitry Andric if (Error Err = resolveGlobalAndIndirectSymbolInits()) 42950b57cec5SDimitry Andric return Err; 42960b57cec5SDimitry Andric break; 42970b57cec5SDimitry Andric case bitc::METADATA_BLOCK_ID: 42980b57cec5SDimitry Andric if (ShouldLazyLoadMetadata) { 42990b57cec5SDimitry Andric if (Error Err = rememberAndSkipMetadata()) 43000b57cec5SDimitry Andric return Err; 43010b57cec5SDimitry Andric break; 43020b57cec5SDimitry Andric } 43030b57cec5SDimitry Andric assert(DeferredMetadataInfo.empty() && "Unexpected deferred metadata"); 43040b57cec5SDimitry Andric if (Error Err = MDLoader->parseModuleMetadata()) 43050b57cec5SDimitry Andric return Err; 43060b57cec5SDimitry Andric break; 43070b57cec5SDimitry Andric case bitc::METADATA_KIND_BLOCK_ID: 43080b57cec5SDimitry Andric if (Error Err = MDLoader->parseMetadataKinds()) 43090b57cec5SDimitry Andric return Err; 43100b57cec5SDimitry Andric break; 43110b57cec5SDimitry Andric case bitc::FUNCTION_BLOCK_ID: 4312bdd1243dSDimitry Andric if (Error Err = ResolveDataLayout()) 4313bdd1243dSDimitry Andric return Err; 43145ffd83dbSDimitry Andric 43150b57cec5SDimitry Andric // If this is the first function body we've seen, reverse the 43160b57cec5SDimitry Andric // FunctionsWithBodies list. 43170b57cec5SDimitry Andric if (!SeenFirstFunctionBody) { 43180b57cec5SDimitry Andric std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end()); 43190b57cec5SDimitry Andric if (Error Err = globalCleanup()) 43200b57cec5SDimitry Andric return Err; 43210b57cec5SDimitry Andric SeenFirstFunctionBody = true; 43220b57cec5SDimitry Andric } 43230b57cec5SDimitry Andric 43240b57cec5SDimitry Andric if (VSTOffset > 0) { 43250b57cec5SDimitry Andric // If we have a VST forward declaration record, make sure we 43260b57cec5SDimitry Andric // parse the VST now if we haven't already. It is needed to 43270b57cec5SDimitry Andric // set up the DeferredFunctionInfo vector for lazy reading. 43280b57cec5SDimitry Andric if (!SeenValueSymbolTable) { 43290b57cec5SDimitry Andric if (Error Err = BitcodeReader::parseValueSymbolTable(VSTOffset)) 43300b57cec5SDimitry Andric return Err; 43310b57cec5SDimitry Andric SeenValueSymbolTable = true; 43320b57cec5SDimitry Andric // Fall through so that we record the NextUnreadBit below. 43330b57cec5SDimitry Andric // This is necessary in case we have an anonymous function that 43340b57cec5SDimitry Andric // is later materialized. Since it will not have a VST entry we 43350b57cec5SDimitry Andric // need to fall back to the lazy parse to find its offset. 43360b57cec5SDimitry Andric } else { 43370b57cec5SDimitry Andric // If we have a VST forward declaration record, but have already 43380b57cec5SDimitry Andric // parsed the VST (just above, when the first function body was 43390b57cec5SDimitry Andric // encountered here), then we are resuming the parse after 43400b57cec5SDimitry Andric // materializing functions. The ResumeBit points to the 43410b57cec5SDimitry Andric // start of the last function block recorded in the 43420b57cec5SDimitry Andric // DeferredFunctionInfo map. Skip it. 43430b57cec5SDimitry Andric if (Error Err = Stream.SkipBlock()) 43440b57cec5SDimitry Andric return Err; 43450b57cec5SDimitry Andric continue; 43460b57cec5SDimitry Andric } 43470b57cec5SDimitry Andric } 43480b57cec5SDimitry Andric 43490b57cec5SDimitry Andric // Support older bitcode files that did not have the function 43500b57cec5SDimitry Andric // index in the VST, nor a VST forward declaration record, as 43510b57cec5SDimitry Andric // well as anonymous functions that do not have VST entries. 43520b57cec5SDimitry Andric // Build the DeferredFunctionInfo vector on the fly. 43530b57cec5SDimitry Andric if (Error Err = rememberAndSkipFunctionBody()) 43540b57cec5SDimitry Andric return Err; 43550b57cec5SDimitry Andric 43560b57cec5SDimitry Andric // Suspend parsing when we reach the function bodies. Subsequent 43570b57cec5SDimitry Andric // materialization calls will resume it when necessary. If the bitcode 43580b57cec5SDimitry Andric // file is old, the symbol table will be at the end instead and will not 43590b57cec5SDimitry Andric // have been seen yet. In this case, just finish the parse now. 43600b57cec5SDimitry Andric if (SeenValueSymbolTable) { 43610b57cec5SDimitry Andric NextUnreadBit = Stream.GetCurrentBitNo(); 43620b57cec5SDimitry Andric // After the VST has been parsed, we need to make sure intrinsic name 43630b57cec5SDimitry Andric // are auto-upgraded. 43640b57cec5SDimitry Andric return globalCleanup(); 43650b57cec5SDimitry Andric } 43660b57cec5SDimitry Andric break; 43670b57cec5SDimitry Andric case bitc::USELIST_BLOCK_ID: 43680b57cec5SDimitry Andric if (Error Err = parseUseLists()) 43690b57cec5SDimitry Andric return Err; 43700b57cec5SDimitry Andric break; 43710b57cec5SDimitry Andric case bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID: 43720b57cec5SDimitry Andric if (Error Err = parseOperandBundleTags()) 43730b57cec5SDimitry Andric return Err; 43740b57cec5SDimitry Andric break; 43750b57cec5SDimitry Andric case bitc::SYNC_SCOPE_NAMES_BLOCK_ID: 43760b57cec5SDimitry Andric if (Error Err = parseSyncScopeNames()) 43770b57cec5SDimitry Andric return Err; 43780b57cec5SDimitry Andric break; 43790b57cec5SDimitry Andric } 43800b57cec5SDimitry Andric continue; 43810b57cec5SDimitry Andric 43820b57cec5SDimitry Andric case BitstreamEntry::Record: 43830b57cec5SDimitry Andric // The interesting case. 43840b57cec5SDimitry Andric break; 43850b57cec5SDimitry Andric } 43860b57cec5SDimitry Andric 43870b57cec5SDimitry Andric // Read a record. 43880b57cec5SDimitry Andric Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record); 43890b57cec5SDimitry Andric if (!MaybeBitCode) 43900b57cec5SDimitry Andric return MaybeBitCode.takeError(); 43910b57cec5SDimitry Andric switch (unsigned BitCode = MaybeBitCode.get()) { 43920b57cec5SDimitry Andric default: break; // Default behavior, ignore unknown content. 43930b57cec5SDimitry Andric case bitc::MODULE_CODE_VERSION: { 43940b57cec5SDimitry Andric Expected<unsigned> VersionOrErr = parseVersionRecord(Record); 43950b57cec5SDimitry Andric if (!VersionOrErr) 43960b57cec5SDimitry Andric return VersionOrErr.takeError(); 43970b57cec5SDimitry Andric UseRelativeIDs = *VersionOrErr >= 1; 43980b57cec5SDimitry Andric break; 43990b57cec5SDimitry Andric } 44000b57cec5SDimitry Andric case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N] 44015ffd83dbSDimitry Andric if (ResolvedDataLayout) 44025ffd83dbSDimitry Andric return error("target triple too late in module"); 44030b57cec5SDimitry Andric std::string S; 44040b57cec5SDimitry Andric if (convertToString(Record, 0, S)) 44050b57cec5SDimitry Andric return error("Invalid record"); 44060b57cec5SDimitry Andric TheModule->setTargetTriple(S); 44070b57cec5SDimitry Andric break; 44080b57cec5SDimitry Andric } 44090b57cec5SDimitry Andric case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N] 44105ffd83dbSDimitry Andric if (ResolvedDataLayout) 44115ffd83dbSDimitry Andric return error("datalayout too late in module"); 4412bdd1243dSDimitry Andric if (convertToString(Record, 0, TentativeDataLayoutStr)) 44130b57cec5SDimitry Andric return error("Invalid record"); 44140b57cec5SDimitry Andric break; 44150b57cec5SDimitry Andric } 44160b57cec5SDimitry Andric case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N] 44170b57cec5SDimitry Andric std::string S; 44180b57cec5SDimitry Andric if (convertToString(Record, 0, S)) 44190b57cec5SDimitry Andric return error("Invalid record"); 44200b57cec5SDimitry Andric TheModule->setModuleInlineAsm(S); 44210b57cec5SDimitry Andric break; 44220b57cec5SDimitry Andric } 44230b57cec5SDimitry Andric case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N] 44245ffd83dbSDimitry Andric // Deprecated, but still needed to read old bitcode files. 44250b57cec5SDimitry Andric std::string S; 44260b57cec5SDimitry Andric if (convertToString(Record, 0, S)) 44270b57cec5SDimitry Andric return error("Invalid record"); 44280b57cec5SDimitry Andric // Ignore value. 44290b57cec5SDimitry Andric break; 44300b57cec5SDimitry Andric } 44310b57cec5SDimitry Andric case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N] 44320b57cec5SDimitry Andric std::string S; 44330b57cec5SDimitry Andric if (convertToString(Record, 0, S)) 44340b57cec5SDimitry Andric return error("Invalid record"); 44350b57cec5SDimitry Andric SectionTable.push_back(S); 44360b57cec5SDimitry Andric break; 44370b57cec5SDimitry Andric } 44380b57cec5SDimitry Andric case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N] 44390b57cec5SDimitry Andric std::string S; 44400b57cec5SDimitry Andric if (convertToString(Record, 0, S)) 44410b57cec5SDimitry Andric return error("Invalid record"); 44420b57cec5SDimitry Andric GCTable.push_back(S); 44430b57cec5SDimitry Andric break; 44440b57cec5SDimitry Andric } 44450b57cec5SDimitry Andric case bitc::MODULE_CODE_COMDAT: 44460b57cec5SDimitry Andric if (Error Err = parseComdatRecord(Record)) 44470b57cec5SDimitry Andric return Err; 44480b57cec5SDimitry Andric break; 444904eeddc0SDimitry Andric // FIXME: BitcodeReader should handle {GLOBALVAR, FUNCTION, ALIAS, IFUNC} 445004eeddc0SDimitry Andric // written by ThinLinkBitcodeWriter. See 445104eeddc0SDimitry Andric // `ThinLinkBitcodeWriter::writeSimplifiedModuleInfo` for the format of each 445204eeddc0SDimitry Andric // record 445304eeddc0SDimitry Andric // (https://github.com/llvm/llvm-project/blob/b6a93967d9c11e79802b5e75cec1584d6c8aa472/llvm/lib/Bitcode/Writer/BitcodeWriter.cpp#L4714) 44540b57cec5SDimitry Andric case bitc::MODULE_CODE_GLOBALVAR: 44550b57cec5SDimitry Andric if (Error Err = parseGlobalVarRecord(Record)) 44560b57cec5SDimitry Andric return Err; 44570b57cec5SDimitry Andric break; 44580b57cec5SDimitry Andric case bitc::MODULE_CODE_FUNCTION: 4459bdd1243dSDimitry Andric if (Error Err = ResolveDataLayout()) 4460bdd1243dSDimitry Andric return Err; 44610b57cec5SDimitry Andric if (Error Err = parseFunctionRecord(Record)) 44620b57cec5SDimitry Andric return Err; 44630b57cec5SDimitry Andric break; 44640b57cec5SDimitry Andric case bitc::MODULE_CODE_IFUNC: 44650b57cec5SDimitry Andric case bitc::MODULE_CODE_ALIAS: 44660b57cec5SDimitry Andric case bitc::MODULE_CODE_ALIAS_OLD: 44670b57cec5SDimitry Andric if (Error Err = parseGlobalIndirectSymbolRecord(BitCode, Record)) 44680b57cec5SDimitry Andric return Err; 44690b57cec5SDimitry Andric break; 44700b57cec5SDimitry Andric /// MODULE_CODE_VSTOFFSET: [offset] 44710b57cec5SDimitry Andric case bitc::MODULE_CODE_VSTOFFSET: 4472e8d8bef9SDimitry Andric if (Record.empty()) 44730b57cec5SDimitry Andric return error("Invalid record"); 44740b57cec5SDimitry Andric // Note that we subtract 1 here because the offset is relative to one word 44750b57cec5SDimitry Andric // before the start of the identification or module block, which was 44760b57cec5SDimitry Andric // historically always the start of the regular bitcode header. 44770b57cec5SDimitry Andric VSTOffset = Record[0] - 1; 44780b57cec5SDimitry Andric break; 44790b57cec5SDimitry Andric /// MODULE_CODE_SOURCE_FILENAME: [namechar x N] 44800b57cec5SDimitry Andric case bitc::MODULE_CODE_SOURCE_FILENAME: 44810b57cec5SDimitry Andric SmallString<128> ValueName; 44820b57cec5SDimitry Andric if (convertToString(Record, 0, ValueName)) 44830b57cec5SDimitry Andric return error("Invalid record"); 44840b57cec5SDimitry Andric TheModule->setSourceFileName(ValueName); 44850b57cec5SDimitry Andric break; 44860b57cec5SDimitry Andric } 44870b57cec5SDimitry Andric Record.clear(); 44880b57cec5SDimitry Andric } 4489bdd1243dSDimitry Andric this->ValueTypeCallback = std::nullopt; 4490bdd1243dSDimitry Andric return Error::success(); 44910b57cec5SDimitry Andric } 44920b57cec5SDimitry Andric 44930b57cec5SDimitry Andric Error BitcodeReader::parseBitcodeInto(Module *M, bool ShouldLazyLoadMetadata, 44945ffd83dbSDimitry Andric bool IsImporting, 4495bdd1243dSDimitry Andric ParserCallbacks Callbacks) { 44960b57cec5SDimitry Andric TheModule = M; 4497bdd1243dSDimitry Andric MetadataLoaderCallbacks MDCallbacks; 4498bdd1243dSDimitry Andric MDCallbacks.GetTypeByID = [&](unsigned ID) { return getTypeByID(ID); }; 4499bdd1243dSDimitry Andric MDCallbacks.GetContainedTypeID = [&](unsigned I, unsigned J) { 4500bdd1243dSDimitry Andric return getContainedTypeID(I, J); 4501bdd1243dSDimitry Andric }; 4502bdd1243dSDimitry Andric MDCallbacks.MDType = Callbacks.MDType; 4503bdd1243dSDimitry Andric MDLoader = MetadataLoader(Stream, *M, ValueList, IsImporting, MDCallbacks); 4504bdd1243dSDimitry Andric return parseModule(0, ShouldLazyLoadMetadata, Callbacks); 45050b57cec5SDimitry Andric } 45060b57cec5SDimitry Andric 45070b57cec5SDimitry Andric Error BitcodeReader::typeCheckLoadStoreInst(Type *ValType, Type *PtrType) { 45080b57cec5SDimitry Andric if (!isa<PointerType>(PtrType)) 45090b57cec5SDimitry Andric return error("Load/Store operand is not a pointer type"); 4510fe6060f1SDimitry Andric if (!PointerType::isLoadableOrStorableType(ValType)) 45110b57cec5SDimitry Andric return error("Cannot load/store from pointer"); 45120b57cec5SDimitry Andric return Error::success(); 45130b57cec5SDimitry Andric } 45140b57cec5SDimitry Andric 451581ad6265SDimitry Andric Error BitcodeReader::propagateAttributeTypes(CallBase *CB, 451681ad6265SDimitry Andric ArrayRef<unsigned> ArgTyIDs) { 451781ad6265SDimitry Andric AttributeList Attrs = CB->getAttributes(); 45180b57cec5SDimitry Andric for (unsigned i = 0; i != CB->arg_size(); ++i) { 4519fe6060f1SDimitry Andric for (Attribute::AttrKind Kind : {Attribute::ByVal, Attribute::StructRet, 4520fe6060f1SDimitry Andric Attribute::InAlloca}) { 452181ad6265SDimitry Andric if (!Attrs.hasParamAttr(i, Kind) || 452281ad6265SDimitry Andric Attrs.getParamAttr(i, Kind).getValueAsType()) 45230b57cec5SDimitry Andric continue; 45240b57cec5SDimitry Andric 452581ad6265SDimitry Andric Type *PtrEltTy = getPtrElementTypeByID(ArgTyIDs[i]); 452681ad6265SDimitry Andric if (!PtrEltTy) 452781ad6265SDimitry Andric return error("Missing element type for typed attribute upgrade"); 4528e8d8bef9SDimitry Andric 4529fe6060f1SDimitry Andric Attribute NewAttr; 4530fe6060f1SDimitry Andric switch (Kind) { 4531fe6060f1SDimitry Andric case Attribute::ByVal: 4532fe6060f1SDimitry Andric NewAttr = Attribute::getWithByValType(Context, PtrEltTy); 4533fe6060f1SDimitry Andric break; 4534fe6060f1SDimitry Andric case Attribute::StructRet: 4535fe6060f1SDimitry Andric NewAttr = Attribute::getWithStructRetType(Context, PtrEltTy); 4536fe6060f1SDimitry Andric break; 4537fe6060f1SDimitry Andric case Attribute::InAlloca: 4538fe6060f1SDimitry Andric NewAttr = Attribute::getWithInAllocaType(Context, PtrEltTy); 4539fe6060f1SDimitry Andric break; 4540fe6060f1SDimitry Andric default: 4541fe6060f1SDimitry Andric llvm_unreachable("not an upgraded type attribute"); 4542fe6060f1SDimitry Andric } 4543fe6060f1SDimitry Andric 454481ad6265SDimitry Andric Attrs = Attrs.addParamAttribute(Context, i, NewAttr); 4545e8d8bef9SDimitry Andric } 45460b57cec5SDimitry Andric } 4547fe6060f1SDimitry Andric 454804eeddc0SDimitry Andric if (CB->isInlineAsm()) { 454904eeddc0SDimitry Andric const InlineAsm *IA = cast<InlineAsm>(CB->getCalledOperand()); 455004eeddc0SDimitry Andric unsigned ArgNo = 0; 455104eeddc0SDimitry Andric for (const InlineAsm::ConstraintInfo &CI : IA->ParseConstraints()) { 455204eeddc0SDimitry Andric if (!CI.hasArg()) 455304eeddc0SDimitry Andric continue; 455404eeddc0SDimitry Andric 455581ad6265SDimitry Andric if (CI.isIndirect && !Attrs.getParamElementType(ArgNo)) { 455681ad6265SDimitry Andric Type *ElemTy = getPtrElementTypeByID(ArgTyIDs[ArgNo]); 455781ad6265SDimitry Andric if (!ElemTy) 455881ad6265SDimitry Andric return error("Missing element type for inline asm upgrade"); 455981ad6265SDimitry Andric Attrs = Attrs.addParamAttribute( 456081ad6265SDimitry Andric Context, ArgNo, 456181ad6265SDimitry Andric Attribute::get(Context, Attribute::ElementType, ElemTy)); 456204eeddc0SDimitry Andric } 456304eeddc0SDimitry Andric 456404eeddc0SDimitry Andric ArgNo++; 456504eeddc0SDimitry Andric } 456604eeddc0SDimitry Andric } 456704eeddc0SDimitry Andric 4568fe6060f1SDimitry Andric switch (CB->getIntrinsicID()) { 4569fe6060f1SDimitry Andric case Intrinsic::preserve_array_access_index: 4570fe6060f1SDimitry Andric case Intrinsic::preserve_struct_access_index: 457181ad6265SDimitry Andric case Intrinsic::aarch64_ldaxr: 457281ad6265SDimitry Andric case Intrinsic::aarch64_ldxr: 457381ad6265SDimitry Andric case Intrinsic::aarch64_stlxr: 457481ad6265SDimitry Andric case Intrinsic::aarch64_stxr: 457581ad6265SDimitry Andric case Intrinsic::arm_ldaex: 457681ad6265SDimitry Andric case Intrinsic::arm_ldrex: 457781ad6265SDimitry Andric case Intrinsic::arm_stlex: 457881ad6265SDimitry Andric case Intrinsic::arm_strex: { 457981ad6265SDimitry Andric unsigned ArgNo; 458081ad6265SDimitry Andric switch (CB->getIntrinsicID()) { 458181ad6265SDimitry Andric case Intrinsic::aarch64_stlxr: 458281ad6265SDimitry Andric case Intrinsic::aarch64_stxr: 458381ad6265SDimitry Andric case Intrinsic::arm_stlex: 458481ad6265SDimitry Andric case Intrinsic::arm_strex: 458581ad6265SDimitry Andric ArgNo = 1; 458681ad6265SDimitry Andric break; 458781ad6265SDimitry Andric default: 458881ad6265SDimitry Andric ArgNo = 0; 458981ad6265SDimitry Andric break; 459081ad6265SDimitry Andric } 459181ad6265SDimitry Andric if (!Attrs.getParamElementType(ArgNo)) { 459281ad6265SDimitry Andric Type *ElTy = getPtrElementTypeByID(ArgTyIDs[ArgNo]); 459381ad6265SDimitry Andric if (!ElTy) 459481ad6265SDimitry Andric return error("Missing element type for elementtype upgrade"); 4595fe6060f1SDimitry Andric Attribute NewAttr = Attribute::get(Context, Attribute::ElementType, ElTy); 459681ad6265SDimitry Andric Attrs = Attrs.addParamAttribute(Context, ArgNo, NewAttr); 4597fe6060f1SDimitry Andric } 4598fe6060f1SDimitry Andric break; 459981ad6265SDimitry Andric } 4600fe6060f1SDimitry Andric default: 4601fe6060f1SDimitry Andric break; 4602fe6060f1SDimitry Andric } 460381ad6265SDimitry Andric 460481ad6265SDimitry Andric CB->setAttributes(Attrs); 460581ad6265SDimitry Andric return Error::success(); 46060b57cec5SDimitry Andric } 46070b57cec5SDimitry Andric 46080b57cec5SDimitry Andric /// Lazily parse the specified function body block. 46090b57cec5SDimitry Andric Error BitcodeReader::parseFunctionBody(Function *F) { 46100b57cec5SDimitry Andric if (Error Err = Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID)) 46110b57cec5SDimitry Andric return Err; 46120b57cec5SDimitry Andric 46130b57cec5SDimitry Andric // Unexpected unresolved metadata when parsing function. 46140b57cec5SDimitry Andric if (MDLoader->hasFwdRefs()) 46150b57cec5SDimitry Andric return error("Invalid function metadata: incoming forward references"); 46160b57cec5SDimitry Andric 46170b57cec5SDimitry Andric InstructionList.clear(); 46180b57cec5SDimitry Andric unsigned ModuleValueListSize = ValueList.size(); 46190b57cec5SDimitry Andric unsigned ModuleMDLoaderSize = MDLoader->size(); 46200b57cec5SDimitry Andric 46210b57cec5SDimitry Andric // Add all the function arguments to the value table. 46220b57cec5SDimitry Andric unsigned ArgNo = 0; 462381ad6265SDimitry Andric unsigned FTyID = FunctionTypeIDs[F]; 46240b57cec5SDimitry Andric for (Argument &I : F->args()) { 462581ad6265SDimitry Andric unsigned ArgTyID = getContainedTypeID(FTyID, ArgNo + 1); 462681ad6265SDimitry Andric assert(I.getType() == getTypeByID(ArgTyID) && 46270b57cec5SDimitry Andric "Incorrect fully specified type for Function Argument"); 462881ad6265SDimitry Andric ValueList.push_back(&I, ArgTyID); 462981ad6265SDimitry Andric ++ArgNo; 46300b57cec5SDimitry Andric } 46310b57cec5SDimitry Andric unsigned NextValueNo = ValueList.size(); 46320b57cec5SDimitry Andric BasicBlock *CurBB = nullptr; 46330b57cec5SDimitry Andric unsigned CurBBNo = 0; 463481ad6265SDimitry Andric // Block into which constant expressions from phi nodes are materialized. 463581ad6265SDimitry Andric BasicBlock *PhiConstExprBB = nullptr; 463681ad6265SDimitry Andric // Edge blocks for phi nodes into which constant expressions have been 463781ad6265SDimitry Andric // expanded. 463881ad6265SDimitry Andric SmallMapVector<std::pair<BasicBlock *, BasicBlock *>, BasicBlock *, 4> 463981ad6265SDimitry Andric ConstExprEdgeBBs; 46400b57cec5SDimitry Andric 46410b57cec5SDimitry Andric DebugLoc LastLoc; 46420b57cec5SDimitry Andric auto getLastInstruction = [&]() -> Instruction * { 46430b57cec5SDimitry Andric if (CurBB && !CurBB->empty()) 46440b57cec5SDimitry Andric return &CurBB->back(); 46450b57cec5SDimitry Andric else if (CurBBNo && FunctionBBs[CurBBNo - 1] && 46460b57cec5SDimitry Andric !FunctionBBs[CurBBNo - 1]->empty()) 46470b57cec5SDimitry Andric return &FunctionBBs[CurBBNo - 1]->back(); 46480b57cec5SDimitry Andric return nullptr; 46490b57cec5SDimitry Andric }; 46500b57cec5SDimitry Andric 46510b57cec5SDimitry Andric std::vector<OperandBundleDef> OperandBundles; 46520b57cec5SDimitry Andric 46530b57cec5SDimitry Andric // Read all the records. 46540b57cec5SDimitry Andric SmallVector<uint64_t, 64> Record; 46550b57cec5SDimitry Andric 46560b57cec5SDimitry Andric while (true) { 46570b57cec5SDimitry Andric Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance(); 46580b57cec5SDimitry Andric if (!MaybeEntry) 46590b57cec5SDimitry Andric return MaybeEntry.takeError(); 46600b57cec5SDimitry Andric llvm::BitstreamEntry Entry = MaybeEntry.get(); 46610b57cec5SDimitry Andric 46620b57cec5SDimitry Andric switch (Entry.Kind) { 46630b57cec5SDimitry Andric case BitstreamEntry::Error: 46640b57cec5SDimitry Andric return error("Malformed block"); 46650b57cec5SDimitry Andric case BitstreamEntry::EndBlock: 46660b57cec5SDimitry Andric goto OutOfRecordLoop; 46670b57cec5SDimitry Andric 46680b57cec5SDimitry Andric case BitstreamEntry::SubBlock: 46690b57cec5SDimitry Andric switch (Entry.ID) { 46700b57cec5SDimitry Andric default: // Skip unknown content. 46710b57cec5SDimitry Andric if (Error Err = Stream.SkipBlock()) 46720b57cec5SDimitry Andric return Err; 46730b57cec5SDimitry Andric break; 46740b57cec5SDimitry Andric case bitc::CONSTANTS_BLOCK_ID: 46750b57cec5SDimitry Andric if (Error Err = parseConstants()) 46760b57cec5SDimitry Andric return Err; 46770b57cec5SDimitry Andric NextValueNo = ValueList.size(); 46780b57cec5SDimitry Andric break; 46790b57cec5SDimitry Andric case bitc::VALUE_SYMTAB_BLOCK_ID: 46800b57cec5SDimitry Andric if (Error Err = parseValueSymbolTable()) 46810b57cec5SDimitry Andric return Err; 46820b57cec5SDimitry Andric break; 46830b57cec5SDimitry Andric case bitc::METADATA_ATTACHMENT_ID: 46840b57cec5SDimitry Andric if (Error Err = MDLoader->parseMetadataAttachment(*F, InstructionList)) 46850b57cec5SDimitry Andric return Err; 46860b57cec5SDimitry Andric break; 46870b57cec5SDimitry Andric case bitc::METADATA_BLOCK_ID: 46880b57cec5SDimitry Andric assert(DeferredMetadataInfo.empty() && 46890b57cec5SDimitry Andric "Must read all module-level metadata before function-level"); 46900b57cec5SDimitry Andric if (Error Err = MDLoader->parseFunctionMetadata()) 46910b57cec5SDimitry Andric return Err; 46920b57cec5SDimitry Andric break; 46930b57cec5SDimitry Andric case bitc::USELIST_BLOCK_ID: 46940b57cec5SDimitry Andric if (Error Err = parseUseLists()) 46950b57cec5SDimitry Andric return Err; 46960b57cec5SDimitry Andric break; 46970b57cec5SDimitry Andric } 46980b57cec5SDimitry Andric continue; 46990b57cec5SDimitry Andric 47000b57cec5SDimitry Andric case BitstreamEntry::Record: 47010b57cec5SDimitry Andric // The interesting case. 47020b57cec5SDimitry Andric break; 47030b57cec5SDimitry Andric } 47040b57cec5SDimitry Andric 47050b57cec5SDimitry Andric // Read a record. 47060b57cec5SDimitry Andric Record.clear(); 47070b57cec5SDimitry Andric Instruction *I = nullptr; 470881ad6265SDimitry Andric unsigned ResTypeID = InvalidTypeID; 47090b57cec5SDimitry Andric Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record); 47100b57cec5SDimitry Andric if (!MaybeBitCode) 47110b57cec5SDimitry Andric return MaybeBitCode.takeError(); 47120b57cec5SDimitry Andric switch (unsigned BitCode = MaybeBitCode.get()) { 47130b57cec5SDimitry Andric default: // Default behavior: reject 47140b57cec5SDimitry Andric return error("Invalid value"); 47150b57cec5SDimitry Andric case bitc::FUNC_CODE_DECLAREBLOCKS: { // DECLAREBLOCKS: [nblocks] 4716e8d8bef9SDimitry Andric if (Record.empty() || Record[0] == 0) 47170b57cec5SDimitry Andric return error("Invalid record"); 47180b57cec5SDimitry Andric // Create all the basic blocks for the function. 47190b57cec5SDimitry Andric FunctionBBs.resize(Record[0]); 47200b57cec5SDimitry Andric 47210b57cec5SDimitry Andric // See if anything took the address of blocks in this function. 47220b57cec5SDimitry Andric auto BBFRI = BasicBlockFwdRefs.find(F); 47230b57cec5SDimitry Andric if (BBFRI == BasicBlockFwdRefs.end()) { 47244824e7fdSDimitry Andric for (BasicBlock *&BB : FunctionBBs) 47254824e7fdSDimitry Andric BB = BasicBlock::Create(Context, "", F); 47260b57cec5SDimitry Andric } else { 47270b57cec5SDimitry Andric auto &BBRefs = BBFRI->second; 47280b57cec5SDimitry Andric // Check for invalid basic block references. 47290b57cec5SDimitry Andric if (BBRefs.size() > FunctionBBs.size()) 47300b57cec5SDimitry Andric return error("Invalid ID"); 47310b57cec5SDimitry Andric assert(!BBRefs.empty() && "Unexpected empty array"); 47320b57cec5SDimitry Andric assert(!BBRefs.front() && "Invalid reference to entry block"); 47330b57cec5SDimitry Andric for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E; 47340b57cec5SDimitry Andric ++I) 47350b57cec5SDimitry Andric if (I < RE && BBRefs[I]) { 47360b57cec5SDimitry Andric BBRefs[I]->insertInto(F); 47370b57cec5SDimitry Andric FunctionBBs[I] = BBRefs[I]; 47380b57cec5SDimitry Andric } else { 47390b57cec5SDimitry Andric FunctionBBs[I] = BasicBlock::Create(Context, "", F); 47400b57cec5SDimitry Andric } 47410b57cec5SDimitry Andric 47420b57cec5SDimitry Andric // Erase from the table. 47430b57cec5SDimitry Andric BasicBlockFwdRefs.erase(BBFRI); 47440b57cec5SDimitry Andric } 47450b57cec5SDimitry Andric 47460b57cec5SDimitry Andric CurBB = FunctionBBs[0]; 47470b57cec5SDimitry Andric continue; 47480b57cec5SDimitry Andric } 47490b57cec5SDimitry Andric 475081ad6265SDimitry Andric case bitc::FUNC_CODE_BLOCKADDR_USERS: // BLOCKADDR_USERS: [vals...] 475181ad6265SDimitry Andric // The record should not be emitted if it's an empty list. 475281ad6265SDimitry Andric if (Record.empty()) 475381ad6265SDimitry Andric return error("Invalid record"); 475481ad6265SDimitry Andric // When we have the RARE case of a BlockAddress Constant that is not 475581ad6265SDimitry Andric // scoped to the Function it refers to, we need to conservatively 475681ad6265SDimitry Andric // materialize the referred to Function, regardless of whether or not 475781ad6265SDimitry Andric // that Function will ultimately be linked, otherwise users of 475881ad6265SDimitry Andric // BitcodeReader might start splicing out Function bodies such that we 475981ad6265SDimitry Andric // might no longer be able to materialize the BlockAddress since the 476081ad6265SDimitry Andric // BasicBlock (and entire body of the Function) the BlockAddress refers 476181ad6265SDimitry Andric // to may have been moved. In the case that the user of BitcodeReader 476281ad6265SDimitry Andric // decides ultimately not to link the Function body, materializing here 476381ad6265SDimitry Andric // could be considered wasteful, but it's better than a deserialization 476481ad6265SDimitry Andric // failure as described. This keeps BitcodeReader unaware of complex 476581ad6265SDimitry Andric // linkage policy decisions such as those use by LTO, leaving those 476681ad6265SDimitry Andric // decisions "one layer up." 476781ad6265SDimitry Andric for (uint64_t ValID : Record) 476881ad6265SDimitry Andric if (auto *F = dyn_cast<Function>(ValueList[ValID])) 476981ad6265SDimitry Andric BackwardRefFunctions.push_back(F); 477081ad6265SDimitry Andric else 477181ad6265SDimitry Andric return error("Invalid record"); 477281ad6265SDimitry Andric 477381ad6265SDimitry Andric continue; 477481ad6265SDimitry Andric 47750b57cec5SDimitry Andric case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN 47760b57cec5SDimitry Andric // This record indicates that the last instruction is at the same 47770b57cec5SDimitry Andric // location as the previous instruction with a location. 47780b57cec5SDimitry Andric I = getLastInstruction(); 47790b57cec5SDimitry Andric 47800b57cec5SDimitry Andric if (!I) 47810b57cec5SDimitry Andric return error("Invalid record"); 47820b57cec5SDimitry Andric I->setDebugLoc(LastLoc); 47830b57cec5SDimitry Andric I = nullptr; 47840b57cec5SDimitry Andric continue; 47850b57cec5SDimitry Andric 47860b57cec5SDimitry Andric case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia] 47870b57cec5SDimitry Andric I = getLastInstruction(); 47880b57cec5SDimitry Andric if (!I || Record.size() < 4) 47890b57cec5SDimitry Andric return error("Invalid record"); 47900b57cec5SDimitry Andric 47910b57cec5SDimitry Andric unsigned Line = Record[0], Col = Record[1]; 47920b57cec5SDimitry Andric unsigned ScopeID = Record[2], IAID = Record[3]; 47930b57cec5SDimitry Andric bool isImplicitCode = Record.size() == 5 && Record[4]; 47940b57cec5SDimitry Andric 47950b57cec5SDimitry Andric MDNode *Scope = nullptr, *IA = nullptr; 47960b57cec5SDimitry Andric if (ScopeID) { 47970b57cec5SDimitry Andric Scope = dyn_cast_or_null<MDNode>( 47980b57cec5SDimitry Andric MDLoader->getMetadataFwdRefOrLoad(ScopeID - 1)); 47990b57cec5SDimitry Andric if (!Scope) 48000b57cec5SDimitry Andric return error("Invalid record"); 48010b57cec5SDimitry Andric } 48020b57cec5SDimitry Andric if (IAID) { 48030b57cec5SDimitry Andric IA = dyn_cast_or_null<MDNode>( 48040b57cec5SDimitry Andric MDLoader->getMetadataFwdRefOrLoad(IAID - 1)); 48050b57cec5SDimitry Andric if (!IA) 48060b57cec5SDimitry Andric return error("Invalid record"); 48070b57cec5SDimitry Andric } 4808e8d8bef9SDimitry Andric LastLoc = DILocation::get(Scope->getContext(), Line, Col, Scope, IA, 4809e8d8bef9SDimitry Andric isImplicitCode); 48100b57cec5SDimitry Andric I->setDebugLoc(LastLoc); 48110b57cec5SDimitry Andric I = nullptr; 48120b57cec5SDimitry Andric continue; 48130b57cec5SDimitry Andric } 48140b57cec5SDimitry Andric case bitc::FUNC_CODE_INST_UNOP: { // UNOP: [opval, ty, opcode] 48150b57cec5SDimitry Andric unsigned OpNum = 0; 48160b57cec5SDimitry Andric Value *LHS; 481781ad6265SDimitry Andric unsigned TypeID; 481881ad6265SDimitry Andric if (getValueTypePair(Record, OpNum, NextValueNo, LHS, TypeID, CurBB) || 48190b57cec5SDimitry Andric OpNum+1 > Record.size()) 48200b57cec5SDimitry Andric return error("Invalid record"); 48210b57cec5SDimitry Andric 48220b57cec5SDimitry Andric int Opc = getDecodedUnaryOpcode(Record[OpNum++], LHS->getType()); 48230b57cec5SDimitry Andric if (Opc == -1) 48240b57cec5SDimitry Andric return error("Invalid record"); 48250b57cec5SDimitry Andric I = UnaryOperator::Create((Instruction::UnaryOps)Opc, LHS); 482681ad6265SDimitry Andric ResTypeID = TypeID; 48270b57cec5SDimitry Andric InstructionList.push_back(I); 48280b57cec5SDimitry Andric if (OpNum < Record.size()) { 48290b57cec5SDimitry Andric if (isa<FPMathOperator>(I)) { 48300b57cec5SDimitry Andric FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]); 48310b57cec5SDimitry Andric if (FMF.any()) 48320b57cec5SDimitry Andric I->setFastMathFlags(FMF); 48330b57cec5SDimitry Andric } 48340b57cec5SDimitry Andric } 48350b57cec5SDimitry Andric break; 48360b57cec5SDimitry Andric } 48370b57cec5SDimitry Andric case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode] 48380b57cec5SDimitry Andric unsigned OpNum = 0; 48390b57cec5SDimitry Andric Value *LHS, *RHS; 484081ad6265SDimitry Andric unsigned TypeID; 484181ad6265SDimitry Andric if (getValueTypePair(Record, OpNum, NextValueNo, LHS, TypeID, CurBB) || 484281ad6265SDimitry Andric popValue(Record, OpNum, NextValueNo, LHS->getType(), TypeID, RHS, 484381ad6265SDimitry Andric CurBB) || 48440b57cec5SDimitry Andric OpNum+1 > Record.size()) 48450b57cec5SDimitry Andric return error("Invalid record"); 48460b57cec5SDimitry Andric 48470b57cec5SDimitry Andric int Opc = getDecodedBinaryOpcode(Record[OpNum++], LHS->getType()); 48480b57cec5SDimitry Andric if (Opc == -1) 48490b57cec5SDimitry Andric return error("Invalid record"); 48500b57cec5SDimitry Andric I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS); 485181ad6265SDimitry Andric ResTypeID = TypeID; 48520b57cec5SDimitry Andric InstructionList.push_back(I); 48530b57cec5SDimitry Andric if (OpNum < Record.size()) { 48540b57cec5SDimitry Andric if (Opc == Instruction::Add || 48550b57cec5SDimitry Andric Opc == Instruction::Sub || 48560b57cec5SDimitry Andric Opc == Instruction::Mul || 48570b57cec5SDimitry Andric Opc == Instruction::Shl) { 48580b57cec5SDimitry Andric if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP)) 48590b57cec5SDimitry Andric cast<BinaryOperator>(I)->setHasNoSignedWrap(true); 48600b57cec5SDimitry Andric if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP)) 48610b57cec5SDimitry Andric cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true); 48620b57cec5SDimitry Andric } else if (Opc == Instruction::SDiv || 48630b57cec5SDimitry Andric Opc == Instruction::UDiv || 48640b57cec5SDimitry Andric Opc == Instruction::LShr || 48650b57cec5SDimitry Andric Opc == Instruction::AShr) { 48660b57cec5SDimitry Andric if (Record[OpNum] & (1 << bitc::PEO_EXACT)) 48670b57cec5SDimitry Andric cast<BinaryOperator>(I)->setIsExact(true); 48680b57cec5SDimitry Andric } else if (isa<FPMathOperator>(I)) { 48690b57cec5SDimitry Andric FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]); 48700b57cec5SDimitry Andric if (FMF.any()) 48710b57cec5SDimitry Andric I->setFastMathFlags(FMF); 48720b57cec5SDimitry Andric } 48730b57cec5SDimitry Andric 48740b57cec5SDimitry Andric } 48750b57cec5SDimitry Andric break; 48760b57cec5SDimitry Andric } 48770b57cec5SDimitry Andric case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc] 48780b57cec5SDimitry Andric unsigned OpNum = 0; 48790b57cec5SDimitry Andric Value *Op; 488081ad6265SDimitry Andric unsigned OpTypeID; 488181ad6265SDimitry Andric if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB) || 48820b57cec5SDimitry Andric OpNum+2 != Record.size()) 48830b57cec5SDimitry Andric return error("Invalid record"); 48840b57cec5SDimitry Andric 488581ad6265SDimitry Andric ResTypeID = Record[OpNum]; 488681ad6265SDimitry Andric Type *ResTy = getTypeByID(ResTypeID); 48870b57cec5SDimitry Andric int Opc = getDecodedCastOpcode(Record[OpNum + 1]); 48880b57cec5SDimitry Andric if (Opc == -1 || !ResTy) 48890b57cec5SDimitry Andric return error("Invalid record"); 48900b57cec5SDimitry Andric Instruction *Temp = nullptr; 48910b57cec5SDimitry Andric if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) { 48920b57cec5SDimitry Andric if (Temp) { 48930b57cec5SDimitry Andric InstructionList.push_back(Temp); 4894480093f4SDimitry Andric assert(CurBB && "No current BB?"); 4895bdd1243dSDimitry Andric Temp->insertInto(CurBB, CurBB->end()); 48960b57cec5SDimitry Andric } 48970b57cec5SDimitry Andric } else { 48980b57cec5SDimitry Andric auto CastOp = (Instruction::CastOps)Opc; 48990b57cec5SDimitry Andric if (!CastInst::castIsValid(CastOp, Op, ResTy)) 49000b57cec5SDimitry Andric return error("Invalid cast"); 49010b57cec5SDimitry Andric I = CastInst::Create(CastOp, Op, ResTy); 49020b57cec5SDimitry Andric } 49030b57cec5SDimitry Andric InstructionList.push_back(I); 49040b57cec5SDimitry Andric break; 49050b57cec5SDimitry Andric } 49060b57cec5SDimitry Andric case bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD: 49070b57cec5SDimitry Andric case bitc::FUNC_CODE_INST_GEP_OLD: 49080b57cec5SDimitry Andric case bitc::FUNC_CODE_INST_GEP: { // GEP: type, [n x operands] 49090b57cec5SDimitry Andric unsigned OpNum = 0; 49100b57cec5SDimitry Andric 491181ad6265SDimitry Andric unsigned TyID; 49120b57cec5SDimitry Andric Type *Ty; 49130b57cec5SDimitry Andric bool InBounds; 49140b57cec5SDimitry Andric 49150b57cec5SDimitry Andric if (BitCode == bitc::FUNC_CODE_INST_GEP) { 49160b57cec5SDimitry Andric InBounds = Record[OpNum++]; 491781ad6265SDimitry Andric TyID = Record[OpNum++]; 491881ad6265SDimitry Andric Ty = getTypeByID(TyID); 49190b57cec5SDimitry Andric } else { 49200b57cec5SDimitry Andric InBounds = BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD; 492181ad6265SDimitry Andric TyID = InvalidTypeID; 49220b57cec5SDimitry Andric Ty = nullptr; 49230b57cec5SDimitry Andric } 49240b57cec5SDimitry Andric 49250b57cec5SDimitry Andric Value *BasePtr; 492681ad6265SDimitry Andric unsigned BasePtrTypeID; 492781ad6265SDimitry Andric if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr, BasePtrTypeID, 492881ad6265SDimitry Andric CurBB)) 49290b57cec5SDimitry Andric return error("Invalid record"); 49300b57cec5SDimitry Andric 49310b57cec5SDimitry Andric if (!Ty) { 493281ad6265SDimitry Andric TyID = getContainedTypeID(BasePtrTypeID); 493381ad6265SDimitry Andric if (BasePtr->getType()->isVectorTy()) 493481ad6265SDimitry Andric TyID = getContainedTypeID(TyID); 493581ad6265SDimitry Andric Ty = getTypeByID(TyID); 4936fe6060f1SDimitry Andric } 49370b57cec5SDimitry Andric 49380b57cec5SDimitry Andric SmallVector<Value*, 16> GEPIdx; 49390b57cec5SDimitry Andric while (OpNum != Record.size()) { 49400b57cec5SDimitry Andric Value *Op; 494181ad6265SDimitry Andric unsigned OpTypeID; 494281ad6265SDimitry Andric if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB)) 49430b57cec5SDimitry Andric return error("Invalid record"); 49440b57cec5SDimitry Andric GEPIdx.push_back(Op); 49450b57cec5SDimitry Andric } 49460b57cec5SDimitry Andric 49470b57cec5SDimitry Andric I = GetElementPtrInst::Create(Ty, BasePtr, GEPIdx); 49480b57cec5SDimitry Andric 494981ad6265SDimitry Andric ResTypeID = TyID; 495081ad6265SDimitry Andric if (cast<GEPOperator>(I)->getNumIndices() != 0) { 495181ad6265SDimitry Andric auto GTI = std::next(gep_type_begin(I)); 495281ad6265SDimitry Andric for (Value *Idx : drop_begin(cast<GEPOperator>(I)->indices())) { 495381ad6265SDimitry Andric unsigned SubType = 0; 495481ad6265SDimitry Andric if (GTI.isStruct()) { 495581ad6265SDimitry Andric ConstantInt *IdxC = 495681ad6265SDimitry Andric Idx->getType()->isVectorTy() 495781ad6265SDimitry Andric ? cast<ConstantInt>(cast<Constant>(Idx)->getSplatValue()) 495881ad6265SDimitry Andric : cast<ConstantInt>(Idx); 495981ad6265SDimitry Andric SubType = IdxC->getZExtValue(); 496081ad6265SDimitry Andric } 496181ad6265SDimitry Andric ResTypeID = getContainedTypeID(ResTypeID, SubType); 496281ad6265SDimitry Andric ++GTI; 496381ad6265SDimitry Andric } 496481ad6265SDimitry Andric } 496581ad6265SDimitry Andric 496681ad6265SDimitry Andric // At this point ResTypeID is the result element type. We need a pointer 496781ad6265SDimitry Andric // or vector of pointer to it. 496881ad6265SDimitry Andric ResTypeID = getVirtualTypeID(I->getType()->getScalarType(), ResTypeID); 496981ad6265SDimitry Andric if (I->getType()->isVectorTy()) 497081ad6265SDimitry Andric ResTypeID = getVirtualTypeID(I->getType(), ResTypeID); 497181ad6265SDimitry Andric 49720b57cec5SDimitry Andric InstructionList.push_back(I); 49730b57cec5SDimitry Andric if (InBounds) 49740b57cec5SDimitry Andric cast<GetElementPtrInst>(I)->setIsInBounds(true); 49750b57cec5SDimitry Andric break; 49760b57cec5SDimitry Andric } 49770b57cec5SDimitry Andric 49780b57cec5SDimitry Andric case bitc::FUNC_CODE_INST_EXTRACTVAL: { 49790b57cec5SDimitry Andric // EXTRACTVAL: [opty, opval, n x indices] 49800b57cec5SDimitry Andric unsigned OpNum = 0; 49810b57cec5SDimitry Andric Value *Agg; 498281ad6265SDimitry Andric unsigned AggTypeID; 498381ad6265SDimitry Andric if (getValueTypePair(Record, OpNum, NextValueNo, Agg, AggTypeID, CurBB)) 49840b57cec5SDimitry Andric return error("Invalid record"); 4985fe6060f1SDimitry Andric Type *Ty = Agg->getType(); 49860b57cec5SDimitry Andric 49870b57cec5SDimitry Andric unsigned RecSize = Record.size(); 49880b57cec5SDimitry Andric if (OpNum == RecSize) 49890b57cec5SDimitry Andric return error("EXTRACTVAL: Invalid instruction with 0 indices"); 49900b57cec5SDimitry Andric 49910b57cec5SDimitry Andric SmallVector<unsigned, 4> EXTRACTVALIdx; 499281ad6265SDimitry Andric ResTypeID = AggTypeID; 49930b57cec5SDimitry Andric for (; OpNum != RecSize; ++OpNum) { 4994fe6060f1SDimitry Andric bool IsArray = Ty->isArrayTy(); 4995fe6060f1SDimitry Andric bool IsStruct = Ty->isStructTy(); 49960b57cec5SDimitry Andric uint64_t Index = Record[OpNum]; 49970b57cec5SDimitry Andric 49980b57cec5SDimitry Andric if (!IsStruct && !IsArray) 49990b57cec5SDimitry Andric return error("EXTRACTVAL: Invalid type"); 50000b57cec5SDimitry Andric if ((unsigned)Index != Index) 50010b57cec5SDimitry Andric return error("Invalid value"); 5002fe6060f1SDimitry Andric if (IsStruct && Index >= Ty->getStructNumElements()) 50030b57cec5SDimitry Andric return error("EXTRACTVAL: Invalid struct index"); 5004fe6060f1SDimitry Andric if (IsArray && Index >= Ty->getArrayNumElements()) 50050b57cec5SDimitry Andric return error("EXTRACTVAL: Invalid array index"); 50060b57cec5SDimitry Andric EXTRACTVALIdx.push_back((unsigned)Index); 50070b57cec5SDimitry Andric 500881ad6265SDimitry Andric if (IsStruct) { 5009fe6060f1SDimitry Andric Ty = Ty->getStructElementType(Index); 501081ad6265SDimitry Andric ResTypeID = getContainedTypeID(ResTypeID, Index); 501181ad6265SDimitry Andric } else { 5012fe6060f1SDimitry Andric Ty = Ty->getArrayElementType(); 501381ad6265SDimitry Andric ResTypeID = getContainedTypeID(ResTypeID); 501481ad6265SDimitry Andric } 50150b57cec5SDimitry Andric } 50160b57cec5SDimitry Andric 50170b57cec5SDimitry Andric I = ExtractValueInst::Create(Agg, EXTRACTVALIdx); 50180b57cec5SDimitry Andric InstructionList.push_back(I); 50190b57cec5SDimitry Andric break; 50200b57cec5SDimitry Andric } 50210b57cec5SDimitry Andric 50220b57cec5SDimitry Andric case bitc::FUNC_CODE_INST_INSERTVAL: { 50230b57cec5SDimitry Andric // INSERTVAL: [opty, opval, opty, opval, n x indices] 50240b57cec5SDimitry Andric unsigned OpNum = 0; 50250b57cec5SDimitry Andric Value *Agg; 502681ad6265SDimitry Andric unsigned AggTypeID; 502781ad6265SDimitry Andric if (getValueTypePair(Record, OpNum, NextValueNo, Agg, AggTypeID, CurBB)) 50280b57cec5SDimitry Andric return error("Invalid record"); 50290b57cec5SDimitry Andric Value *Val; 503081ad6265SDimitry Andric unsigned ValTypeID; 503181ad6265SDimitry Andric if (getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID, CurBB)) 50320b57cec5SDimitry Andric return error("Invalid record"); 50330b57cec5SDimitry Andric 50340b57cec5SDimitry Andric unsigned RecSize = Record.size(); 50350b57cec5SDimitry Andric if (OpNum == RecSize) 50360b57cec5SDimitry Andric return error("INSERTVAL: Invalid instruction with 0 indices"); 50370b57cec5SDimitry Andric 50380b57cec5SDimitry Andric SmallVector<unsigned, 4> INSERTVALIdx; 50390b57cec5SDimitry Andric Type *CurTy = Agg->getType(); 50400b57cec5SDimitry Andric for (; OpNum != RecSize; ++OpNum) { 50410b57cec5SDimitry Andric bool IsArray = CurTy->isArrayTy(); 50420b57cec5SDimitry Andric bool IsStruct = CurTy->isStructTy(); 50430b57cec5SDimitry Andric uint64_t Index = Record[OpNum]; 50440b57cec5SDimitry Andric 50450b57cec5SDimitry Andric if (!IsStruct && !IsArray) 50460b57cec5SDimitry Andric return error("INSERTVAL: Invalid type"); 50470b57cec5SDimitry Andric if ((unsigned)Index != Index) 50480b57cec5SDimitry Andric return error("Invalid value"); 50490b57cec5SDimitry Andric if (IsStruct && Index >= CurTy->getStructNumElements()) 50500b57cec5SDimitry Andric return error("INSERTVAL: Invalid struct index"); 50510b57cec5SDimitry Andric if (IsArray && Index >= CurTy->getArrayNumElements()) 50520b57cec5SDimitry Andric return error("INSERTVAL: Invalid array index"); 50530b57cec5SDimitry Andric 50540b57cec5SDimitry Andric INSERTVALIdx.push_back((unsigned)Index); 50550b57cec5SDimitry Andric if (IsStruct) 50560b57cec5SDimitry Andric CurTy = CurTy->getStructElementType(Index); 50570b57cec5SDimitry Andric else 50580b57cec5SDimitry Andric CurTy = CurTy->getArrayElementType(); 50590b57cec5SDimitry Andric } 50600b57cec5SDimitry Andric 50610b57cec5SDimitry Andric if (CurTy != Val->getType()) 50620b57cec5SDimitry Andric return error("Inserted value type doesn't match aggregate type"); 50630b57cec5SDimitry Andric 50640b57cec5SDimitry Andric I = InsertValueInst::Create(Agg, Val, INSERTVALIdx); 506581ad6265SDimitry Andric ResTypeID = AggTypeID; 50660b57cec5SDimitry Andric InstructionList.push_back(I); 50670b57cec5SDimitry Andric break; 50680b57cec5SDimitry Andric } 50690b57cec5SDimitry Andric 50700b57cec5SDimitry Andric case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval] 50710b57cec5SDimitry Andric // obsolete form of select 50720b57cec5SDimitry Andric // handles select i1 ... in old bitcode 50730b57cec5SDimitry Andric unsigned OpNum = 0; 50740b57cec5SDimitry Andric Value *TrueVal, *FalseVal, *Cond; 507581ad6265SDimitry Andric unsigned TypeID; 507681ad6265SDimitry Andric Type *CondType = Type::getInt1Ty(Context); 507781ad6265SDimitry Andric if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal, TypeID, 507881ad6265SDimitry Andric CurBB) || 507981ad6265SDimitry Andric popValue(Record, OpNum, NextValueNo, TrueVal->getType(), TypeID, 508081ad6265SDimitry Andric FalseVal, CurBB) || 508181ad6265SDimitry Andric popValue(Record, OpNum, NextValueNo, CondType, 508281ad6265SDimitry Andric getVirtualTypeID(CondType), Cond, CurBB)) 50830b57cec5SDimitry Andric return error("Invalid record"); 50840b57cec5SDimitry Andric 50850b57cec5SDimitry Andric I = SelectInst::Create(Cond, TrueVal, FalseVal); 508681ad6265SDimitry Andric ResTypeID = TypeID; 50870b57cec5SDimitry Andric InstructionList.push_back(I); 50880b57cec5SDimitry Andric break; 50890b57cec5SDimitry Andric } 50900b57cec5SDimitry Andric 50910b57cec5SDimitry Andric case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred] 50920b57cec5SDimitry Andric // new form of select 50930b57cec5SDimitry Andric // handles select i1 or select [N x i1] 50940b57cec5SDimitry Andric unsigned OpNum = 0; 50950b57cec5SDimitry Andric Value *TrueVal, *FalseVal, *Cond; 509681ad6265SDimitry Andric unsigned ValTypeID, CondTypeID; 509781ad6265SDimitry Andric if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal, ValTypeID, 509881ad6265SDimitry Andric CurBB) || 509981ad6265SDimitry Andric popValue(Record, OpNum, NextValueNo, TrueVal->getType(), ValTypeID, 510081ad6265SDimitry Andric FalseVal, CurBB) || 510181ad6265SDimitry Andric getValueTypePair(Record, OpNum, NextValueNo, Cond, CondTypeID, CurBB)) 51020b57cec5SDimitry Andric return error("Invalid record"); 51030b57cec5SDimitry Andric 51040b57cec5SDimitry Andric // select condition can be either i1 or [N x i1] 51050b57cec5SDimitry Andric if (VectorType* vector_type = 51060b57cec5SDimitry Andric dyn_cast<VectorType>(Cond->getType())) { 51070b57cec5SDimitry Andric // expect <n x i1> 51080b57cec5SDimitry Andric if (vector_type->getElementType() != Type::getInt1Ty(Context)) 51090b57cec5SDimitry Andric return error("Invalid type for value"); 51100b57cec5SDimitry Andric } else { 51110b57cec5SDimitry Andric // expect i1 51120b57cec5SDimitry Andric if (Cond->getType() != Type::getInt1Ty(Context)) 51130b57cec5SDimitry Andric return error("Invalid type for value"); 51140b57cec5SDimitry Andric } 51150b57cec5SDimitry Andric 51160b57cec5SDimitry Andric I = SelectInst::Create(Cond, TrueVal, FalseVal); 511781ad6265SDimitry Andric ResTypeID = ValTypeID; 51180b57cec5SDimitry Andric InstructionList.push_back(I); 51190b57cec5SDimitry Andric if (OpNum < Record.size() && isa<FPMathOperator>(I)) { 51200b57cec5SDimitry Andric FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]); 51210b57cec5SDimitry Andric if (FMF.any()) 51220b57cec5SDimitry Andric I->setFastMathFlags(FMF); 51230b57cec5SDimitry Andric } 51240b57cec5SDimitry Andric break; 51250b57cec5SDimitry Andric } 51260b57cec5SDimitry Andric 51270b57cec5SDimitry Andric case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval] 51280b57cec5SDimitry Andric unsigned OpNum = 0; 51290b57cec5SDimitry Andric Value *Vec, *Idx; 513081ad6265SDimitry Andric unsigned VecTypeID, IdxTypeID; 513181ad6265SDimitry Andric if (getValueTypePair(Record, OpNum, NextValueNo, Vec, VecTypeID, CurBB) || 513281ad6265SDimitry Andric getValueTypePair(Record, OpNum, NextValueNo, Idx, IdxTypeID, CurBB)) 51330b57cec5SDimitry Andric return error("Invalid record"); 51340b57cec5SDimitry Andric if (!Vec->getType()->isVectorTy()) 51350b57cec5SDimitry Andric return error("Invalid type for value"); 51360b57cec5SDimitry Andric I = ExtractElementInst::Create(Vec, Idx); 513781ad6265SDimitry Andric ResTypeID = getContainedTypeID(VecTypeID); 51380b57cec5SDimitry Andric InstructionList.push_back(I); 51390b57cec5SDimitry Andric break; 51400b57cec5SDimitry Andric } 51410b57cec5SDimitry Andric 51420b57cec5SDimitry Andric case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval] 51430b57cec5SDimitry Andric unsigned OpNum = 0; 51440b57cec5SDimitry Andric Value *Vec, *Elt, *Idx; 514581ad6265SDimitry Andric unsigned VecTypeID, IdxTypeID; 514681ad6265SDimitry Andric if (getValueTypePair(Record, OpNum, NextValueNo, Vec, VecTypeID, CurBB)) 51470b57cec5SDimitry Andric return error("Invalid record"); 51480b57cec5SDimitry Andric if (!Vec->getType()->isVectorTy()) 51490b57cec5SDimitry Andric return error("Invalid type for value"); 51500b57cec5SDimitry Andric if (popValue(Record, OpNum, NextValueNo, 515181ad6265SDimitry Andric cast<VectorType>(Vec->getType())->getElementType(), 515281ad6265SDimitry Andric getContainedTypeID(VecTypeID), Elt, CurBB) || 515381ad6265SDimitry Andric getValueTypePair(Record, OpNum, NextValueNo, Idx, IdxTypeID, CurBB)) 51540b57cec5SDimitry Andric return error("Invalid record"); 51550b57cec5SDimitry Andric I = InsertElementInst::Create(Vec, Elt, Idx); 515681ad6265SDimitry Andric ResTypeID = VecTypeID; 51570b57cec5SDimitry Andric InstructionList.push_back(I); 51580b57cec5SDimitry Andric break; 51590b57cec5SDimitry Andric } 51600b57cec5SDimitry Andric 51610b57cec5SDimitry Andric case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval] 51620b57cec5SDimitry Andric unsigned OpNum = 0; 51630b57cec5SDimitry Andric Value *Vec1, *Vec2, *Mask; 516481ad6265SDimitry Andric unsigned Vec1TypeID; 516581ad6265SDimitry Andric if (getValueTypePair(Record, OpNum, NextValueNo, Vec1, Vec1TypeID, 516681ad6265SDimitry Andric CurBB) || 516781ad6265SDimitry Andric popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec1TypeID, 516881ad6265SDimitry Andric Vec2, CurBB)) 51690b57cec5SDimitry Andric return error("Invalid record"); 51700b57cec5SDimitry Andric 517181ad6265SDimitry Andric unsigned MaskTypeID; 517281ad6265SDimitry Andric if (getValueTypePair(Record, OpNum, NextValueNo, Mask, MaskTypeID, CurBB)) 51730b57cec5SDimitry Andric return error("Invalid record"); 51740b57cec5SDimitry Andric if (!Vec1->getType()->isVectorTy() || !Vec2->getType()->isVectorTy()) 51750b57cec5SDimitry Andric return error("Invalid type for value"); 51765ffd83dbSDimitry Andric 51770b57cec5SDimitry Andric I = new ShuffleVectorInst(Vec1, Vec2, Mask); 517881ad6265SDimitry Andric ResTypeID = 517981ad6265SDimitry Andric getVirtualTypeID(I->getType(), getContainedTypeID(Vec1TypeID)); 51800b57cec5SDimitry Andric InstructionList.push_back(I); 51810b57cec5SDimitry Andric break; 51820b57cec5SDimitry Andric } 51830b57cec5SDimitry Andric 51840b57cec5SDimitry Andric case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred] 51850b57cec5SDimitry Andric // Old form of ICmp/FCmp returning bool 51860b57cec5SDimitry Andric // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were 51870b57cec5SDimitry Andric // both legal on vectors but had different behaviour. 51880b57cec5SDimitry Andric case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred] 51890b57cec5SDimitry Andric // FCmp/ICmp returning bool or vector of bool 51900b57cec5SDimitry Andric 51910b57cec5SDimitry Andric unsigned OpNum = 0; 51920b57cec5SDimitry Andric Value *LHS, *RHS; 519381ad6265SDimitry Andric unsigned LHSTypeID; 519481ad6265SDimitry Andric if (getValueTypePair(Record, OpNum, NextValueNo, LHS, LHSTypeID, CurBB) || 519581ad6265SDimitry Andric popValue(Record, OpNum, NextValueNo, LHS->getType(), LHSTypeID, RHS, 519681ad6265SDimitry Andric CurBB)) 51970b57cec5SDimitry Andric return error("Invalid record"); 51980b57cec5SDimitry Andric 51990b57cec5SDimitry Andric if (OpNum >= Record.size()) 52000b57cec5SDimitry Andric return error( 52010b57cec5SDimitry Andric "Invalid record: operand number exceeded available operands"); 52020b57cec5SDimitry Andric 52030b57cec5SDimitry Andric unsigned PredVal = Record[OpNum]; 52040b57cec5SDimitry Andric bool IsFP = LHS->getType()->isFPOrFPVectorTy(); 52050b57cec5SDimitry Andric FastMathFlags FMF; 52060b57cec5SDimitry Andric if (IsFP && Record.size() > OpNum+1) 52070b57cec5SDimitry Andric FMF = getDecodedFastMathFlags(Record[++OpNum]); 52080b57cec5SDimitry Andric 52090b57cec5SDimitry Andric if (OpNum+1 != Record.size()) 52100b57cec5SDimitry Andric return error("Invalid record"); 52110b57cec5SDimitry Andric 52120b57cec5SDimitry Andric if (LHS->getType()->isFPOrFPVectorTy()) 52130b57cec5SDimitry Andric I = new FCmpInst((FCmpInst::Predicate)PredVal, LHS, RHS); 52140b57cec5SDimitry Andric else 52150b57cec5SDimitry Andric I = new ICmpInst((ICmpInst::Predicate)PredVal, LHS, RHS); 52160b57cec5SDimitry Andric 521781ad6265SDimitry Andric ResTypeID = getVirtualTypeID(I->getType()->getScalarType()); 521881ad6265SDimitry Andric if (LHS->getType()->isVectorTy()) 521981ad6265SDimitry Andric ResTypeID = getVirtualTypeID(I->getType(), ResTypeID); 522081ad6265SDimitry Andric 52210b57cec5SDimitry Andric if (FMF.any()) 52220b57cec5SDimitry Andric I->setFastMathFlags(FMF); 52230b57cec5SDimitry Andric InstructionList.push_back(I); 52240b57cec5SDimitry Andric break; 52250b57cec5SDimitry Andric } 52260b57cec5SDimitry Andric 52270b57cec5SDimitry Andric case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>] 52280b57cec5SDimitry Andric { 52290b57cec5SDimitry Andric unsigned Size = Record.size(); 52300b57cec5SDimitry Andric if (Size == 0) { 52310b57cec5SDimitry Andric I = ReturnInst::Create(Context); 52320b57cec5SDimitry Andric InstructionList.push_back(I); 52330b57cec5SDimitry Andric break; 52340b57cec5SDimitry Andric } 52350b57cec5SDimitry Andric 52360b57cec5SDimitry Andric unsigned OpNum = 0; 52370b57cec5SDimitry Andric Value *Op = nullptr; 523881ad6265SDimitry Andric unsigned OpTypeID; 523981ad6265SDimitry Andric if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB)) 52400b57cec5SDimitry Andric return error("Invalid record"); 52410b57cec5SDimitry Andric if (OpNum != Record.size()) 52420b57cec5SDimitry Andric return error("Invalid record"); 52430b57cec5SDimitry Andric 52440b57cec5SDimitry Andric I = ReturnInst::Create(Context, Op); 52450b57cec5SDimitry Andric InstructionList.push_back(I); 52460b57cec5SDimitry Andric break; 52470b57cec5SDimitry Andric } 52480b57cec5SDimitry Andric case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#] 52490b57cec5SDimitry Andric if (Record.size() != 1 && Record.size() != 3) 52500b57cec5SDimitry Andric return error("Invalid record"); 52510b57cec5SDimitry Andric BasicBlock *TrueDest = getBasicBlock(Record[0]); 52520b57cec5SDimitry Andric if (!TrueDest) 52530b57cec5SDimitry Andric return error("Invalid record"); 52540b57cec5SDimitry Andric 52550b57cec5SDimitry Andric if (Record.size() == 1) { 52560b57cec5SDimitry Andric I = BranchInst::Create(TrueDest); 52570b57cec5SDimitry Andric InstructionList.push_back(I); 52580b57cec5SDimitry Andric } 52590b57cec5SDimitry Andric else { 52600b57cec5SDimitry Andric BasicBlock *FalseDest = getBasicBlock(Record[1]); 526181ad6265SDimitry Andric Type *CondType = Type::getInt1Ty(Context); 526281ad6265SDimitry Andric Value *Cond = getValue(Record, 2, NextValueNo, CondType, 526381ad6265SDimitry Andric getVirtualTypeID(CondType), CurBB); 52640b57cec5SDimitry Andric if (!FalseDest || !Cond) 52650b57cec5SDimitry Andric return error("Invalid record"); 52660b57cec5SDimitry Andric I = BranchInst::Create(TrueDest, FalseDest, Cond); 52670b57cec5SDimitry Andric InstructionList.push_back(I); 52680b57cec5SDimitry Andric } 52690b57cec5SDimitry Andric break; 52700b57cec5SDimitry Andric } 52710b57cec5SDimitry Andric case bitc::FUNC_CODE_INST_CLEANUPRET: { // CLEANUPRET: [val] or [val,bb#] 52720b57cec5SDimitry Andric if (Record.size() != 1 && Record.size() != 2) 52730b57cec5SDimitry Andric return error("Invalid record"); 52740b57cec5SDimitry Andric unsigned Idx = 0; 527581ad6265SDimitry Andric Type *TokenTy = Type::getTokenTy(Context); 527681ad6265SDimitry Andric Value *CleanupPad = getValue(Record, Idx++, NextValueNo, TokenTy, 527781ad6265SDimitry Andric getVirtualTypeID(TokenTy), CurBB); 52780b57cec5SDimitry Andric if (!CleanupPad) 52790b57cec5SDimitry Andric return error("Invalid record"); 52800b57cec5SDimitry Andric BasicBlock *UnwindDest = nullptr; 52810b57cec5SDimitry Andric if (Record.size() == 2) { 52820b57cec5SDimitry Andric UnwindDest = getBasicBlock(Record[Idx++]); 52830b57cec5SDimitry Andric if (!UnwindDest) 52840b57cec5SDimitry Andric return error("Invalid record"); 52850b57cec5SDimitry Andric } 52860b57cec5SDimitry Andric 52870b57cec5SDimitry Andric I = CleanupReturnInst::Create(CleanupPad, UnwindDest); 52880b57cec5SDimitry Andric InstructionList.push_back(I); 52890b57cec5SDimitry Andric break; 52900b57cec5SDimitry Andric } 52910b57cec5SDimitry Andric case bitc::FUNC_CODE_INST_CATCHRET: { // CATCHRET: [val,bb#] 52920b57cec5SDimitry Andric if (Record.size() != 2) 52930b57cec5SDimitry Andric return error("Invalid record"); 52940b57cec5SDimitry Andric unsigned Idx = 0; 529581ad6265SDimitry Andric Type *TokenTy = Type::getTokenTy(Context); 529681ad6265SDimitry Andric Value *CatchPad = getValue(Record, Idx++, NextValueNo, TokenTy, 529781ad6265SDimitry Andric getVirtualTypeID(TokenTy), CurBB); 52980b57cec5SDimitry Andric if (!CatchPad) 52990b57cec5SDimitry Andric return error("Invalid record"); 53000b57cec5SDimitry Andric BasicBlock *BB = getBasicBlock(Record[Idx++]); 53010b57cec5SDimitry Andric if (!BB) 53020b57cec5SDimitry Andric return error("Invalid record"); 53030b57cec5SDimitry Andric 53040b57cec5SDimitry Andric I = CatchReturnInst::Create(CatchPad, BB); 53050b57cec5SDimitry Andric InstructionList.push_back(I); 53060b57cec5SDimitry Andric break; 53070b57cec5SDimitry Andric } 53080b57cec5SDimitry Andric case bitc::FUNC_CODE_INST_CATCHSWITCH: { // CATCHSWITCH: [tok,num,(bb)*,bb?] 53090b57cec5SDimitry Andric // We must have, at minimum, the outer scope and the number of arguments. 53100b57cec5SDimitry Andric if (Record.size() < 2) 53110b57cec5SDimitry Andric return error("Invalid record"); 53120b57cec5SDimitry Andric 53130b57cec5SDimitry Andric unsigned Idx = 0; 53140b57cec5SDimitry Andric 531581ad6265SDimitry Andric Type *TokenTy = Type::getTokenTy(Context); 531681ad6265SDimitry Andric Value *ParentPad = getValue(Record, Idx++, NextValueNo, TokenTy, 531781ad6265SDimitry Andric getVirtualTypeID(TokenTy), CurBB); 53180b57cec5SDimitry Andric 53190b57cec5SDimitry Andric unsigned NumHandlers = Record[Idx++]; 53200b57cec5SDimitry Andric 53210b57cec5SDimitry Andric SmallVector<BasicBlock *, 2> Handlers; 53220b57cec5SDimitry Andric for (unsigned Op = 0; Op != NumHandlers; ++Op) { 53230b57cec5SDimitry Andric BasicBlock *BB = getBasicBlock(Record[Idx++]); 53240b57cec5SDimitry Andric if (!BB) 53250b57cec5SDimitry Andric return error("Invalid record"); 53260b57cec5SDimitry Andric Handlers.push_back(BB); 53270b57cec5SDimitry Andric } 53280b57cec5SDimitry Andric 53290b57cec5SDimitry Andric BasicBlock *UnwindDest = nullptr; 53300b57cec5SDimitry Andric if (Idx + 1 == Record.size()) { 53310b57cec5SDimitry Andric UnwindDest = getBasicBlock(Record[Idx++]); 53320b57cec5SDimitry Andric if (!UnwindDest) 53330b57cec5SDimitry Andric return error("Invalid record"); 53340b57cec5SDimitry Andric } 53350b57cec5SDimitry Andric 53360b57cec5SDimitry Andric if (Record.size() != Idx) 53370b57cec5SDimitry Andric return error("Invalid record"); 53380b57cec5SDimitry Andric 53390b57cec5SDimitry Andric auto *CatchSwitch = 53400b57cec5SDimitry Andric CatchSwitchInst::Create(ParentPad, UnwindDest, NumHandlers); 53410b57cec5SDimitry Andric for (BasicBlock *Handler : Handlers) 53420b57cec5SDimitry Andric CatchSwitch->addHandler(Handler); 53430b57cec5SDimitry Andric I = CatchSwitch; 534481ad6265SDimitry Andric ResTypeID = getVirtualTypeID(I->getType()); 53450b57cec5SDimitry Andric InstructionList.push_back(I); 53460b57cec5SDimitry Andric break; 53470b57cec5SDimitry Andric } 53480b57cec5SDimitry Andric case bitc::FUNC_CODE_INST_CATCHPAD: 53490b57cec5SDimitry Andric case bitc::FUNC_CODE_INST_CLEANUPPAD: { // [tok,num,(ty,val)*] 53500b57cec5SDimitry Andric // We must have, at minimum, the outer scope and the number of arguments. 53510b57cec5SDimitry Andric if (Record.size() < 2) 53520b57cec5SDimitry Andric return error("Invalid record"); 53530b57cec5SDimitry Andric 53540b57cec5SDimitry Andric unsigned Idx = 0; 53550b57cec5SDimitry Andric 535681ad6265SDimitry Andric Type *TokenTy = Type::getTokenTy(Context); 535781ad6265SDimitry Andric Value *ParentPad = getValue(Record, Idx++, NextValueNo, TokenTy, 535881ad6265SDimitry Andric getVirtualTypeID(TokenTy), CurBB); 53590b57cec5SDimitry Andric 53600b57cec5SDimitry Andric unsigned NumArgOperands = Record[Idx++]; 53610b57cec5SDimitry Andric 53620b57cec5SDimitry Andric SmallVector<Value *, 2> Args; 53630b57cec5SDimitry Andric for (unsigned Op = 0; Op != NumArgOperands; ++Op) { 53640b57cec5SDimitry Andric Value *Val; 536581ad6265SDimitry Andric unsigned ValTypeID; 536681ad6265SDimitry Andric if (getValueTypePair(Record, Idx, NextValueNo, Val, ValTypeID, nullptr)) 53670b57cec5SDimitry Andric return error("Invalid record"); 53680b57cec5SDimitry Andric Args.push_back(Val); 53690b57cec5SDimitry Andric } 53700b57cec5SDimitry Andric 53710b57cec5SDimitry Andric if (Record.size() != Idx) 53720b57cec5SDimitry Andric return error("Invalid record"); 53730b57cec5SDimitry Andric 53740b57cec5SDimitry Andric if (BitCode == bitc::FUNC_CODE_INST_CLEANUPPAD) 53750b57cec5SDimitry Andric I = CleanupPadInst::Create(ParentPad, Args); 53760b57cec5SDimitry Andric else 53770b57cec5SDimitry Andric I = CatchPadInst::Create(ParentPad, Args); 537881ad6265SDimitry Andric ResTypeID = getVirtualTypeID(I->getType()); 53790b57cec5SDimitry Andric InstructionList.push_back(I); 53800b57cec5SDimitry Andric break; 53810b57cec5SDimitry Andric } 53820b57cec5SDimitry Andric case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...] 53830b57cec5SDimitry Andric // Check magic 53840b57cec5SDimitry Andric if ((Record[0] >> 16) == SWITCH_INST_MAGIC) { 53850b57cec5SDimitry Andric // "New" SwitchInst format with case ranges. The changes to write this 53860b57cec5SDimitry Andric // format were reverted but we still recognize bitcode that uses it. 53870b57cec5SDimitry Andric // Hopefully someday we will have support for case ranges and can use 53880b57cec5SDimitry Andric // this format again. 53890b57cec5SDimitry Andric 539081ad6265SDimitry Andric unsigned OpTyID = Record[1]; 539181ad6265SDimitry Andric Type *OpTy = getTypeByID(OpTyID); 53920b57cec5SDimitry Andric unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth(); 53930b57cec5SDimitry Andric 539481ad6265SDimitry Andric Value *Cond = getValue(Record, 2, NextValueNo, OpTy, OpTyID, CurBB); 53950b57cec5SDimitry Andric BasicBlock *Default = getBasicBlock(Record[3]); 53960b57cec5SDimitry Andric if (!OpTy || !Cond || !Default) 53970b57cec5SDimitry Andric return error("Invalid record"); 53980b57cec5SDimitry Andric 53990b57cec5SDimitry Andric unsigned NumCases = Record[4]; 54000b57cec5SDimitry Andric 54010b57cec5SDimitry Andric SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases); 54020b57cec5SDimitry Andric InstructionList.push_back(SI); 54030b57cec5SDimitry Andric 54040b57cec5SDimitry Andric unsigned CurIdx = 5; 54050b57cec5SDimitry Andric for (unsigned i = 0; i != NumCases; ++i) { 54060b57cec5SDimitry Andric SmallVector<ConstantInt*, 1> CaseVals; 54070b57cec5SDimitry Andric unsigned NumItems = Record[CurIdx++]; 54080b57cec5SDimitry Andric for (unsigned ci = 0; ci != NumItems; ++ci) { 54090b57cec5SDimitry Andric bool isSingleNumber = Record[CurIdx++]; 54100b57cec5SDimitry Andric 54110b57cec5SDimitry Andric APInt Low; 54120b57cec5SDimitry Andric unsigned ActiveWords = 1; 54130b57cec5SDimitry Andric if (ValueBitWidth > 64) 54140b57cec5SDimitry Andric ActiveWords = Record[CurIdx++]; 5415bdd1243dSDimitry Andric Low = readWideAPInt(ArrayRef(&Record[CurIdx], ActiveWords), 54160b57cec5SDimitry Andric ValueBitWidth); 54170b57cec5SDimitry Andric CurIdx += ActiveWords; 54180b57cec5SDimitry Andric 54190b57cec5SDimitry Andric if (!isSingleNumber) { 54200b57cec5SDimitry Andric ActiveWords = 1; 54210b57cec5SDimitry Andric if (ValueBitWidth > 64) 54220b57cec5SDimitry Andric ActiveWords = Record[CurIdx++]; 5423bdd1243dSDimitry Andric APInt High = readWideAPInt(ArrayRef(&Record[CurIdx], ActiveWords), 5424bdd1243dSDimitry Andric ValueBitWidth); 54250b57cec5SDimitry Andric CurIdx += ActiveWords; 54260b57cec5SDimitry Andric 54270b57cec5SDimitry Andric // FIXME: It is not clear whether values in the range should be 54280b57cec5SDimitry Andric // compared as signed or unsigned values. The partially 54290b57cec5SDimitry Andric // implemented changes that used this format in the past used 54300b57cec5SDimitry Andric // unsigned comparisons. 54310b57cec5SDimitry Andric for ( ; Low.ule(High); ++Low) 54320b57cec5SDimitry Andric CaseVals.push_back(ConstantInt::get(Context, Low)); 54330b57cec5SDimitry Andric } else 54340b57cec5SDimitry Andric CaseVals.push_back(ConstantInt::get(Context, Low)); 54350b57cec5SDimitry Andric } 54360b57cec5SDimitry Andric BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]); 54374824e7fdSDimitry Andric for (ConstantInt *Cst : CaseVals) 54384824e7fdSDimitry Andric SI->addCase(Cst, DestBB); 54390b57cec5SDimitry Andric } 54400b57cec5SDimitry Andric I = SI; 54410b57cec5SDimitry Andric break; 54420b57cec5SDimitry Andric } 54430b57cec5SDimitry Andric 54440b57cec5SDimitry Andric // Old SwitchInst format without case ranges. 54450b57cec5SDimitry Andric 54460b57cec5SDimitry Andric if (Record.size() < 3 || (Record.size() & 1) == 0) 54470b57cec5SDimitry Andric return error("Invalid record"); 544881ad6265SDimitry Andric unsigned OpTyID = Record[0]; 544981ad6265SDimitry Andric Type *OpTy = getTypeByID(OpTyID); 545081ad6265SDimitry Andric Value *Cond = getValue(Record, 1, NextValueNo, OpTy, OpTyID, CurBB); 54510b57cec5SDimitry Andric BasicBlock *Default = getBasicBlock(Record[2]); 54520b57cec5SDimitry Andric if (!OpTy || !Cond || !Default) 54530b57cec5SDimitry Andric return error("Invalid record"); 54540b57cec5SDimitry Andric unsigned NumCases = (Record.size()-3)/2; 54550b57cec5SDimitry Andric SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases); 54560b57cec5SDimitry Andric InstructionList.push_back(SI); 54570b57cec5SDimitry Andric for (unsigned i = 0, e = NumCases; i != e; ++i) { 545881ad6265SDimitry Andric ConstantInt *CaseVal = dyn_cast_or_null<ConstantInt>( 545981ad6265SDimitry Andric getFnValueByID(Record[3+i*2], OpTy, OpTyID, nullptr)); 54600b57cec5SDimitry Andric BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]); 54610b57cec5SDimitry Andric if (!CaseVal || !DestBB) { 54620b57cec5SDimitry Andric delete SI; 54630b57cec5SDimitry Andric return error("Invalid record"); 54640b57cec5SDimitry Andric } 54650b57cec5SDimitry Andric SI->addCase(CaseVal, DestBB); 54660b57cec5SDimitry Andric } 54670b57cec5SDimitry Andric I = SI; 54680b57cec5SDimitry Andric break; 54690b57cec5SDimitry Andric } 54700b57cec5SDimitry Andric case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...] 54710b57cec5SDimitry Andric if (Record.size() < 2) 54720b57cec5SDimitry Andric return error("Invalid record"); 547381ad6265SDimitry Andric unsigned OpTyID = Record[0]; 547481ad6265SDimitry Andric Type *OpTy = getTypeByID(OpTyID); 547581ad6265SDimitry Andric Value *Address = getValue(Record, 1, NextValueNo, OpTy, OpTyID, CurBB); 54760b57cec5SDimitry Andric if (!OpTy || !Address) 54770b57cec5SDimitry Andric return error("Invalid record"); 54780b57cec5SDimitry Andric unsigned NumDests = Record.size()-2; 54790b57cec5SDimitry Andric IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests); 54800b57cec5SDimitry Andric InstructionList.push_back(IBI); 54810b57cec5SDimitry Andric for (unsigned i = 0, e = NumDests; i != e; ++i) { 54820b57cec5SDimitry Andric if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) { 54830b57cec5SDimitry Andric IBI->addDestination(DestBB); 54840b57cec5SDimitry Andric } else { 54850b57cec5SDimitry Andric delete IBI; 54860b57cec5SDimitry Andric return error("Invalid record"); 54870b57cec5SDimitry Andric } 54880b57cec5SDimitry Andric } 54890b57cec5SDimitry Andric I = IBI; 54900b57cec5SDimitry Andric break; 54910b57cec5SDimitry Andric } 54920b57cec5SDimitry Andric 54930b57cec5SDimitry Andric case bitc::FUNC_CODE_INST_INVOKE: { 54940b57cec5SDimitry Andric // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...] 54950b57cec5SDimitry Andric if (Record.size() < 4) 54960b57cec5SDimitry Andric return error("Invalid record"); 54970b57cec5SDimitry Andric unsigned OpNum = 0; 54980b57cec5SDimitry Andric AttributeList PAL = getAttributes(Record[OpNum++]); 54990b57cec5SDimitry Andric unsigned CCInfo = Record[OpNum++]; 55000b57cec5SDimitry Andric BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]); 55010b57cec5SDimitry Andric BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]); 55020b57cec5SDimitry Andric 550381ad6265SDimitry Andric unsigned FTyID = InvalidTypeID; 55040b57cec5SDimitry Andric FunctionType *FTy = nullptr; 55050b57cec5SDimitry Andric if ((CCInfo >> 13) & 1) { 550681ad6265SDimitry Andric FTyID = Record[OpNum++]; 550781ad6265SDimitry Andric FTy = dyn_cast<FunctionType>(getTypeByID(FTyID)); 5508fe6060f1SDimitry Andric if (!FTy) 55090b57cec5SDimitry Andric return error("Explicit invoke type is not a function type"); 55100b57cec5SDimitry Andric } 55110b57cec5SDimitry Andric 55120b57cec5SDimitry Andric Value *Callee; 551381ad6265SDimitry Andric unsigned CalleeTypeID; 551481ad6265SDimitry Andric if (getValueTypePair(Record, OpNum, NextValueNo, Callee, CalleeTypeID, 551581ad6265SDimitry Andric CurBB)) 55160b57cec5SDimitry Andric return error("Invalid record"); 55170b57cec5SDimitry Andric 55180b57cec5SDimitry Andric PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType()); 55190b57cec5SDimitry Andric if (!CalleeTy) 55200b57cec5SDimitry Andric return error("Callee is not a pointer"); 55210b57cec5SDimitry Andric if (!FTy) { 552281ad6265SDimitry Andric FTyID = getContainedTypeID(CalleeTypeID); 552381ad6265SDimitry Andric FTy = dyn_cast_or_null<FunctionType>(getTypeByID(FTyID)); 5524fe6060f1SDimitry Andric if (!FTy) 55250b57cec5SDimitry Andric return error("Callee is not of pointer to function type"); 5526*fe013be4SDimitry Andric } 55270b57cec5SDimitry Andric if (Record.size() < FTy->getNumParams() + OpNum) 55280b57cec5SDimitry Andric return error("Insufficient operands to call"); 55290b57cec5SDimitry Andric 55300b57cec5SDimitry Andric SmallVector<Value*, 16> Ops; 553181ad6265SDimitry Andric SmallVector<unsigned, 16> ArgTyIDs; 55320b57cec5SDimitry Andric for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) { 553381ad6265SDimitry Andric unsigned ArgTyID = getContainedTypeID(FTyID, i + 1); 553481ad6265SDimitry Andric Ops.push_back(getValue(Record, OpNum, NextValueNo, FTy->getParamType(i), 553581ad6265SDimitry Andric ArgTyID, CurBB)); 553681ad6265SDimitry Andric ArgTyIDs.push_back(ArgTyID); 55370b57cec5SDimitry Andric if (!Ops.back()) 55380b57cec5SDimitry Andric return error("Invalid record"); 55390b57cec5SDimitry Andric } 55400b57cec5SDimitry Andric 55410b57cec5SDimitry Andric if (!FTy->isVarArg()) { 55420b57cec5SDimitry Andric if (Record.size() != OpNum) 55430b57cec5SDimitry Andric return error("Invalid record"); 55440b57cec5SDimitry Andric } else { 55450b57cec5SDimitry Andric // Read type/value pairs for varargs params. 55460b57cec5SDimitry Andric while (OpNum != Record.size()) { 55470b57cec5SDimitry Andric Value *Op; 554881ad6265SDimitry Andric unsigned OpTypeID; 554981ad6265SDimitry Andric if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB)) 55500b57cec5SDimitry Andric return error("Invalid record"); 55510b57cec5SDimitry Andric Ops.push_back(Op); 555281ad6265SDimitry Andric ArgTyIDs.push_back(OpTypeID); 55530b57cec5SDimitry Andric } 55540b57cec5SDimitry Andric } 55550b57cec5SDimitry Andric 555681ad6265SDimitry Andric // Upgrade the bundles if needed. 555781ad6265SDimitry Andric if (!OperandBundles.empty()) 555881ad6265SDimitry Andric UpgradeOperandBundles(OperandBundles); 555981ad6265SDimitry Andric 55600b57cec5SDimitry Andric I = InvokeInst::Create(FTy, Callee, NormalBB, UnwindBB, Ops, 55610b57cec5SDimitry Andric OperandBundles); 556281ad6265SDimitry Andric ResTypeID = getContainedTypeID(FTyID); 55630b57cec5SDimitry Andric OperandBundles.clear(); 55640b57cec5SDimitry Andric InstructionList.push_back(I); 55650b57cec5SDimitry Andric cast<InvokeInst>(I)->setCallingConv( 55660b57cec5SDimitry Andric static_cast<CallingConv::ID>(CallingConv::MaxID & CCInfo)); 55670b57cec5SDimitry Andric cast<InvokeInst>(I)->setAttributes(PAL); 556881ad6265SDimitry Andric if (Error Err = propagateAttributeTypes(cast<CallBase>(I), ArgTyIDs)) { 556981ad6265SDimitry Andric I->deleteValue(); 557081ad6265SDimitry Andric return Err; 557181ad6265SDimitry Andric } 55720b57cec5SDimitry Andric 55730b57cec5SDimitry Andric break; 55740b57cec5SDimitry Andric } 55750b57cec5SDimitry Andric case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval] 55760b57cec5SDimitry Andric unsigned Idx = 0; 55770b57cec5SDimitry Andric Value *Val = nullptr; 557881ad6265SDimitry Andric unsigned ValTypeID; 557981ad6265SDimitry Andric if (getValueTypePair(Record, Idx, NextValueNo, Val, ValTypeID, CurBB)) 55800b57cec5SDimitry Andric return error("Invalid record"); 55810b57cec5SDimitry Andric I = ResumeInst::Create(Val); 55820b57cec5SDimitry Andric InstructionList.push_back(I); 55830b57cec5SDimitry Andric break; 55840b57cec5SDimitry Andric } 55850b57cec5SDimitry Andric case bitc::FUNC_CODE_INST_CALLBR: { 55860b57cec5SDimitry Andric // CALLBR: [attr, cc, norm, transfs, fty, fnid, args] 55870b57cec5SDimitry Andric unsigned OpNum = 0; 55880b57cec5SDimitry Andric AttributeList PAL = getAttributes(Record[OpNum++]); 55890b57cec5SDimitry Andric unsigned CCInfo = Record[OpNum++]; 55900b57cec5SDimitry Andric 55910b57cec5SDimitry Andric BasicBlock *DefaultDest = getBasicBlock(Record[OpNum++]); 55920b57cec5SDimitry Andric unsigned NumIndirectDests = Record[OpNum++]; 55930b57cec5SDimitry Andric SmallVector<BasicBlock *, 16> IndirectDests; 55940b57cec5SDimitry Andric for (unsigned i = 0, e = NumIndirectDests; i != e; ++i) 55950b57cec5SDimitry Andric IndirectDests.push_back(getBasicBlock(Record[OpNum++])); 55960b57cec5SDimitry Andric 559781ad6265SDimitry Andric unsigned FTyID = InvalidTypeID; 55980b57cec5SDimitry Andric FunctionType *FTy = nullptr; 55990b57cec5SDimitry Andric if ((CCInfo >> bitc::CALL_EXPLICIT_TYPE) & 1) { 560081ad6265SDimitry Andric FTyID = Record[OpNum++]; 560181ad6265SDimitry Andric FTy = dyn_cast_or_null<FunctionType>(getTypeByID(FTyID)); 5602fe6060f1SDimitry Andric if (!FTy) 56030b57cec5SDimitry Andric return error("Explicit call type is not a function type"); 56040b57cec5SDimitry Andric } 56050b57cec5SDimitry Andric 56060b57cec5SDimitry Andric Value *Callee; 560781ad6265SDimitry Andric unsigned CalleeTypeID; 560881ad6265SDimitry Andric if (getValueTypePair(Record, OpNum, NextValueNo, Callee, CalleeTypeID, 560981ad6265SDimitry Andric CurBB)) 56100b57cec5SDimitry Andric return error("Invalid record"); 56110b57cec5SDimitry Andric 56120b57cec5SDimitry Andric PointerType *OpTy = dyn_cast<PointerType>(Callee->getType()); 56130b57cec5SDimitry Andric if (!OpTy) 56140b57cec5SDimitry Andric return error("Callee is not a pointer type"); 56150b57cec5SDimitry Andric if (!FTy) { 561681ad6265SDimitry Andric FTyID = getContainedTypeID(CalleeTypeID); 561781ad6265SDimitry Andric FTy = dyn_cast_or_null<FunctionType>(getTypeByID(FTyID)); 5618fe6060f1SDimitry Andric if (!FTy) 56190b57cec5SDimitry Andric return error("Callee is not of pointer to function type"); 5620*fe013be4SDimitry Andric } 56210b57cec5SDimitry Andric if (Record.size() < FTy->getNumParams() + OpNum) 56220b57cec5SDimitry Andric return error("Insufficient operands to call"); 56230b57cec5SDimitry Andric 56240b57cec5SDimitry Andric SmallVector<Value*, 16> Args; 562581ad6265SDimitry Andric SmallVector<unsigned, 16> ArgTyIDs; 56260b57cec5SDimitry Andric // Read the fixed params. 56270b57cec5SDimitry Andric for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) { 562804eeddc0SDimitry Andric Value *Arg; 562981ad6265SDimitry Andric unsigned ArgTyID = getContainedTypeID(FTyID, i + 1); 56300b57cec5SDimitry Andric if (FTy->getParamType(i)->isLabelTy()) 563104eeddc0SDimitry Andric Arg = getBasicBlock(Record[OpNum]); 56320b57cec5SDimitry Andric else 563381ad6265SDimitry Andric Arg = getValue(Record, OpNum, NextValueNo, FTy->getParamType(i), 563481ad6265SDimitry Andric ArgTyID, CurBB); 563504eeddc0SDimitry Andric if (!Arg) 56360b57cec5SDimitry Andric return error("Invalid record"); 563704eeddc0SDimitry Andric Args.push_back(Arg); 563881ad6265SDimitry Andric ArgTyIDs.push_back(ArgTyID); 56390b57cec5SDimitry Andric } 56400b57cec5SDimitry Andric 56410b57cec5SDimitry Andric // Read type/value pairs for varargs params. 56420b57cec5SDimitry Andric if (!FTy->isVarArg()) { 56430b57cec5SDimitry Andric if (OpNum != Record.size()) 56440b57cec5SDimitry Andric return error("Invalid record"); 56450b57cec5SDimitry Andric } else { 56460b57cec5SDimitry Andric while (OpNum != Record.size()) { 56470b57cec5SDimitry Andric Value *Op; 564881ad6265SDimitry Andric unsigned OpTypeID; 564981ad6265SDimitry Andric if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB)) 56500b57cec5SDimitry Andric return error("Invalid record"); 56510b57cec5SDimitry Andric Args.push_back(Op); 565281ad6265SDimitry Andric ArgTyIDs.push_back(OpTypeID); 56530b57cec5SDimitry Andric } 56540b57cec5SDimitry Andric } 56550b57cec5SDimitry Andric 565681ad6265SDimitry Andric // Upgrade the bundles if needed. 565781ad6265SDimitry Andric if (!OperandBundles.empty()) 565881ad6265SDimitry Andric UpgradeOperandBundles(OperandBundles); 565981ad6265SDimitry Andric 5660fcaf7f86SDimitry Andric if (auto *IA = dyn_cast<InlineAsm>(Callee)) { 5661fcaf7f86SDimitry Andric InlineAsm::ConstraintInfoVector ConstraintInfo = IA->ParseConstraints(); 5662fcaf7f86SDimitry Andric auto IsLabelConstraint = [](const InlineAsm::ConstraintInfo &CI) { 5663fcaf7f86SDimitry Andric return CI.Type == InlineAsm::isLabel; 5664fcaf7f86SDimitry Andric }; 5665fcaf7f86SDimitry Andric if (none_of(ConstraintInfo, IsLabelConstraint)) { 5666fcaf7f86SDimitry Andric // Upgrade explicit blockaddress arguments to label constraints. 5667fcaf7f86SDimitry Andric // Verify that the last arguments are blockaddress arguments that 5668fcaf7f86SDimitry Andric // match the indirect destinations. Clang always generates callbr 5669fcaf7f86SDimitry Andric // in this form. We could support reordering with more effort. 5670fcaf7f86SDimitry Andric unsigned FirstBlockArg = Args.size() - IndirectDests.size(); 5671fcaf7f86SDimitry Andric for (unsigned ArgNo = FirstBlockArg; ArgNo < Args.size(); ++ArgNo) { 5672fcaf7f86SDimitry Andric unsigned LabelNo = ArgNo - FirstBlockArg; 5673fcaf7f86SDimitry Andric auto *BA = dyn_cast<BlockAddress>(Args[ArgNo]); 5674fcaf7f86SDimitry Andric if (!BA || BA->getFunction() != F || 5675fcaf7f86SDimitry Andric LabelNo > IndirectDests.size() || 5676fcaf7f86SDimitry Andric BA->getBasicBlock() != IndirectDests[LabelNo]) 5677fcaf7f86SDimitry Andric return error("callbr argument does not match indirect dest"); 5678fcaf7f86SDimitry Andric } 5679fcaf7f86SDimitry Andric 5680fcaf7f86SDimitry Andric // Remove blockaddress arguments. 5681fcaf7f86SDimitry Andric Args.erase(Args.begin() + FirstBlockArg, Args.end()); 5682fcaf7f86SDimitry Andric ArgTyIDs.erase(ArgTyIDs.begin() + FirstBlockArg, ArgTyIDs.end()); 5683fcaf7f86SDimitry Andric 5684fcaf7f86SDimitry Andric // Recreate the function type with less arguments. 5685fcaf7f86SDimitry Andric SmallVector<Type *> ArgTys; 5686fcaf7f86SDimitry Andric for (Value *Arg : Args) 5687fcaf7f86SDimitry Andric ArgTys.push_back(Arg->getType()); 5688fcaf7f86SDimitry Andric FTy = 5689fcaf7f86SDimitry Andric FunctionType::get(FTy->getReturnType(), ArgTys, FTy->isVarArg()); 5690fcaf7f86SDimitry Andric 5691fcaf7f86SDimitry Andric // Update constraint string to use label constraints. 5692fcaf7f86SDimitry Andric std::string Constraints = IA->getConstraintString(); 5693fcaf7f86SDimitry Andric unsigned ArgNo = 0; 5694fcaf7f86SDimitry Andric size_t Pos = 0; 5695fcaf7f86SDimitry Andric for (const auto &CI : ConstraintInfo) { 5696fcaf7f86SDimitry Andric if (CI.hasArg()) { 5697fcaf7f86SDimitry Andric if (ArgNo >= FirstBlockArg) 5698fcaf7f86SDimitry Andric Constraints.insert(Pos, "!"); 5699fcaf7f86SDimitry Andric ++ArgNo; 5700fcaf7f86SDimitry Andric } 5701fcaf7f86SDimitry Andric 5702fcaf7f86SDimitry Andric // Go to next constraint in string. 5703fcaf7f86SDimitry Andric Pos = Constraints.find(',', Pos); 5704fcaf7f86SDimitry Andric if (Pos == std::string::npos) 5705fcaf7f86SDimitry Andric break; 5706fcaf7f86SDimitry Andric ++Pos; 5707fcaf7f86SDimitry Andric } 5708fcaf7f86SDimitry Andric 5709fcaf7f86SDimitry Andric Callee = InlineAsm::get(FTy, IA->getAsmString(), Constraints, 5710fcaf7f86SDimitry Andric IA->hasSideEffects(), IA->isAlignStack(), 5711fcaf7f86SDimitry Andric IA->getDialect(), IA->canThrow()); 5712fcaf7f86SDimitry Andric } 5713fcaf7f86SDimitry Andric } 5714fcaf7f86SDimitry Andric 57150b57cec5SDimitry Andric I = CallBrInst::Create(FTy, Callee, DefaultDest, IndirectDests, Args, 57160b57cec5SDimitry Andric OperandBundles); 571781ad6265SDimitry Andric ResTypeID = getContainedTypeID(FTyID); 57180b57cec5SDimitry Andric OperandBundles.clear(); 57190b57cec5SDimitry Andric InstructionList.push_back(I); 57200b57cec5SDimitry Andric cast<CallBrInst>(I)->setCallingConv( 57210b57cec5SDimitry Andric static_cast<CallingConv::ID>((0x7ff & CCInfo) >> bitc::CALL_CCONV)); 57220b57cec5SDimitry Andric cast<CallBrInst>(I)->setAttributes(PAL); 572381ad6265SDimitry Andric if (Error Err = propagateAttributeTypes(cast<CallBase>(I), ArgTyIDs)) { 572481ad6265SDimitry Andric I->deleteValue(); 572581ad6265SDimitry Andric return Err; 572681ad6265SDimitry Andric } 57270b57cec5SDimitry Andric break; 57280b57cec5SDimitry Andric } 57290b57cec5SDimitry Andric case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE 57300b57cec5SDimitry Andric I = new UnreachableInst(Context); 57310b57cec5SDimitry Andric InstructionList.push_back(I); 57320b57cec5SDimitry Andric break; 57330b57cec5SDimitry Andric case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...] 5734e8d8bef9SDimitry Andric if (Record.empty()) 573581ad6265SDimitry Andric return error("Invalid phi record"); 57368bcb0991SDimitry Andric // The first record specifies the type. 573781ad6265SDimitry Andric unsigned TyID = Record[0]; 573881ad6265SDimitry Andric Type *Ty = getTypeByID(TyID); 57390b57cec5SDimitry Andric if (!Ty) 574081ad6265SDimitry Andric return error("Invalid phi record"); 57410b57cec5SDimitry Andric 57428bcb0991SDimitry Andric // Phi arguments are pairs of records of [value, basic block]. 57438bcb0991SDimitry Andric // There is an optional final record for fast-math-flags if this phi has a 57448bcb0991SDimitry Andric // floating-point type. 57458bcb0991SDimitry Andric size_t NumArgs = (Record.size() - 1) / 2; 57468bcb0991SDimitry Andric PHINode *PN = PHINode::Create(Ty, NumArgs); 574781ad6265SDimitry Andric if ((Record.size() - 1) % 2 == 1 && !isa<FPMathOperator>(PN)) { 574881ad6265SDimitry Andric PN->deleteValue(); 574981ad6265SDimitry Andric return error("Invalid phi record"); 575081ad6265SDimitry Andric } 57510b57cec5SDimitry Andric InstructionList.push_back(PN); 57520b57cec5SDimitry Andric 575381ad6265SDimitry Andric SmallDenseMap<BasicBlock *, Value *> Args; 57548bcb0991SDimitry Andric for (unsigned i = 0; i != NumArgs; i++) { 575581ad6265SDimitry Andric BasicBlock *BB = getBasicBlock(Record[i * 2 + 2]); 575681ad6265SDimitry Andric if (!BB) { 575781ad6265SDimitry Andric PN->deleteValue(); 575881ad6265SDimitry Andric return error("Invalid phi BB"); 575981ad6265SDimitry Andric } 576081ad6265SDimitry Andric 576181ad6265SDimitry Andric // Phi nodes may contain the same predecessor multiple times, in which 576281ad6265SDimitry Andric // case the incoming value must be identical. Directly reuse the already 576381ad6265SDimitry Andric // seen value here, to avoid expanding a constant expression multiple 576481ad6265SDimitry Andric // times. 576581ad6265SDimitry Andric auto It = Args.find(BB); 576681ad6265SDimitry Andric if (It != Args.end()) { 576781ad6265SDimitry Andric PN->addIncoming(It->second, BB); 576881ad6265SDimitry Andric continue; 576981ad6265SDimitry Andric } 577081ad6265SDimitry Andric 577181ad6265SDimitry Andric // If there already is a block for this edge (from a different phi), 577281ad6265SDimitry Andric // use it. 577381ad6265SDimitry Andric BasicBlock *EdgeBB = ConstExprEdgeBBs.lookup({BB, CurBB}); 577481ad6265SDimitry Andric if (!EdgeBB) { 577581ad6265SDimitry Andric // Otherwise, use a temporary block (that we will discard if it 577681ad6265SDimitry Andric // turns out to be unnecessary). 577781ad6265SDimitry Andric if (!PhiConstExprBB) 577881ad6265SDimitry Andric PhiConstExprBB = BasicBlock::Create(Context, "phi.constexpr", F); 577981ad6265SDimitry Andric EdgeBB = PhiConstExprBB; 578081ad6265SDimitry Andric } 578181ad6265SDimitry Andric 57820b57cec5SDimitry Andric // With the new function encoding, it is possible that operands have 57830b57cec5SDimitry Andric // negative IDs (for forward references). Use a signed VBR 57840b57cec5SDimitry Andric // representation to keep the encoding small. 578581ad6265SDimitry Andric Value *V; 57860b57cec5SDimitry Andric if (UseRelativeIDs) 578781ad6265SDimitry Andric V = getValueSigned(Record, i * 2 + 1, NextValueNo, Ty, TyID, EdgeBB); 57880b57cec5SDimitry Andric else 578981ad6265SDimitry Andric V = getValue(Record, i * 2 + 1, NextValueNo, Ty, TyID, EdgeBB); 579081ad6265SDimitry Andric if (!V) { 579181ad6265SDimitry Andric PN->deleteValue(); 579281ad6265SDimitry Andric PhiConstExprBB->eraseFromParent(); 579381ad6265SDimitry Andric return error("Invalid phi record"); 579481ad6265SDimitry Andric } 579581ad6265SDimitry Andric 579681ad6265SDimitry Andric if (EdgeBB == PhiConstExprBB && !EdgeBB->empty()) { 579781ad6265SDimitry Andric ConstExprEdgeBBs.insert({{BB, CurBB}, EdgeBB}); 579881ad6265SDimitry Andric PhiConstExprBB = nullptr; 579981ad6265SDimitry Andric } 58000b57cec5SDimitry Andric PN->addIncoming(V, BB); 580181ad6265SDimitry Andric Args.insert({BB, V}); 58020b57cec5SDimitry Andric } 58030b57cec5SDimitry Andric I = PN; 580481ad6265SDimitry Andric ResTypeID = TyID; 58058bcb0991SDimitry Andric 58068bcb0991SDimitry Andric // If there are an even number of records, the final record must be FMF. 58078bcb0991SDimitry Andric if (Record.size() % 2 == 0) { 58088bcb0991SDimitry Andric assert(isa<FPMathOperator>(I) && "Unexpected phi type"); 58098bcb0991SDimitry Andric FastMathFlags FMF = getDecodedFastMathFlags(Record[Record.size() - 1]); 58108bcb0991SDimitry Andric if (FMF.any()) 58118bcb0991SDimitry Andric I->setFastMathFlags(FMF); 58128bcb0991SDimitry Andric } 58138bcb0991SDimitry Andric 58140b57cec5SDimitry Andric break; 58150b57cec5SDimitry Andric } 58160b57cec5SDimitry Andric 58170b57cec5SDimitry Andric case bitc::FUNC_CODE_INST_LANDINGPAD: 58180b57cec5SDimitry Andric case bitc::FUNC_CODE_INST_LANDINGPAD_OLD: { 58190b57cec5SDimitry Andric // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?] 58200b57cec5SDimitry Andric unsigned Idx = 0; 58210b57cec5SDimitry Andric if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD) { 58220b57cec5SDimitry Andric if (Record.size() < 3) 58230b57cec5SDimitry Andric return error("Invalid record"); 58240b57cec5SDimitry Andric } else { 58250b57cec5SDimitry Andric assert(BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD); 58260b57cec5SDimitry Andric if (Record.size() < 4) 58270b57cec5SDimitry Andric return error("Invalid record"); 58280b57cec5SDimitry Andric } 582981ad6265SDimitry Andric ResTypeID = Record[Idx++]; 583081ad6265SDimitry Andric Type *Ty = getTypeByID(ResTypeID); 58310b57cec5SDimitry Andric if (!Ty) 58320b57cec5SDimitry Andric return error("Invalid record"); 58330b57cec5SDimitry Andric if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD) { 58340b57cec5SDimitry Andric Value *PersFn = nullptr; 583581ad6265SDimitry Andric unsigned PersFnTypeID; 583681ad6265SDimitry Andric if (getValueTypePair(Record, Idx, NextValueNo, PersFn, PersFnTypeID, 583781ad6265SDimitry Andric nullptr)) 58380b57cec5SDimitry Andric return error("Invalid record"); 58390b57cec5SDimitry Andric 58400b57cec5SDimitry Andric if (!F->hasPersonalityFn()) 58410b57cec5SDimitry Andric F->setPersonalityFn(cast<Constant>(PersFn)); 58420b57cec5SDimitry Andric else if (F->getPersonalityFn() != cast<Constant>(PersFn)) 58430b57cec5SDimitry Andric return error("Personality function mismatch"); 58440b57cec5SDimitry Andric } 58450b57cec5SDimitry Andric 58460b57cec5SDimitry Andric bool IsCleanup = !!Record[Idx++]; 58470b57cec5SDimitry Andric unsigned NumClauses = Record[Idx++]; 58480b57cec5SDimitry Andric LandingPadInst *LP = LandingPadInst::Create(Ty, NumClauses); 58490b57cec5SDimitry Andric LP->setCleanup(IsCleanup); 58500b57cec5SDimitry Andric for (unsigned J = 0; J != NumClauses; ++J) { 58510b57cec5SDimitry Andric LandingPadInst::ClauseType CT = 58520b57cec5SDimitry Andric LandingPadInst::ClauseType(Record[Idx++]); (void)CT; 58530b57cec5SDimitry Andric Value *Val; 585481ad6265SDimitry Andric unsigned ValTypeID; 58550b57cec5SDimitry Andric 585681ad6265SDimitry Andric if (getValueTypePair(Record, Idx, NextValueNo, Val, ValTypeID, 585781ad6265SDimitry Andric nullptr)) { 58580b57cec5SDimitry Andric delete LP; 58590b57cec5SDimitry Andric return error("Invalid record"); 58600b57cec5SDimitry Andric } 58610b57cec5SDimitry Andric 58620b57cec5SDimitry Andric assert((CT != LandingPadInst::Catch || 58630b57cec5SDimitry Andric !isa<ArrayType>(Val->getType())) && 58640b57cec5SDimitry Andric "Catch clause has a invalid type!"); 58650b57cec5SDimitry Andric assert((CT != LandingPadInst::Filter || 58660b57cec5SDimitry Andric isa<ArrayType>(Val->getType())) && 58670b57cec5SDimitry Andric "Filter clause has invalid type!"); 58680b57cec5SDimitry Andric LP->addClause(cast<Constant>(Val)); 58690b57cec5SDimitry Andric } 58700b57cec5SDimitry Andric 58710b57cec5SDimitry Andric I = LP; 58720b57cec5SDimitry Andric InstructionList.push_back(I); 58730b57cec5SDimitry Andric break; 58740b57cec5SDimitry Andric } 58750b57cec5SDimitry Andric 58760b57cec5SDimitry Andric case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align] 587781ad6265SDimitry Andric if (Record.size() != 4 && Record.size() != 5) 58780b57cec5SDimitry Andric return error("Invalid record"); 5879e8d8bef9SDimitry Andric using APV = AllocaPackedValues; 5880e8d8bef9SDimitry Andric const uint64_t Rec = Record[3]; 5881e8d8bef9SDimitry Andric const bool InAlloca = Bitfield::get<APV::UsedWithInAlloca>(Rec); 5882e8d8bef9SDimitry Andric const bool SwiftError = Bitfield::get<APV::SwiftError>(Rec); 588381ad6265SDimitry Andric unsigned TyID = Record[0]; 588481ad6265SDimitry Andric Type *Ty = getTypeByID(TyID); 5885e8d8bef9SDimitry Andric if (!Bitfield::get<APV::ExplicitType>(Rec)) { 588681ad6265SDimitry Andric TyID = getContainedTypeID(TyID); 588781ad6265SDimitry Andric Ty = getTypeByID(TyID); 588881ad6265SDimitry Andric if (!Ty) 588981ad6265SDimitry Andric return error("Missing element type for old-style alloca"); 58900b57cec5SDimitry Andric } 589181ad6265SDimitry Andric unsigned OpTyID = Record[1]; 589281ad6265SDimitry Andric Type *OpTy = getTypeByID(OpTyID); 589381ad6265SDimitry Andric Value *Size = getFnValueByID(Record[2], OpTy, OpTyID, CurBB); 58948bcb0991SDimitry Andric MaybeAlign Align; 5895349cc55cSDimitry Andric uint64_t AlignExp = 5896349cc55cSDimitry Andric Bitfield::get<APV::AlignLower>(Rec) | 5897349cc55cSDimitry Andric (Bitfield::get<APV::AlignUpper>(Rec) << APV::AlignLower::Bits); 5898349cc55cSDimitry Andric if (Error Err = parseAlignmentValue(AlignExp, Align)) { 58990b57cec5SDimitry Andric return Err; 59000b57cec5SDimitry Andric } 59010b57cec5SDimitry Andric if (!Ty || !Size) 59020b57cec5SDimitry Andric return error("Invalid record"); 59030b57cec5SDimitry Andric 59040b57cec5SDimitry Andric const DataLayout &DL = TheModule->getDataLayout(); 590581ad6265SDimitry Andric unsigned AS = Record.size() == 5 ? Record[4] : DL.getAllocaAddrSpace(); 59060b57cec5SDimitry Andric 59075ffd83dbSDimitry Andric SmallPtrSet<Type *, 4> Visited; 59085ffd83dbSDimitry Andric if (!Align && !Ty->isSized(&Visited)) 59095ffd83dbSDimitry Andric return error("alloca of unsized type"); 59105ffd83dbSDimitry Andric if (!Align) 59115ffd83dbSDimitry Andric Align = DL.getPrefTypeAlign(Ty); 59125ffd83dbSDimitry Andric 59135ffd83dbSDimitry Andric AllocaInst *AI = new AllocaInst(Ty, AS, Size, *Align); 59140b57cec5SDimitry Andric AI->setUsedWithInAlloca(InAlloca); 59150b57cec5SDimitry Andric AI->setSwiftError(SwiftError); 59160b57cec5SDimitry Andric I = AI; 591781ad6265SDimitry Andric ResTypeID = getVirtualTypeID(AI->getType(), TyID); 59180b57cec5SDimitry Andric InstructionList.push_back(I); 59190b57cec5SDimitry Andric break; 59200b57cec5SDimitry Andric } 59210b57cec5SDimitry Andric case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol] 59220b57cec5SDimitry Andric unsigned OpNum = 0; 59230b57cec5SDimitry Andric Value *Op; 592481ad6265SDimitry Andric unsigned OpTypeID; 592581ad6265SDimitry Andric if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB) || 59260b57cec5SDimitry Andric (OpNum + 2 != Record.size() && OpNum + 3 != Record.size())) 59270b57cec5SDimitry Andric return error("Invalid record"); 59280b57cec5SDimitry Andric 59290b57cec5SDimitry Andric if (!isa<PointerType>(Op->getType())) 59300b57cec5SDimitry Andric return error("Load operand is not a pointer type"); 59310b57cec5SDimitry Andric 59320b57cec5SDimitry Andric Type *Ty = nullptr; 59330b57cec5SDimitry Andric if (OpNum + 3 == Record.size()) { 593481ad6265SDimitry Andric ResTypeID = Record[OpNum++]; 593581ad6265SDimitry Andric Ty = getTypeByID(ResTypeID); 5936fe6060f1SDimitry Andric } else { 593781ad6265SDimitry Andric ResTypeID = getContainedTypeID(OpTypeID); 593881ad6265SDimitry Andric Ty = getTypeByID(ResTypeID); 593981ad6265SDimitry Andric if (!Ty) 594081ad6265SDimitry Andric return error("Missing element type for old-style load"); 5941fe6060f1SDimitry Andric } 59420b57cec5SDimitry Andric 59430b57cec5SDimitry Andric if (Error Err = typeCheckLoadStoreInst(Ty, Op->getType())) 59440b57cec5SDimitry Andric return Err; 59450b57cec5SDimitry Andric 59468bcb0991SDimitry Andric MaybeAlign Align; 59470b57cec5SDimitry Andric if (Error Err = parseAlignmentValue(Record[OpNum], Align)) 59480b57cec5SDimitry Andric return Err; 59495ffd83dbSDimitry Andric SmallPtrSet<Type *, 4> Visited; 59505ffd83dbSDimitry Andric if (!Align && !Ty->isSized(&Visited)) 59515ffd83dbSDimitry Andric return error("load of unsized type"); 59525ffd83dbSDimitry Andric if (!Align) 59535ffd83dbSDimitry Andric Align = TheModule->getDataLayout().getABITypeAlign(Ty); 59545ffd83dbSDimitry Andric I = new LoadInst(Ty, Op, "", Record[OpNum + 1], *Align); 59550b57cec5SDimitry Andric InstructionList.push_back(I); 59560b57cec5SDimitry Andric break; 59570b57cec5SDimitry Andric } 59580b57cec5SDimitry Andric case bitc::FUNC_CODE_INST_LOADATOMIC: { 59590b57cec5SDimitry Andric // LOADATOMIC: [opty, op, align, vol, ordering, ssid] 59600b57cec5SDimitry Andric unsigned OpNum = 0; 59610b57cec5SDimitry Andric Value *Op; 596281ad6265SDimitry Andric unsigned OpTypeID; 596381ad6265SDimitry Andric if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB) || 59640b57cec5SDimitry Andric (OpNum + 4 != Record.size() && OpNum + 5 != Record.size())) 59650b57cec5SDimitry Andric return error("Invalid record"); 59660b57cec5SDimitry Andric 59670b57cec5SDimitry Andric if (!isa<PointerType>(Op->getType())) 59680b57cec5SDimitry Andric return error("Load operand is not a pointer type"); 59690b57cec5SDimitry Andric 59700b57cec5SDimitry Andric Type *Ty = nullptr; 59710b57cec5SDimitry Andric if (OpNum + 5 == Record.size()) { 597281ad6265SDimitry Andric ResTypeID = Record[OpNum++]; 597381ad6265SDimitry Andric Ty = getTypeByID(ResTypeID); 5974fe6060f1SDimitry Andric } else { 597581ad6265SDimitry Andric ResTypeID = getContainedTypeID(OpTypeID); 597681ad6265SDimitry Andric Ty = getTypeByID(ResTypeID); 597781ad6265SDimitry Andric if (!Ty) 597881ad6265SDimitry Andric return error("Missing element type for old style atomic load"); 5979fe6060f1SDimitry Andric } 59800b57cec5SDimitry Andric 59810b57cec5SDimitry Andric if (Error Err = typeCheckLoadStoreInst(Ty, Op->getType())) 59820b57cec5SDimitry Andric return Err; 59830b57cec5SDimitry Andric 59840b57cec5SDimitry Andric AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]); 59850b57cec5SDimitry Andric if (Ordering == AtomicOrdering::NotAtomic || 59860b57cec5SDimitry Andric Ordering == AtomicOrdering::Release || 59870b57cec5SDimitry Andric Ordering == AtomicOrdering::AcquireRelease) 59880b57cec5SDimitry Andric return error("Invalid record"); 59890b57cec5SDimitry Andric if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0) 59900b57cec5SDimitry Andric return error("Invalid record"); 59910b57cec5SDimitry Andric SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]); 59920b57cec5SDimitry Andric 59938bcb0991SDimitry Andric MaybeAlign Align; 59940b57cec5SDimitry Andric if (Error Err = parseAlignmentValue(Record[OpNum], Align)) 59950b57cec5SDimitry Andric return Err; 59965ffd83dbSDimitry Andric if (!Align) 59975ffd83dbSDimitry Andric return error("Alignment missing from atomic load"); 59985ffd83dbSDimitry Andric I = new LoadInst(Ty, Op, "", Record[OpNum + 1], *Align, Ordering, SSID); 59990b57cec5SDimitry Andric InstructionList.push_back(I); 60000b57cec5SDimitry Andric break; 60010b57cec5SDimitry Andric } 60020b57cec5SDimitry Andric case bitc::FUNC_CODE_INST_STORE: 60030b57cec5SDimitry Andric case bitc::FUNC_CODE_INST_STORE_OLD: { // STORE2:[ptrty, ptr, val, align, vol] 60040b57cec5SDimitry Andric unsigned OpNum = 0; 60050b57cec5SDimitry Andric Value *Val, *Ptr; 600681ad6265SDimitry Andric unsigned PtrTypeID, ValTypeID; 600781ad6265SDimitry Andric if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB)) 600881ad6265SDimitry Andric return error("Invalid record"); 600981ad6265SDimitry Andric 601081ad6265SDimitry Andric if (BitCode == bitc::FUNC_CODE_INST_STORE) { 601181ad6265SDimitry Andric if (getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID, CurBB)) 601281ad6265SDimitry Andric return error("Invalid record"); 601381ad6265SDimitry Andric } else { 601481ad6265SDimitry Andric ValTypeID = getContainedTypeID(PtrTypeID); 601581ad6265SDimitry Andric if (popValue(Record, OpNum, NextValueNo, getTypeByID(ValTypeID), 601681ad6265SDimitry Andric ValTypeID, Val, CurBB)) 601781ad6265SDimitry Andric return error("Invalid record"); 601881ad6265SDimitry Andric } 601981ad6265SDimitry Andric 602081ad6265SDimitry Andric if (OpNum + 2 != Record.size()) 60210b57cec5SDimitry Andric return error("Invalid record"); 60220b57cec5SDimitry Andric 60230b57cec5SDimitry Andric if (Error Err = typeCheckLoadStoreInst(Val->getType(), Ptr->getType())) 60240b57cec5SDimitry Andric return Err; 60258bcb0991SDimitry Andric MaybeAlign Align; 60260b57cec5SDimitry Andric if (Error Err = parseAlignmentValue(Record[OpNum], Align)) 60270b57cec5SDimitry Andric return Err; 60285ffd83dbSDimitry Andric SmallPtrSet<Type *, 4> Visited; 60295ffd83dbSDimitry Andric if (!Align && !Val->getType()->isSized(&Visited)) 60305ffd83dbSDimitry Andric return error("store of unsized type"); 60315ffd83dbSDimitry Andric if (!Align) 60325ffd83dbSDimitry Andric Align = TheModule->getDataLayout().getABITypeAlign(Val->getType()); 60335ffd83dbSDimitry Andric I = new StoreInst(Val, Ptr, Record[OpNum + 1], *Align); 60340b57cec5SDimitry Andric InstructionList.push_back(I); 60350b57cec5SDimitry Andric break; 60360b57cec5SDimitry Andric } 60370b57cec5SDimitry Andric case bitc::FUNC_CODE_INST_STOREATOMIC: 60380b57cec5SDimitry Andric case bitc::FUNC_CODE_INST_STOREATOMIC_OLD: { 60390b57cec5SDimitry Andric // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, ssid] 60400b57cec5SDimitry Andric unsigned OpNum = 0; 60410b57cec5SDimitry Andric Value *Val, *Ptr; 604281ad6265SDimitry Andric unsigned PtrTypeID, ValTypeID; 604381ad6265SDimitry Andric if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB) || 604481ad6265SDimitry Andric !isa<PointerType>(Ptr->getType())) 604581ad6265SDimitry Andric return error("Invalid record"); 604681ad6265SDimitry Andric if (BitCode == bitc::FUNC_CODE_INST_STOREATOMIC) { 604781ad6265SDimitry Andric if (getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID, CurBB)) 604881ad6265SDimitry Andric return error("Invalid record"); 604981ad6265SDimitry Andric } else { 605081ad6265SDimitry Andric ValTypeID = getContainedTypeID(PtrTypeID); 605181ad6265SDimitry Andric if (popValue(Record, OpNum, NextValueNo, getTypeByID(ValTypeID), 605281ad6265SDimitry Andric ValTypeID, Val, CurBB)) 605381ad6265SDimitry Andric return error("Invalid record"); 605481ad6265SDimitry Andric } 605581ad6265SDimitry Andric 605681ad6265SDimitry Andric if (OpNum + 4 != Record.size()) 60570b57cec5SDimitry Andric return error("Invalid record"); 60580b57cec5SDimitry Andric 60590b57cec5SDimitry Andric if (Error Err = typeCheckLoadStoreInst(Val->getType(), Ptr->getType())) 60600b57cec5SDimitry Andric return Err; 60610b57cec5SDimitry Andric AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]); 60620b57cec5SDimitry Andric if (Ordering == AtomicOrdering::NotAtomic || 60630b57cec5SDimitry Andric Ordering == AtomicOrdering::Acquire || 60640b57cec5SDimitry Andric Ordering == AtomicOrdering::AcquireRelease) 60650b57cec5SDimitry Andric return error("Invalid record"); 60660b57cec5SDimitry Andric SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]); 60670b57cec5SDimitry Andric if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0) 60680b57cec5SDimitry Andric return error("Invalid record"); 60690b57cec5SDimitry Andric 60708bcb0991SDimitry Andric MaybeAlign Align; 60710b57cec5SDimitry Andric if (Error Err = parseAlignmentValue(Record[OpNum], Align)) 60720b57cec5SDimitry Andric return Err; 60735ffd83dbSDimitry Andric if (!Align) 60745ffd83dbSDimitry Andric return error("Alignment missing from atomic store"); 60755ffd83dbSDimitry Andric I = new StoreInst(Val, Ptr, Record[OpNum + 1], *Align, Ordering, SSID); 60760b57cec5SDimitry Andric InstructionList.push_back(I); 60770b57cec5SDimitry Andric break; 60780b57cec5SDimitry Andric } 6079e8d8bef9SDimitry Andric case bitc::FUNC_CODE_INST_CMPXCHG_OLD: { 6080e8d8bef9SDimitry Andric // CMPXCHG_OLD: [ptrty, ptr, cmp, val, vol, ordering, synchscope, 6081e8d8bef9SDimitry Andric // failure_ordering?, weak?] 6082e8d8bef9SDimitry Andric const size_t NumRecords = Record.size(); 60830b57cec5SDimitry Andric unsigned OpNum = 0; 6084e8d8bef9SDimitry Andric Value *Ptr = nullptr; 608581ad6265SDimitry Andric unsigned PtrTypeID; 608681ad6265SDimitry Andric if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB)) 60870b57cec5SDimitry Andric return error("Invalid record"); 60880b57cec5SDimitry Andric 60890b57cec5SDimitry Andric if (!isa<PointerType>(Ptr->getType())) 60900b57cec5SDimitry Andric return error("Cmpxchg operand is not a pointer type"); 60910b57cec5SDimitry Andric 6092e8d8bef9SDimitry Andric Value *Cmp = nullptr; 609381ad6265SDimitry Andric unsigned CmpTypeID = getContainedTypeID(PtrTypeID); 609481ad6265SDimitry Andric if (popValue(Record, OpNum, NextValueNo, getTypeByID(CmpTypeID), 609581ad6265SDimitry Andric CmpTypeID, Cmp, CurBB)) 60960b57cec5SDimitry Andric return error("Invalid record"); 6097e8d8bef9SDimitry Andric 6098e8d8bef9SDimitry Andric Value *New = nullptr; 609981ad6265SDimitry Andric if (popValue(Record, OpNum, NextValueNo, Cmp->getType(), CmpTypeID, 610081ad6265SDimitry Andric New, CurBB) || 6101e8d8bef9SDimitry Andric NumRecords < OpNum + 3 || NumRecords > OpNum + 5) 61020b57cec5SDimitry Andric return error("Invalid record"); 61030b57cec5SDimitry Andric 6104e8d8bef9SDimitry Andric const AtomicOrdering SuccessOrdering = 6105e8d8bef9SDimitry Andric getDecodedOrdering(Record[OpNum + 1]); 61060b57cec5SDimitry Andric if (SuccessOrdering == AtomicOrdering::NotAtomic || 61070b57cec5SDimitry Andric SuccessOrdering == AtomicOrdering::Unordered) 61080b57cec5SDimitry Andric return error("Invalid record"); 6109e8d8bef9SDimitry Andric 6110e8d8bef9SDimitry Andric const SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 2]); 61110b57cec5SDimitry Andric 61120b57cec5SDimitry Andric if (Error Err = typeCheckLoadStoreInst(Cmp->getType(), Ptr->getType())) 61130b57cec5SDimitry Andric return Err; 61140b57cec5SDimitry Andric 6115e8d8bef9SDimitry Andric const AtomicOrdering FailureOrdering = 6116e8d8bef9SDimitry Andric NumRecords < 7 6117e8d8bef9SDimitry Andric ? AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering) 6118e8d8bef9SDimitry Andric : getDecodedOrdering(Record[OpNum + 3]); 6119e8d8bef9SDimitry Andric 6120fe6060f1SDimitry Andric if (FailureOrdering == AtomicOrdering::NotAtomic || 6121fe6060f1SDimitry Andric FailureOrdering == AtomicOrdering::Unordered) 6122fe6060f1SDimitry Andric return error("Invalid record"); 6123fe6060f1SDimitry Andric 6124e8d8bef9SDimitry Andric const Align Alignment( 61255ffd83dbSDimitry Andric TheModule->getDataLayout().getTypeStoreSize(Cmp->getType())); 6126e8d8bef9SDimitry Andric 61275ffd83dbSDimitry Andric I = new AtomicCmpXchgInst(Ptr, Cmp, New, Alignment, SuccessOrdering, 61285ffd83dbSDimitry Andric FailureOrdering, SSID); 61290b57cec5SDimitry Andric cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]); 61300b57cec5SDimitry Andric 6131e8d8bef9SDimitry Andric if (NumRecords < 8) { 61320b57cec5SDimitry Andric // Before weak cmpxchgs existed, the instruction simply returned the 61330b57cec5SDimitry Andric // value loaded from memory, so bitcode files from that era will be 61340b57cec5SDimitry Andric // expecting the first component of a modern cmpxchg. 6135bdd1243dSDimitry Andric I->insertInto(CurBB, CurBB->end()); 61360b57cec5SDimitry Andric I = ExtractValueInst::Create(I, 0); 613781ad6265SDimitry Andric ResTypeID = CmpTypeID; 61380b57cec5SDimitry Andric } else { 61390b57cec5SDimitry Andric cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum + 4]); 614081ad6265SDimitry Andric unsigned I1TypeID = getVirtualTypeID(Type::getInt1Ty(Context)); 614181ad6265SDimitry Andric ResTypeID = getVirtualTypeID(I->getType(), {CmpTypeID, I1TypeID}); 61420b57cec5SDimitry Andric } 61430b57cec5SDimitry Andric 61440b57cec5SDimitry Andric InstructionList.push_back(I); 61450b57cec5SDimitry Andric break; 61460b57cec5SDimitry Andric } 6147e8d8bef9SDimitry Andric case bitc::FUNC_CODE_INST_CMPXCHG: { 6148e8d8bef9SDimitry Andric // CMPXCHG: [ptrty, ptr, cmp, val, vol, success_ordering, synchscope, 6149fe6060f1SDimitry Andric // failure_ordering, weak, align?] 6150e8d8bef9SDimitry Andric const size_t NumRecords = Record.size(); 6151e8d8bef9SDimitry Andric unsigned OpNum = 0; 6152e8d8bef9SDimitry Andric Value *Ptr = nullptr; 615381ad6265SDimitry Andric unsigned PtrTypeID; 615481ad6265SDimitry Andric if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB)) 6155e8d8bef9SDimitry Andric return error("Invalid record"); 6156e8d8bef9SDimitry Andric 6157e8d8bef9SDimitry Andric if (!isa<PointerType>(Ptr->getType())) 6158e8d8bef9SDimitry Andric return error("Cmpxchg operand is not a pointer type"); 6159e8d8bef9SDimitry Andric 6160e8d8bef9SDimitry Andric Value *Cmp = nullptr; 616181ad6265SDimitry Andric unsigned CmpTypeID; 616281ad6265SDimitry Andric if (getValueTypePair(Record, OpNum, NextValueNo, Cmp, CmpTypeID, CurBB)) 6163e8d8bef9SDimitry Andric return error("Invalid record"); 6164e8d8bef9SDimitry Andric 6165e8d8bef9SDimitry Andric Value *Val = nullptr; 616681ad6265SDimitry Andric if (popValue(Record, OpNum, NextValueNo, Cmp->getType(), CmpTypeID, Val, 616781ad6265SDimitry Andric CurBB)) 6168e8d8bef9SDimitry Andric return error("Invalid record"); 6169e8d8bef9SDimitry Andric 6170fe6060f1SDimitry Andric if (NumRecords < OpNum + 3 || NumRecords > OpNum + 6) 6171fe6060f1SDimitry Andric return error("Invalid record"); 6172fe6060f1SDimitry Andric 6173fe6060f1SDimitry Andric const bool IsVol = Record[OpNum]; 6174fe6060f1SDimitry Andric 6175e8d8bef9SDimitry Andric const AtomicOrdering SuccessOrdering = 6176e8d8bef9SDimitry Andric getDecodedOrdering(Record[OpNum + 1]); 6177fe6060f1SDimitry Andric if (!AtomicCmpXchgInst::isValidSuccessOrdering(SuccessOrdering)) 6178fe6060f1SDimitry Andric return error("Invalid cmpxchg success ordering"); 6179e8d8bef9SDimitry Andric 6180e8d8bef9SDimitry Andric const SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 2]); 6181e8d8bef9SDimitry Andric 6182e8d8bef9SDimitry Andric if (Error Err = typeCheckLoadStoreInst(Cmp->getType(), Ptr->getType())) 6183e8d8bef9SDimitry Andric return Err; 6184e8d8bef9SDimitry Andric 6185e8d8bef9SDimitry Andric const AtomicOrdering FailureOrdering = 6186e8d8bef9SDimitry Andric getDecodedOrdering(Record[OpNum + 3]); 6187fe6060f1SDimitry Andric if (!AtomicCmpXchgInst::isValidFailureOrdering(FailureOrdering)) 6188fe6060f1SDimitry Andric return error("Invalid cmpxchg failure ordering"); 6189e8d8bef9SDimitry Andric 6190fe6060f1SDimitry Andric const bool IsWeak = Record[OpNum + 4]; 6191e8d8bef9SDimitry Andric 6192fe6060f1SDimitry Andric MaybeAlign Alignment; 6193fe6060f1SDimitry Andric 6194fe6060f1SDimitry Andric if (NumRecords == (OpNum + 6)) { 6195fe6060f1SDimitry Andric if (Error Err = parseAlignmentValue(Record[OpNum + 5], Alignment)) 6196fe6060f1SDimitry Andric return Err; 6197fe6060f1SDimitry Andric } 6198fe6060f1SDimitry Andric if (!Alignment) 6199fe6060f1SDimitry Andric Alignment = 6200fe6060f1SDimitry Andric Align(TheModule->getDataLayout().getTypeStoreSize(Cmp->getType())); 6201fe6060f1SDimitry Andric 6202fe6060f1SDimitry Andric I = new AtomicCmpXchgInst(Ptr, Cmp, Val, *Alignment, SuccessOrdering, 6203e8d8bef9SDimitry Andric FailureOrdering, SSID); 6204fe6060f1SDimitry Andric cast<AtomicCmpXchgInst>(I)->setVolatile(IsVol); 6205fe6060f1SDimitry Andric cast<AtomicCmpXchgInst>(I)->setWeak(IsWeak); 6206e8d8bef9SDimitry Andric 620781ad6265SDimitry Andric unsigned I1TypeID = getVirtualTypeID(Type::getInt1Ty(Context)); 620881ad6265SDimitry Andric ResTypeID = getVirtualTypeID(I->getType(), {CmpTypeID, I1TypeID}); 620981ad6265SDimitry Andric 6210e8d8bef9SDimitry Andric InstructionList.push_back(I); 6211e8d8bef9SDimitry Andric break; 6212e8d8bef9SDimitry Andric } 6213fe6060f1SDimitry Andric case bitc::FUNC_CODE_INST_ATOMICRMW_OLD: 62140b57cec5SDimitry Andric case bitc::FUNC_CODE_INST_ATOMICRMW: { 6215fe6060f1SDimitry Andric // ATOMICRMW_OLD: [ptrty, ptr, val, op, vol, ordering, ssid, align?] 6216fe6060f1SDimitry Andric // ATOMICRMW: [ptrty, ptr, valty, val, op, vol, ordering, ssid, align?] 6217fe6060f1SDimitry Andric const size_t NumRecords = Record.size(); 62180b57cec5SDimitry Andric unsigned OpNum = 0; 6219fe6060f1SDimitry Andric 6220fe6060f1SDimitry Andric Value *Ptr = nullptr; 622181ad6265SDimitry Andric unsigned PtrTypeID; 622281ad6265SDimitry Andric if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB)) 62230b57cec5SDimitry Andric return error("Invalid record"); 6224fe6060f1SDimitry Andric 6225fe6060f1SDimitry Andric if (!isa<PointerType>(Ptr->getType())) 6226fe6060f1SDimitry Andric return error("Invalid record"); 6227fe6060f1SDimitry Andric 6228fe6060f1SDimitry Andric Value *Val = nullptr; 622981ad6265SDimitry Andric unsigned ValTypeID = InvalidTypeID; 6230fe6060f1SDimitry Andric if (BitCode == bitc::FUNC_CODE_INST_ATOMICRMW_OLD) { 623181ad6265SDimitry Andric ValTypeID = getContainedTypeID(PtrTypeID); 6232fe6060f1SDimitry Andric if (popValue(Record, OpNum, NextValueNo, 623381ad6265SDimitry Andric getTypeByID(ValTypeID), ValTypeID, Val, CurBB)) 6234fe6060f1SDimitry Andric return error("Invalid record"); 6235fe6060f1SDimitry Andric } else { 623681ad6265SDimitry Andric if (getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID, CurBB)) 6237fe6060f1SDimitry Andric return error("Invalid record"); 6238fe6060f1SDimitry Andric } 6239fe6060f1SDimitry Andric 6240fe6060f1SDimitry Andric if (!(NumRecords == (OpNum + 4) || NumRecords == (OpNum + 5))) 6241fe6060f1SDimitry Andric return error("Invalid record"); 6242fe6060f1SDimitry Andric 6243fe6060f1SDimitry Andric const AtomicRMWInst::BinOp Operation = 6244fe6060f1SDimitry Andric getDecodedRMWOperation(Record[OpNum]); 62450b57cec5SDimitry Andric if (Operation < AtomicRMWInst::FIRST_BINOP || 62460b57cec5SDimitry Andric Operation > AtomicRMWInst::LAST_BINOP) 62470b57cec5SDimitry Andric return error("Invalid record"); 6248fe6060f1SDimitry Andric 6249fe6060f1SDimitry Andric const bool IsVol = Record[OpNum + 1]; 6250fe6060f1SDimitry Andric 6251fe6060f1SDimitry Andric const AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]); 62520b57cec5SDimitry Andric if (Ordering == AtomicOrdering::NotAtomic || 62530b57cec5SDimitry Andric Ordering == AtomicOrdering::Unordered) 62540b57cec5SDimitry Andric return error("Invalid record"); 6255fe6060f1SDimitry Andric 6256fe6060f1SDimitry Andric const SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]); 6257fe6060f1SDimitry Andric 6258fe6060f1SDimitry Andric MaybeAlign Alignment; 6259fe6060f1SDimitry Andric 6260fe6060f1SDimitry Andric if (NumRecords == (OpNum + 5)) { 6261fe6060f1SDimitry Andric if (Error Err = parseAlignmentValue(Record[OpNum + 4], Alignment)) 6262fe6060f1SDimitry Andric return Err; 6263fe6060f1SDimitry Andric } 6264fe6060f1SDimitry Andric 6265fe6060f1SDimitry Andric if (!Alignment) 6266fe6060f1SDimitry Andric Alignment = 6267fe6060f1SDimitry Andric Align(TheModule->getDataLayout().getTypeStoreSize(Val->getType())); 6268fe6060f1SDimitry Andric 6269fe6060f1SDimitry Andric I = new AtomicRMWInst(Operation, Ptr, Val, *Alignment, Ordering, SSID); 627081ad6265SDimitry Andric ResTypeID = ValTypeID; 6271fe6060f1SDimitry Andric cast<AtomicRMWInst>(I)->setVolatile(IsVol); 6272fe6060f1SDimitry Andric 62730b57cec5SDimitry Andric InstructionList.push_back(I); 62740b57cec5SDimitry Andric break; 62750b57cec5SDimitry Andric } 62760b57cec5SDimitry Andric case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, ssid] 62770b57cec5SDimitry Andric if (2 != Record.size()) 62780b57cec5SDimitry Andric return error("Invalid record"); 62790b57cec5SDimitry Andric AtomicOrdering Ordering = getDecodedOrdering(Record[0]); 62800b57cec5SDimitry Andric if (Ordering == AtomicOrdering::NotAtomic || 62810b57cec5SDimitry Andric Ordering == AtomicOrdering::Unordered || 62820b57cec5SDimitry Andric Ordering == AtomicOrdering::Monotonic) 62830b57cec5SDimitry Andric return error("Invalid record"); 62840b57cec5SDimitry Andric SyncScope::ID SSID = getDecodedSyncScopeID(Record[1]); 62850b57cec5SDimitry Andric I = new FenceInst(Context, Ordering, SSID); 62860b57cec5SDimitry Andric InstructionList.push_back(I); 62870b57cec5SDimitry Andric break; 62880b57cec5SDimitry Andric } 62890b57cec5SDimitry Andric case bitc::FUNC_CODE_INST_CALL: { 62900b57cec5SDimitry Andric // CALL: [paramattrs, cc, fmf, fnty, fnid, arg0, arg1...] 62910b57cec5SDimitry Andric if (Record.size() < 3) 62920b57cec5SDimitry Andric return error("Invalid record"); 62930b57cec5SDimitry Andric 62940b57cec5SDimitry Andric unsigned OpNum = 0; 62950b57cec5SDimitry Andric AttributeList PAL = getAttributes(Record[OpNum++]); 62960b57cec5SDimitry Andric unsigned CCInfo = Record[OpNum++]; 62970b57cec5SDimitry Andric 62980b57cec5SDimitry Andric FastMathFlags FMF; 62990b57cec5SDimitry Andric if ((CCInfo >> bitc::CALL_FMF) & 1) { 63000b57cec5SDimitry Andric FMF = getDecodedFastMathFlags(Record[OpNum++]); 63010b57cec5SDimitry Andric if (!FMF.any()) 63020b57cec5SDimitry Andric return error("Fast math flags indicator set for call with no FMF"); 63030b57cec5SDimitry Andric } 63040b57cec5SDimitry Andric 630581ad6265SDimitry Andric unsigned FTyID = InvalidTypeID; 63060b57cec5SDimitry Andric FunctionType *FTy = nullptr; 63070b57cec5SDimitry Andric if ((CCInfo >> bitc::CALL_EXPLICIT_TYPE) & 1) { 630881ad6265SDimitry Andric FTyID = Record[OpNum++]; 630981ad6265SDimitry Andric FTy = dyn_cast_or_null<FunctionType>(getTypeByID(FTyID)); 6310fe6060f1SDimitry Andric if (!FTy) 63110b57cec5SDimitry Andric return error("Explicit call type is not a function type"); 63120b57cec5SDimitry Andric } 63130b57cec5SDimitry Andric 63140b57cec5SDimitry Andric Value *Callee; 631581ad6265SDimitry Andric unsigned CalleeTypeID; 631681ad6265SDimitry Andric if (getValueTypePair(Record, OpNum, NextValueNo, Callee, CalleeTypeID, 631781ad6265SDimitry Andric CurBB)) 63180b57cec5SDimitry Andric return error("Invalid record"); 63190b57cec5SDimitry Andric 63200b57cec5SDimitry Andric PointerType *OpTy = dyn_cast<PointerType>(Callee->getType()); 63210b57cec5SDimitry Andric if (!OpTy) 63220b57cec5SDimitry Andric return error("Callee is not a pointer type"); 63230b57cec5SDimitry Andric if (!FTy) { 632481ad6265SDimitry Andric FTyID = getContainedTypeID(CalleeTypeID); 632581ad6265SDimitry Andric FTy = dyn_cast_or_null<FunctionType>(getTypeByID(FTyID)); 6326fe6060f1SDimitry Andric if (!FTy) 63270b57cec5SDimitry Andric return error("Callee is not of pointer to function type"); 6328*fe013be4SDimitry Andric } 63290b57cec5SDimitry Andric if (Record.size() < FTy->getNumParams() + OpNum) 63300b57cec5SDimitry Andric return error("Insufficient operands to call"); 63310b57cec5SDimitry Andric 63320b57cec5SDimitry Andric SmallVector<Value*, 16> Args; 633381ad6265SDimitry Andric SmallVector<unsigned, 16> ArgTyIDs; 63340b57cec5SDimitry Andric // Read the fixed params. 63350b57cec5SDimitry Andric for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) { 633681ad6265SDimitry Andric unsigned ArgTyID = getContainedTypeID(FTyID, i + 1); 63370b57cec5SDimitry Andric if (FTy->getParamType(i)->isLabelTy()) 63380b57cec5SDimitry Andric Args.push_back(getBasicBlock(Record[OpNum])); 63390b57cec5SDimitry Andric else 63400b57cec5SDimitry Andric Args.push_back(getValue(Record, OpNum, NextValueNo, 634181ad6265SDimitry Andric FTy->getParamType(i), ArgTyID, CurBB)); 634281ad6265SDimitry Andric ArgTyIDs.push_back(ArgTyID); 63430b57cec5SDimitry Andric if (!Args.back()) 63440b57cec5SDimitry Andric return error("Invalid record"); 63450b57cec5SDimitry Andric } 63460b57cec5SDimitry Andric 63470b57cec5SDimitry Andric // Read type/value pairs for varargs params. 63480b57cec5SDimitry Andric if (!FTy->isVarArg()) { 63490b57cec5SDimitry Andric if (OpNum != Record.size()) 63500b57cec5SDimitry Andric return error("Invalid record"); 63510b57cec5SDimitry Andric } else { 63520b57cec5SDimitry Andric while (OpNum != Record.size()) { 63530b57cec5SDimitry Andric Value *Op; 635481ad6265SDimitry Andric unsigned OpTypeID; 635581ad6265SDimitry Andric if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB)) 63560b57cec5SDimitry Andric return error("Invalid record"); 63570b57cec5SDimitry Andric Args.push_back(Op); 635881ad6265SDimitry Andric ArgTyIDs.push_back(OpTypeID); 63590b57cec5SDimitry Andric } 63600b57cec5SDimitry Andric } 63610b57cec5SDimitry Andric 636281ad6265SDimitry Andric // Upgrade the bundles if needed. 636381ad6265SDimitry Andric if (!OperandBundles.empty()) 636481ad6265SDimitry Andric UpgradeOperandBundles(OperandBundles); 636581ad6265SDimitry Andric 63660b57cec5SDimitry Andric I = CallInst::Create(FTy, Callee, Args, OperandBundles); 636781ad6265SDimitry Andric ResTypeID = getContainedTypeID(FTyID); 63680b57cec5SDimitry Andric OperandBundles.clear(); 63690b57cec5SDimitry Andric InstructionList.push_back(I); 63700b57cec5SDimitry Andric cast<CallInst>(I)->setCallingConv( 63710b57cec5SDimitry Andric static_cast<CallingConv::ID>((0x7ff & CCInfo) >> bitc::CALL_CCONV)); 63720b57cec5SDimitry Andric CallInst::TailCallKind TCK = CallInst::TCK_None; 63730b57cec5SDimitry Andric if (CCInfo & 1 << bitc::CALL_TAIL) 63740b57cec5SDimitry Andric TCK = CallInst::TCK_Tail; 63750b57cec5SDimitry Andric if (CCInfo & (1 << bitc::CALL_MUSTTAIL)) 63760b57cec5SDimitry Andric TCK = CallInst::TCK_MustTail; 63770b57cec5SDimitry Andric if (CCInfo & (1 << bitc::CALL_NOTAIL)) 63780b57cec5SDimitry Andric TCK = CallInst::TCK_NoTail; 63790b57cec5SDimitry Andric cast<CallInst>(I)->setTailCallKind(TCK); 63800b57cec5SDimitry Andric cast<CallInst>(I)->setAttributes(PAL); 638181ad6265SDimitry Andric if (Error Err = propagateAttributeTypes(cast<CallBase>(I), ArgTyIDs)) { 638281ad6265SDimitry Andric I->deleteValue(); 638381ad6265SDimitry Andric return Err; 638481ad6265SDimitry Andric } 63850b57cec5SDimitry Andric if (FMF.any()) { 63860b57cec5SDimitry Andric if (!isa<FPMathOperator>(I)) 63870b57cec5SDimitry Andric return error("Fast-math-flags specified for call without " 63880b57cec5SDimitry Andric "floating-point scalar or vector return type"); 63890b57cec5SDimitry Andric I->setFastMathFlags(FMF); 63900b57cec5SDimitry Andric } 63910b57cec5SDimitry Andric break; 63920b57cec5SDimitry Andric } 63930b57cec5SDimitry Andric case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty] 63940b57cec5SDimitry Andric if (Record.size() < 3) 63950b57cec5SDimitry Andric return error("Invalid record"); 639681ad6265SDimitry Andric unsigned OpTyID = Record[0]; 639781ad6265SDimitry Andric Type *OpTy = getTypeByID(OpTyID); 639881ad6265SDimitry Andric Value *Op = getValue(Record, 1, NextValueNo, OpTy, OpTyID, CurBB); 639981ad6265SDimitry Andric ResTypeID = Record[2]; 640081ad6265SDimitry Andric Type *ResTy = getTypeByID(ResTypeID); 64010b57cec5SDimitry Andric if (!OpTy || !Op || !ResTy) 64020b57cec5SDimitry Andric return error("Invalid record"); 64030b57cec5SDimitry Andric I = new VAArgInst(Op, ResTy); 64040b57cec5SDimitry Andric InstructionList.push_back(I); 64050b57cec5SDimitry Andric break; 64060b57cec5SDimitry Andric } 64070b57cec5SDimitry Andric 64080b57cec5SDimitry Andric case bitc::FUNC_CODE_OPERAND_BUNDLE: { 64090b57cec5SDimitry Andric // A call or an invoke can be optionally prefixed with some variable 64100b57cec5SDimitry Andric // number of operand bundle blocks. These blocks are read into 64110b57cec5SDimitry Andric // OperandBundles and consumed at the next call or invoke instruction. 64120b57cec5SDimitry Andric 6413e8d8bef9SDimitry Andric if (Record.empty() || Record[0] >= BundleTags.size()) 64140b57cec5SDimitry Andric return error("Invalid record"); 64150b57cec5SDimitry Andric 64160b57cec5SDimitry Andric std::vector<Value *> Inputs; 64170b57cec5SDimitry Andric 64180b57cec5SDimitry Andric unsigned OpNum = 1; 64190b57cec5SDimitry Andric while (OpNum != Record.size()) { 64200b57cec5SDimitry Andric Value *Op; 642181ad6265SDimitry Andric unsigned OpTypeID; 642281ad6265SDimitry Andric if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB)) 64230b57cec5SDimitry Andric return error("Invalid record"); 64240b57cec5SDimitry Andric Inputs.push_back(Op); 64250b57cec5SDimitry Andric } 64260b57cec5SDimitry Andric 64270b57cec5SDimitry Andric OperandBundles.emplace_back(BundleTags[Record[0]], std::move(Inputs)); 64280b57cec5SDimitry Andric continue; 64290b57cec5SDimitry Andric } 6430480093f4SDimitry Andric 6431480093f4SDimitry Andric case bitc::FUNC_CODE_INST_FREEZE: { // FREEZE: [opty,opval] 6432480093f4SDimitry Andric unsigned OpNum = 0; 6433480093f4SDimitry Andric Value *Op = nullptr; 643481ad6265SDimitry Andric unsigned OpTypeID; 643581ad6265SDimitry Andric if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB)) 6436480093f4SDimitry Andric return error("Invalid record"); 6437480093f4SDimitry Andric if (OpNum != Record.size()) 6438480093f4SDimitry Andric return error("Invalid record"); 6439480093f4SDimitry Andric 6440480093f4SDimitry Andric I = new FreezeInst(Op); 644181ad6265SDimitry Andric ResTypeID = OpTypeID; 6442480093f4SDimitry Andric InstructionList.push_back(I); 6443480093f4SDimitry Andric break; 6444480093f4SDimitry Andric } 64450b57cec5SDimitry Andric } 64460b57cec5SDimitry Andric 64470b57cec5SDimitry Andric // Add instruction to end of current BB. If there is no current BB, reject 64480b57cec5SDimitry Andric // this file. 64490b57cec5SDimitry Andric if (!CurBB) { 64500b57cec5SDimitry Andric I->deleteValue(); 64510b57cec5SDimitry Andric return error("Invalid instruction with no BB"); 64520b57cec5SDimitry Andric } 64530b57cec5SDimitry Andric if (!OperandBundles.empty()) { 64540b57cec5SDimitry Andric I->deleteValue(); 64550b57cec5SDimitry Andric return error("Operand bundles found with no consumer"); 64560b57cec5SDimitry Andric } 6457bdd1243dSDimitry Andric I->insertInto(CurBB, CurBB->end()); 64580b57cec5SDimitry Andric 64590b57cec5SDimitry Andric // If this was a terminator instruction, move to the next block. 64600b57cec5SDimitry Andric if (I->isTerminator()) { 64610b57cec5SDimitry Andric ++CurBBNo; 64620b57cec5SDimitry Andric CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr; 64630b57cec5SDimitry Andric } 64640b57cec5SDimitry Andric 64650b57cec5SDimitry Andric // Non-void values get registered in the value table for future use. 646681ad6265SDimitry Andric if (!I->getType()->isVoidTy()) { 646781ad6265SDimitry Andric assert(I->getType() == getTypeByID(ResTypeID) && 646881ad6265SDimitry Andric "Incorrect result type ID"); 646981ad6265SDimitry Andric if (Error Err = ValueList.assignValue(NextValueNo++, I, ResTypeID)) 647081ad6265SDimitry Andric return Err; 647181ad6265SDimitry Andric } 64720b57cec5SDimitry Andric } 64730b57cec5SDimitry Andric 64740b57cec5SDimitry Andric OutOfRecordLoop: 64750b57cec5SDimitry Andric 64760b57cec5SDimitry Andric if (!OperandBundles.empty()) 64770b57cec5SDimitry Andric return error("Operand bundles found with no consumer"); 64780b57cec5SDimitry Andric 64790b57cec5SDimitry Andric // Check the function list for unresolved values. 64800b57cec5SDimitry Andric if (Argument *A = dyn_cast<Argument>(ValueList.back())) { 64810b57cec5SDimitry Andric if (!A->getParent()) { 64820b57cec5SDimitry Andric // We found at least one unresolved value. Nuke them all to avoid leaks. 64830b57cec5SDimitry Andric for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){ 64840b57cec5SDimitry Andric if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) { 6485bdd1243dSDimitry Andric A->replaceAllUsesWith(PoisonValue::get(A->getType())); 64860b57cec5SDimitry Andric delete A; 64870b57cec5SDimitry Andric } 64880b57cec5SDimitry Andric } 64890b57cec5SDimitry Andric return error("Never resolved value found in function"); 64900b57cec5SDimitry Andric } 64910b57cec5SDimitry Andric } 64920b57cec5SDimitry Andric 64930b57cec5SDimitry Andric // Unexpected unresolved metadata about to be dropped. 64940b57cec5SDimitry Andric if (MDLoader->hasFwdRefs()) 64950b57cec5SDimitry Andric return error("Invalid function metadata: outgoing forward refs"); 64960b57cec5SDimitry Andric 649781ad6265SDimitry Andric if (PhiConstExprBB) 649881ad6265SDimitry Andric PhiConstExprBB->eraseFromParent(); 649981ad6265SDimitry Andric 650081ad6265SDimitry Andric for (const auto &Pair : ConstExprEdgeBBs) { 650181ad6265SDimitry Andric BasicBlock *From = Pair.first.first; 650281ad6265SDimitry Andric BasicBlock *To = Pair.first.second; 650381ad6265SDimitry Andric BasicBlock *EdgeBB = Pair.second; 650481ad6265SDimitry Andric BranchInst::Create(To, EdgeBB); 650581ad6265SDimitry Andric From->getTerminator()->replaceSuccessorWith(To, EdgeBB); 650681ad6265SDimitry Andric To->replacePhiUsesWith(From, EdgeBB); 650781ad6265SDimitry Andric EdgeBB->moveBefore(To); 650881ad6265SDimitry Andric } 650981ad6265SDimitry Andric 65100b57cec5SDimitry Andric // Trim the value list down to the size it was before we parsed this function. 65110b57cec5SDimitry Andric ValueList.shrinkTo(ModuleValueListSize); 65120b57cec5SDimitry Andric MDLoader->shrinkTo(ModuleMDLoaderSize); 65130b57cec5SDimitry Andric std::vector<BasicBlock*>().swap(FunctionBBs); 65140b57cec5SDimitry Andric return Error::success(); 65150b57cec5SDimitry Andric } 65160b57cec5SDimitry Andric 65170b57cec5SDimitry Andric /// Find the function body in the bitcode stream 65180b57cec5SDimitry Andric Error BitcodeReader::findFunctionInStream( 65190b57cec5SDimitry Andric Function *F, 65200b57cec5SDimitry Andric DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) { 65210b57cec5SDimitry Andric while (DeferredFunctionInfoIterator->second == 0) { 65220b57cec5SDimitry Andric // This is the fallback handling for the old format bitcode that 65230b57cec5SDimitry Andric // didn't contain the function index in the VST, or when we have 65240b57cec5SDimitry Andric // an anonymous function which would not have a VST entry. 65250b57cec5SDimitry Andric // Assert that we have one of those two cases. 65260b57cec5SDimitry Andric assert(VSTOffset == 0 || !F->hasName()); 65270b57cec5SDimitry Andric // Parse the next body in the stream and set its position in the 65280b57cec5SDimitry Andric // DeferredFunctionInfo map. 65290b57cec5SDimitry Andric if (Error Err = rememberAndSkipFunctionBodies()) 65300b57cec5SDimitry Andric return Err; 65310b57cec5SDimitry Andric } 65320b57cec5SDimitry Andric return Error::success(); 65330b57cec5SDimitry Andric } 65340b57cec5SDimitry Andric 65350b57cec5SDimitry Andric SyncScope::ID BitcodeReader::getDecodedSyncScopeID(unsigned Val) { 65360b57cec5SDimitry Andric if (Val == SyncScope::SingleThread || Val == SyncScope::System) 65370b57cec5SDimitry Andric return SyncScope::ID(Val); 65380b57cec5SDimitry Andric if (Val >= SSIDs.size()) 65390b57cec5SDimitry Andric return SyncScope::System; // Map unknown synchronization scopes to system. 65400b57cec5SDimitry Andric return SSIDs[Val]; 65410b57cec5SDimitry Andric } 65420b57cec5SDimitry Andric 65430b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 65440b57cec5SDimitry Andric // GVMaterializer implementation 65450b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 65460b57cec5SDimitry Andric 65470b57cec5SDimitry Andric Error BitcodeReader::materialize(GlobalValue *GV) { 65480b57cec5SDimitry Andric Function *F = dyn_cast<Function>(GV); 65490b57cec5SDimitry Andric // If it's not a function or is already material, ignore the request. 65500b57cec5SDimitry Andric if (!F || !F->isMaterializable()) 65510b57cec5SDimitry Andric return Error::success(); 65520b57cec5SDimitry Andric 65530b57cec5SDimitry Andric DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F); 65540b57cec5SDimitry Andric assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!"); 65550b57cec5SDimitry Andric // If its position is recorded as 0, its body is somewhere in the stream 65560b57cec5SDimitry Andric // but we haven't seen it yet. 65570b57cec5SDimitry Andric if (DFII->second == 0) 65580b57cec5SDimitry Andric if (Error Err = findFunctionInStream(F, DFII)) 65590b57cec5SDimitry Andric return Err; 65600b57cec5SDimitry Andric 65610b57cec5SDimitry Andric // Materialize metadata before parsing any function bodies. 65620b57cec5SDimitry Andric if (Error Err = materializeMetadata()) 65630b57cec5SDimitry Andric return Err; 65640b57cec5SDimitry Andric 65650b57cec5SDimitry Andric // Move the bit stream to the saved position of the deferred function body. 65660b57cec5SDimitry Andric if (Error JumpFailed = Stream.JumpToBit(DFII->second)) 65670b57cec5SDimitry Andric return JumpFailed; 65680b57cec5SDimitry Andric if (Error Err = parseFunctionBody(F)) 65690b57cec5SDimitry Andric return Err; 65700b57cec5SDimitry Andric F->setIsMaterializable(false); 65710b57cec5SDimitry Andric 65720b57cec5SDimitry Andric if (StripDebugInfo) 65730b57cec5SDimitry Andric stripDebugInfo(*F); 65740b57cec5SDimitry Andric 65750b57cec5SDimitry Andric // Upgrade any old intrinsic calls in the function. 65760b57cec5SDimitry Andric for (auto &I : UpgradedIntrinsics) { 6577349cc55cSDimitry Andric for (User *U : llvm::make_early_inc_range(I.first->materialized_users())) 65780b57cec5SDimitry Andric if (CallInst *CI = dyn_cast<CallInst>(U)) 65790b57cec5SDimitry Andric UpgradeIntrinsicCall(CI, I.second); 65800b57cec5SDimitry Andric } 65810b57cec5SDimitry Andric 65820b57cec5SDimitry Andric // Finish fn->subprogram upgrade for materialized functions. 65830b57cec5SDimitry Andric if (DISubprogram *SP = MDLoader->lookupSubprogramForFunction(F)) 65840b57cec5SDimitry Andric F->setSubprogram(SP); 65850b57cec5SDimitry Andric 65860b57cec5SDimitry Andric // Check if the TBAA Metadata are valid, otherwise we will need to strip them. 65870b57cec5SDimitry Andric if (!MDLoader->isStrippingTBAA()) { 65880b57cec5SDimitry Andric for (auto &I : instructions(F)) { 65890b57cec5SDimitry Andric MDNode *TBAA = I.getMetadata(LLVMContext::MD_tbaa); 65900b57cec5SDimitry Andric if (!TBAA || TBAAVerifyHelper.visitTBAAMetadata(I, TBAA)) 65910b57cec5SDimitry Andric continue; 65920b57cec5SDimitry Andric MDLoader->setStripTBAA(true); 65930b57cec5SDimitry Andric stripTBAA(F->getParent()); 65940b57cec5SDimitry Andric } 65950b57cec5SDimitry Andric } 65960b57cec5SDimitry Andric 6597e8d8bef9SDimitry Andric for (auto &I : instructions(F)) { 6598fe6060f1SDimitry Andric // "Upgrade" older incorrect branch weights by dropping them. 6599e8d8bef9SDimitry Andric if (auto *MD = I.getMetadata(LLVMContext::MD_prof)) { 6600e8d8bef9SDimitry Andric if (MD->getOperand(0) != nullptr && isa<MDString>(MD->getOperand(0))) { 6601e8d8bef9SDimitry Andric MDString *MDS = cast<MDString>(MD->getOperand(0)); 6602e8d8bef9SDimitry Andric StringRef ProfName = MDS->getString(); 6603e8d8bef9SDimitry Andric // Check consistency of !prof branch_weights metadata. 6604e8d8bef9SDimitry Andric if (!ProfName.equals("branch_weights")) 6605e8d8bef9SDimitry Andric continue; 6606e8d8bef9SDimitry Andric unsigned ExpectedNumOperands = 0; 6607e8d8bef9SDimitry Andric if (BranchInst *BI = dyn_cast<BranchInst>(&I)) 6608e8d8bef9SDimitry Andric ExpectedNumOperands = BI->getNumSuccessors(); 6609e8d8bef9SDimitry Andric else if (SwitchInst *SI = dyn_cast<SwitchInst>(&I)) 6610e8d8bef9SDimitry Andric ExpectedNumOperands = SI->getNumSuccessors(); 6611e8d8bef9SDimitry Andric else if (isa<CallInst>(&I)) 6612e8d8bef9SDimitry Andric ExpectedNumOperands = 1; 6613e8d8bef9SDimitry Andric else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(&I)) 6614e8d8bef9SDimitry Andric ExpectedNumOperands = IBI->getNumDestinations(); 6615e8d8bef9SDimitry Andric else if (isa<SelectInst>(&I)) 6616e8d8bef9SDimitry Andric ExpectedNumOperands = 2; 6617e8d8bef9SDimitry Andric else 6618e8d8bef9SDimitry Andric continue; // ignore and continue. 6619e8d8bef9SDimitry Andric 6620e8d8bef9SDimitry Andric // If branch weight doesn't match, just strip branch weight. 6621e8d8bef9SDimitry Andric if (MD->getNumOperands() != 1 + ExpectedNumOperands) 6622e8d8bef9SDimitry Andric I.setMetadata(LLVMContext::MD_prof, nullptr); 6623e8d8bef9SDimitry Andric } 6624e8d8bef9SDimitry Andric } 6625fe6060f1SDimitry Andric 6626fe6060f1SDimitry Andric // Remove incompatible attributes on function calls. 6627fe6060f1SDimitry Andric if (auto *CI = dyn_cast<CallBase>(&I)) { 6628349cc55cSDimitry Andric CI->removeRetAttrs(AttributeFuncs::typeIncompatible( 6629fe6060f1SDimitry Andric CI->getFunctionType()->getReturnType())); 6630fe6060f1SDimitry Andric 6631fe6060f1SDimitry Andric for (unsigned ArgNo = 0; ArgNo < CI->arg_size(); ++ArgNo) 6632fe6060f1SDimitry Andric CI->removeParamAttrs(ArgNo, AttributeFuncs::typeIncompatible( 6633fe6060f1SDimitry Andric CI->getArgOperand(ArgNo)->getType())); 6634fe6060f1SDimitry Andric } 6635e8d8bef9SDimitry Andric } 6636e8d8bef9SDimitry Andric 66375ffd83dbSDimitry Andric // Look for functions that rely on old function attribute behavior. 66385ffd83dbSDimitry Andric UpgradeFunctionAttributes(*F); 66395ffd83dbSDimitry Andric 66400b57cec5SDimitry Andric // Bring in any functions that this function forward-referenced via 66410b57cec5SDimitry Andric // blockaddresses. 66420b57cec5SDimitry Andric return materializeForwardReferencedFunctions(); 66430b57cec5SDimitry Andric } 66440b57cec5SDimitry Andric 66450b57cec5SDimitry Andric Error BitcodeReader::materializeModule() { 66460b57cec5SDimitry Andric if (Error Err = materializeMetadata()) 66470b57cec5SDimitry Andric return Err; 66480b57cec5SDimitry Andric 66490b57cec5SDimitry Andric // Promise to materialize all forward references. 66500b57cec5SDimitry Andric WillMaterializeAllForwardRefs = true; 66510b57cec5SDimitry Andric 66520b57cec5SDimitry Andric // Iterate over the module, deserializing any functions that are still on 66530b57cec5SDimitry Andric // disk. 66540b57cec5SDimitry Andric for (Function &F : *TheModule) { 66550b57cec5SDimitry Andric if (Error Err = materialize(&F)) 66560b57cec5SDimitry Andric return Err; 66570b57cec5SDimitry Andric } 66580b57cec5SDimitry Andric // At this point, if there are any function bodies, parse the rest of 66590b57cec5SDimitry Andric // the bits in the module past the last function block we have recorded 66600b57cec5SDimitry Andric // through either lazy scanning or the VST. 66610b57cec5SDimitry Andric if (LastFunctionBlockBit || NextUnreadBit) 66620b57cec5SDimitry Andric if (Error Err = parseModule(LastFunctionBlockBit > NextUnreadBit 66630b57cec5SDimitry Andric ? LastFunctionBlockBit 66640b57cec5SDimitry Andric : NextUnreadBit)) 66650b57cec5SDimitry Andric return Err; 66660b57cec5SDimitry Andric 66670b57cec5SDimitry Andric // Check that all block address forward references got resolved (as we 66680b57cec5SDimitry Andric // promised above). 66690b57cec5SDimitry Andric if (!BasicBlockFwdRefs.empty()) 66700b57cec5SDimitry Andric return error("Never resolved function from blockaddress"); 66710b57cec5SDimitry Andric 66720b57cec5SDimitry Andric // Upgrade any intrinsic calls that slipped through (should not happen!) and 66730b57cec5SDimitry Andric // delete the old functions to clean up. We can't do this unless the entire 66740b57cec5SDimitry Andric // module is materialized because there could always be another function body 66750b57cec5SDimitry Andric // with calls to the old function. 66760b57cec5SDimitry Andric for (auto &I : UpgradedIntrinsics) { 66770b57cec5SDimitry Andric for (auto *U : I.first->users()) { 66780b57cec5SDimitry Andric if (CallInst *CI = dyn_cast<CallInst>(U)) 66790b57cec5SDimitry Andric UpgradeIntrinsicCall(CI, I.second); 66800b57cec5SDimitry Andric } 66810b57cec5SDimitry Andric if (!I.first->use_empty()) 66820b57cec5SDimitry Andric I.first->replaceAllUsesWith(I.second); 66830b57cec5SDimitry Andric I.first->eraseFromParent(); 66840b57cec5SDimitry Andric } 66850b57cec5SDimitry Andric UpgradedIntrinsics.clear(); 66860b57cec5SDimitry Andric 66870b57cec5SDimitry Andric UpgradeDebugInfo(*TheModule); 66880b57cec5SDimitry Andric 66890b57cec5SDimitry Andric UpgradeModuleFlags(*TheModule); 66900b57cec5SDimitry Andric 66918bcb0991SDimitry Andric UpgradeARCRuntime(*TheModule); 66920b57cec5SDimitry Andric 66930b57cec5SDimitry Andric return Error::success(); 66940b57cec5SDimitry Andric } 66950b57cec5SDimitry Andric 66960b57cec5SDimitry Andric std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const { 66970b57cec5SDimitry Andric return IdentifiedStructTypes; 66980b57cec5SDimitry Andric } 66990b57cec5SDimitry Andric 67000b57cec5SDimitry Andric ModuleSummaryIndexBitcodeReader::ModuleSummaryIndexBitcodeReader( 67010b57cec5SDimitry Andric BitstreamCursor Cursor, StringRef Strtab, ModuleSummaryIndex &TheIndex, 6702bdd1243dSDimitry Andric StringRef ModulePath, unsigned ModuleId, 6703bdd1243dSDimitry Andric std::function<bool(GlobalValue::GUID)> IsPrevailing) 67040b57cec5SDimitry Andric : BitcodeReaderBase(std::move(Cursor), Strtab), TheIndex(TheIndex), 6705bdd1243dSDimitry Andric ModulePath(ModulePath), ModuleId(ModuleId), IsPrevailing(IsPrevailing) {} 67060b57cec5SDimitry Andric 67070b57cec5SDimitry Andric void ModuleSummaryIndexBitcodeReader::addThisModule() { 67080b57cec5SDimitry Andric TheIndex.addModule(ModulePath, ModuleId); 67090b57cec5SDimitry Andric } 67100b57cec5SDimitry Andric 67110b57cec5SDimitry Andric ModuleSummaryIndex::ModuleInfo * 67120b57cec5SDimitry Andric ModuleSummaryIndexBitcodeReader::getThisModule() { 67130b57cec5SDimitry Andric return TheIndex.getModule(ModulePath); 67140b57cec5SDimitry Andric } 67150b57cec5SDimitry Andric 6716bdd1243dSDimitry Andric template <bool AllowNullValueInfo> 6717bdd1243dSDimitry Andric std::tuple<ValueInfo, GlobalValue::GUID, GlobalValue::GUID> 67180b57cec5SDimitry Andric ModuleSummaryIndexBitcodeReader::getValueInfoFromValueId(unsigned ValueId) { 67190b57cec5SDimitry Andric auto VGI = ValueIdToValueInfoMap[ValueId]; 6720bdd1243dSDimitry Andric // We can have a null value info for memprof callsite info records in 6721bdd1243dSDimitry Andric // distributed ThinLTO index files when the callee function summary is not 6722bdd1243dSDimitry Andric // included in the index. The bitcode writer records 0 in that case, 6723bdd1243dSDimitry Andric // and the caller of this helper will set AllowNullValueInfo to true. 6724bdd1243dSDimitry Andric assert(AllowNullValueInfo || std::get<0>(VGI)); 67250b57cec5SDimitry Andric return VGI; 67260b57cec5SDimitry Andric } 67270b57cec5SDimitry Andric 67280b57cec5SDimitry Andric void ModuleSummaryIndexBitcodeReader::setValueGUID( 67290b57cec5SDimitry Andric uint64_t ValueID, StringRef ValueName, GlobalValue::LinkageTypes Linkage, 67300b57cec5SDimitry Andric StringRef SourceFileName) { 67310b57cec5SDimitry Andric std::string GlobalId = 67320b57cec5SDimitry Andric GlobalValue::getGlobalIdentifier(ValueName, Linkage, SourceFileName); 67330b57cec5SDimitry Andric auto ValueGUID = GlobalValue::getGUID(GlobalId); 67340b57cec5SDimitry Andric auto OriginalNameID = ValueGUID; 67350b57cec5SDimitry Andric if (GlobalValue::isLocalLinkage(Linkage)) 67360b57cec5SDimitry Andric OriginalNameID = GlobalValue::getGUID(ValueName); 67370b57cec5SDimitry Andric if (PrintSummaryGUIDs) 67380b57cec5SDimitry Andric dbgs() << "GUID " << ValueGUID << "(" << OriginalNameID << ") is " 67390b57cec5SDimitry Andric << ValueName << "\n"; 67400b57cec5SDimitry Andric 67410b57cec5SDimitry Andric // UseStrtab is false for legacy summary formats and value names are 67420b57cec5SDimitry Andric // created on stack. In that case we save the name in a string saver in 67430b57cec5SDimitry Andric // the index so that the value name can be recorded. 6744bdd1243dSDimitry Andric ValueIdToValueInfoMap[ValueID] = std::make_tuple( 67450b57cec5SDimitry Andric TheIndex.getOrInsertValueInfo( 6746bdd1243dSDimitry Andric ValueGUID, UseStrtab ? ValueName : TheIndex.saveString(ValueName)), 6747bdd1243dSDimitry Andric OriginalNameID, ValueGUID); 67480b57cec5SDimitry Andric } 67490b57cec5SDimitry Andric 67500b57cec5SDimitry Andric // Specialized value symbol table parser used when reading module index 67510b57cec5SDimitry Andric // blocks where we don't actually create global values. The parsed information 67520b57cec5SDimitry Andric // is saved in the bitcode reader for use when later parsing summaries. 67530b57cec5SDimitry Andric Error ModuleSummaryIndexBitcodeReader::parseValueSymbolTable( 67540b57cec5SDimitry Andric uint64_t Offset, 67550b57cec5SDimitry Andric DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap) { 67560b57cec5SDimitry Andric // With a strtab the VST is not required to parse the summary. 67570b57cec5SDimitry Andric if (UseStrtab) 67580b57cec5SDimitry Andric return Error::success(); 67590b57cec5SDimitry Andric 67600b57cec5SDimitry Andric assert(Offset > 0 && "Expected non-zero VST offset"); 67610b57cec5SDimitry Andric Expected<uint64_t> MaybeCurrentBit = jumpToValueSymbolTable(Offset, Stream); 67620b57cec5SDimitry Andric if (!MaybeCurrentBit) 67630b57cec5SDimitry Andric return MaybeCurrentBit.takeError(); 67640b57cec5SDimitry Andric uint64_t CurrentBit = MaybeCurrentBit.get(); 67650b57cec5SDimitry Andric 67660b57cec5SDimitry Andric if (Error Err = Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID)) 67670b57cec5SDimitry Andric return Err; 67680b57cec5SDimitry Andric 67690b57cec5SDimitry Andric SmallVector<uint64_t, 64> Record; 67700b57cec5SDimitry Andric 67710b57cec5SDimitry Andric // Read all the records for this value table. 67720b57cec5SDimitry Andric SmallString<128> ValueName; 67730b57cec5SDimitry Andric 67740b57cec5SDimitry Andric while (true) { 67750b57cec5SDimitry Andric Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); 67760b57cec5SDimitry Andric if (!MaybeEntry) 67770b57cec5SDimitry Andric return MaybeEntry.takeError(); 67780b57cec5SDimitry Andric BitstreamEntry Entry = MaybeEntry.get(); 67790b57cec5SDimitry Andric 67800b57cec5SDimitry Andric switch (Entry.Kind) { 67810b57cec5SDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already. 67820b57cec5SDimitry Andric case BitstreamEntry::Error: 67830b57cec5SDimitry Andric return error("Malformed block"); 67840b57cec5SDimitry Andric case BitstreamEntry::EndBlock: 67850b57cec5SDimitry Andric // Done parsing VST, jump back to wherever we came from. 67860b57cec5SDimitry Andric if (Error JumpFailed = Stream.JumpToBit(CurrentBit)) 67870b57cec5SDimitry Andric return JumpFailed; 67880b57cec5SDimitry Andric return Error::success(); 67890b57cec5SDimitry Andric case BitstreamEntry::Record: 67900b57cec5SDimitry Andric // The interesting case. 67910b57cec5SDimitry Andric break; 67920b57cec5SDimitry Andric } 67930b57cec5SDimitry Andric 67940b57cec5SDimitry Andric // Read a record. 67950b57cec5SDimitry Andric Record.clear(); 67960b57cec5SDimitry Andric Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record); 67970b57cec5SDimitry Andric if (!MaybeRecord) 67980b57cec5SDimitry Andric return MaybeRecord.takeError(); 67990b57cec5SDimitry Andric switch (MaybeRecord.get()) { 68000b57cec5SDimitry Andric default: // Default behavior: ignore (e.g. VST_CODE_BBENTRY records). 68010b57cec5SDimitry Andric break; 68020b57cec5SDimitry Andric case bitc::VST_CODE_ENTRY: { // VST_CODE_ENTRY: [valueid, namechar x N] 68030b57cec5SDimitry Andric if (convertToString(Record, 1, ValueName)) 68040b57cec5SDimitry Andric return error("Invalid record"); 68050b57cec5SDimitry Andric unsigned ValueID = Record[0]; 68060b57cec5SDimitry Andric assert(!SourceFileName.empty()); 68070b57cec5SDimitry Andric auto VLI = ValueIdToLinkageMap.find(ValueID); 68080b57cec5SDimitry Andric assert(VLI != ValueIdToLinkageMap.end() && 68090b57cec5SDimitry Andric "No linkage found for VST entry?"); 68100b57cec5SDimitry Andric auto Linkage = VLI->second; 68110b57cec5SDimitry Andric setValueGUID(ValueID, ValueName, Linkage, SourceFileName); 68120b57cec5SDimitry Andric ValueName.clear(); 68130b57cec5SDimitry Andric break; 68140b57cec5SDimitry Andric } 68150b57cec5SDimitry Andric case bitc::VST_CODE_FNENTRY: { 68160b57cec5SDimitry Andric // VST_CODE_FNENTRY: [valueid, offset, namechar x N] 68170b57cec5SDimitry Andric if (convertToString(Record, 2, ValueName)) 68180b57cec5SDimitry Andric return error("Invalid record"); 68190b57cec5SDimitry Andric unsigned ValueID = Record[0]; 68200b57cec5SDimitry Andric assert(!SourceFileName.empty()); 68210b57cec5SDimitry Andric auto VLI = ValueIdToLinkageMap.find(ValueID); 68220b57cec5SDimitry Andric assert(VLI != ValueIdToLinkageMap.end() && 68230b57cec5SDimitry Andric "No linkage found for VST entry?"); 68240b57cec5SDimitry Andric auto Linkage = VLI->second; 68250b57cec5SDimitry Andric setValueGUID(ValueID, ValueName, Linkage, SourceFileName); 68260b57cec5SDimitry Andric ValueName.clear(); 68270b57cec5SDimitry Andric break; 68280b57cec5SDimitry Andric } 68290b57cec5SDimitry Andric case bitc::VST_CODE_COMBINED_ENTRY: { 68300b57cec5SDimitry Andric // VST_CODE_COMBINED_ENTRY: [valueid, refguid] 68310b57cec5SDimitry Andric unsigned ValueID = Record[0]; 68320b57cec5SDimitry Andric GlobalValue::GUID RefGUID = Record[1]; 68330b57cec5SDimitry Andric // The "original name", which is the second value of the pair will be 68340b57cec5SDimitry Andric // overriden later by a FS_COMBINED_ORIGINAL_NAME in the combined index. 6835bdd1243dSDimitry Andric ValueIdToValueInfoMap[ValueID] = std::make_tuple( 6836bdd1243dSDimitry Andric TheIndex.getOrInsertValueInfo(RefGUID), RefGUID, RefGUID); 68370b57cec5SDimitry Andric break; 68380b57cec5SDimitry Andric } 68390b57cec5SDimitry Andric } 68400b57cec5SDimitry Andric } 68410b57cec5SDimitry Andric } 68420b57cec5SDimitry Andric 68430b57cec5SDimitry Andric // Parse just the blocks needed for building the index out of the module. 68440b57cec5SDimitry Andric // At the end of this routine the module Index is populated with a map 68450b57cec5SDimitry Andric // from global value id to GlobalValueSummary objects. 68460b57cec5SDimitry Andric Error ModuleSummaryIndexBitcodeReader::parseModule() { 68470b57cec5SDimitry Andric if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID)) 68480b57cec5SDimitry Andric return Err; 68490b57cec5SDimitry Andric 68500b57cec5SDimitry Andric SmallVector<uint64_t, 64> Record; 68510b57cec5SDimitry Andric DenseMap<unsigned, GlobalValue::LinkageTypes> ValueIdToLinkageMap; 68520b57cec5SDimitry Andric unsigned ValueId = 0; 68530b57cec5SDimitry Andric 68540b57cec5SDimitry Andric // Read the index for this module. 68550b57cec5SDimitry Andric while (true) { 68560b57cec5SDimitry Andric Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance(); 68570b57cec5SDimitry Andric if (!MaybeEntry) 68580b57cec5SDimitry Andric return MaybeEntry.takeError(); 68590b57cec5SDimitry Andric llvm::BitstreamEntry Entry = MaybeEntry.get(); 68600b57cec5SDimitry Andric 68610b57cec5SDimitry Andric switch (Entry.Kind) { 68620b57cec5SDimitry Andric case BitstreamEntry::Error: 68630b57cec5SDimitry Andric return error("Malformed block"); 68640b57cec5SDimitry Andric case BitstreamEntry::EndBlock: 68650b57cec5SDimitry Andric return Error::success(); 68660b57cec5SDimitry Andric 68670b57cec5SDimitry Andric case BitstreamEntry::SubBlock: 68680b57cec5SDimitry Andric switch (Entry.ID) { 68690b57cec5SDimitry Andric default: // Skip unknown content. 68700b57cec5SDimitry Andric if (Error Err = Stream.SkipBlock()) 68710b57cec5SDimitry Andric return Err; 68720b57cec5SDimitry Andric break; 68730b57cec5SDimitry Andric case bitc::BLOCKINFO_BLOCK_ID: 68740b57cec5SDimitry Andric // Need to parse these to get abbrev ids (e.g. for VST) 687581ad6265SDimitry Andric if (Error Err = readBlockInfo()) 687681ad6265SDimitry Andric return Err; 68770b57cec5SDimitry Andric break; 68780b57cec5SDimitry Andric case bitc::VALUE_SYMTAB_BLOCK_ID: 68790b57cec5SDimitry Andric // Should have been parsed earlier via VSTOffset, unless there 68800b57cec5SDimitry Andric // is no summary section. 68810b57cec5SDimitry Andric assert(((SeenValueSymbolTable && VSTOffset > 0) || 68820b57cec5SDimitry Andric !SeenGlobalValSummary) && 68830b57cec5SDimitry Andric "Expected early VST parse via VSTOffset record"); 68840b57cec5SDimitry Andric if (Error Err = Stream.SkipBlock()) 68850b57cec5SDimitry Andric return Err; 68860b57cec5SDimitry Andric break; 68870b57cec5SDimitry Andric case bitc::GLOBALVAL_SUMMARY_BLOCK_ID: 68880b57cec5SDimitry Andric case bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID: 68890b57cec5SDimitry Andric // Add the module if it is a per-module index (has a source file name). 68900b57cec5SDimitry Andric if (!SourceFileName.empty()) 68910b57cec5SDimitry Andric addThisModule(); 68920b57cec5SDimitry Andric assert(!SeenValueSymbolTable && 68930b57cec5SDimitry Andric "Already read VST when parsing summary block?"); 68940b57cec5SDimitry Andric // We might not have a VST if there were no values in the 68950b57cec5SDimitry Andric // summary. An empty summary block generated when we are 68960b57cec5SDimitry Andric // performing ThinLTO compiles so we don't later invoke 68970b57cec5SDimitry Andric // the regular LTO process on them. 68980b57cec5SDimitry Andric if (VSTOffset > 0) { 68990b57cec5SDimitry Andric if (Error Err = parseValueSymbolTable(VSTOffset, ValueIdToLinkageMap)) 69000b57cec5SDimitry Andric return Err; 69010b57cec5SDimitry Andric SeenValueSymbolTable = true; 69020b57cec5SDimitry Andric } 69030b57cec5SDimitry Andric SeenGlobalValSummary = true; 69040b57cec5SDimitry Andric if (Error Err = parseEntireSummary(Entry.ID)) 69050b57cec5SDimitry Andric return Err; 69060b57cec5SDimitry Andric break; 69070b57cec5SDimitry Andric case bitc::MODULE_STRTAB_BLOCK_ID: 69080b57cec5SDimitry Andric if (Error Err = parseModuleStringTable()) 69090b57cec5SDimitry Andric return Err; 69100b57cec5SDimitry Andric break; 69110b57cec5SDimitry Andric } 69120b57cec5SDimitry Andric continue; 69130b57cec5SDimitry Andric 69140b57cec5SDimitry Andric case BitstreamEntry::Record: { 69150b57cec5SDimitry Andric Record.clear(); 69160b57cec5SDimitry Andric Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record); 69170b57cec5SDimitry Andric if (!MaybeBitCode) 69180b57cec5SDimitry Andric return MaybeBitCode.takeError(); 69190b57cec5SDimitry Andric switch (MaybeBitCode.get()) { 69200b57cec5SDimitry Andric default: 69210b57cec5SDimitry Andric break; // Default behavior, ignore unknown content. 69220b57cec5SDimitry Andric case bitc::MODULE_CODE_VERSION: { 69230b57cec5SDimitry Andric if (Error Err = parseVersionRecord(Record).takeError()) 69240b57cec5SDimitry Andric return Err; 69250b57cec5SDimitry Andric break; 69260b57cec5SDimitry Andric } 69270b57cec5SDimitry Andric /// MODULE_CODE_SOURCE_FILENAME: [namechar x N] 69280b57cec5SDimitry Andric case bitc::MODULE_CODE_SOURCE_FILENAME: { 69290b57cec5SDimitry Andric SmallString<128> ValueName; 69300b57cec5SDimitry Andric if (convertToString(Record, 0, ValueName)) 69310b57cec5SDimitry Andric return error("Invalid record"); 69320b57cec5SDimitry Andric SourceFileName = ValueName.c_str(); 69330b57cec5SDimitry Andric break; 69340b57cec5SDimitry Andric } 69350b57cec5SDimitry Andric /// MODULE_CODE_HASH: [5*i32] 69360b57cec5SDimitry Andric case bitc::MODULE_CODE_HASH: { 69370b57cec5SDimitry Andric if (Record.size() != 5) 69380b57cec5SDimitry Andric return error("Invalid hash length " + Twine(Record.size()).str()); 69390b57cec5SDimitry Andric auto &Hash = getThisModule()->second.second; 69400b57cec5SDimitry Andric int Pos = 0; 69410b57cec5SDimitry Andric for (auto &Val : Record) { 69420b57cec5SDimitry Andric assert(!(Val >> 32) && "Unexpected high bits set"); 69430b57cec5SDimitry Andric Hash[Pos++] = Val; 69440b57cec5SDimitry Andric } 69450b57cec5SDimitry Andric break; 69460b57cec5SDimitry Andric } 69470b57cec5SDimitry Andric /// MODULE_CODE_VSTOFFSET: [offset] 69480b57cec5SDimitry Andric case bitc::MODULE_CODE_VSTOFFSET: 6949e8d8bef9SDimitry Andric if (Record.empty()) 69500b57cec5SDimitry Andric return error("Invalid record"); 69510b57cec5SDimitry Andric // Note that we subtract 1 here because the offset is relative to one 69520b57cec5SDimitry Andric // word before the start of the identification or module block, which 69530b57cec5SDimitry Andric // was historically always the start of the regular bitcode header. 69540b57cec5SDimitry Andric VSTOffset = Record[0] - 1; 69550b57cec5SDimitry Andric break; 69560b57cec5SDimitry Andric // v1 GLOBALVAR: [pointer type, isconst, initid, linkage, ...] 69570b57cec5SDimitry Andric // v1 FUNCTION: [type, callingconv, isproto, linkage, ...] 69580b57cec5SDimitry Andric // v1 ALIAS: [alias type, addrspace, aliasee val#, linkage, ...] 69590b57cec5SDimitry Andric // v2: [strtab offset, strtab size, v1] 69600b57cec5SDimitry Andric case bitc::MODULE_CODE_GLOBALVAR: 69610b57cec5SDimitry Andric case bitc::MODULE_CODE_FUNCTION: 69620b57cec5SDimitry Andric case bitc::MODULE_CODE_ALIAS: { 69630b57cec5SDimitry Andric StringRef Name; 69640b57cec5SDimitry Andric ArrayRef<uint64_t> GVRecord; 69650b57cec5SDimitry Andric std::tie(Name, GVRecord) = readNameFromStrtab(Record); 69660b57cec5SDimitry Andric if (GVRecord.size() <= 3) 69670b57cec5SDimitry Andric return error("Invalid record"); 69680b57cec5SDimitry Andric uint64_t RawLinkage = GVRecord[3]; 69690b57cec5SDimitry Andric GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage); 69700b57cec5SDimitry Andric if (!UseStrtab) { 69710b57cec5SDimitry Andric ValueIdToLinkageMap[ValueId++] = Linkage; 69720b57cec5SDimitry Andric break; 69730b57cec5SDimitry Andric } 69740b57cec5SDimitry Andric 69750b57cec5SDimitry Andric setValueGUID(ValueId++, Name, Linkage, SourceFileName); 69760b57cec5SDimitry Andric break; 69770b57cec5SDimitry Andric } 69780b57cec5SDimitry Andric } 69790b57cec5SDimitry Andric } 69800b57cec5SDimitry Andric continue; 69810b57cec5SDimitry Andric } 69820b57cec5SDimitry Andric } 69830b57cec5SDimitry Andric } 69840b57cec5SDimitry Andric 69850b57cec5SDimitry Andric std::vector<ValueInfo> 69860b57cec5SDimitry Andric ModuleSummaryIndexBitcodeReader::makeRefList(ArrayRef<uint64_t> Record) { 69870b57cec5SDimitry Andric std::vector<ValueInfo> Ret; 69880b57cec5SDimitry Andric Ret.reserve(Record.size()); 69890b57cec5SDimitry Andric for (uint64_t RefValueId : Record) 6990bdd1243dSDimitry Andric Ret.push_back(std::get<0>(getValueInfoFromValueId(RefValueId))); 69910b57cec5SDimitry Andric return Ret; 69920b57cec5SDimitry Andric } 69930b57cec5SDimitry Andric 69940b57cec5SDimitry Andric std::vector<FunctionSummary::EdgeTy> 69950b57cec5SDimitry Andric ModuleSummaryIndexBitcodeReader::makeCallList(ArrayRef<uint64_t> Record, 69960b57cec5SDimitry Andric bool IsOldProfileFormat, 69970b57cec5SDimitry Andric bool HasProfile, bool HasRelBF) { 69980b57cec5SDimitry Andric std::vector<FunctionSummary::EdgeTy> Ret; 69990b57cec5SDimitry Andric Ret.reserve(Record.size()); 70000b57cec5SDimitry Andric for (unsigned I = 0, E = Record.size(); I != E; ++I) { 70010b57cec5SDimitry Andric CalleeInfo::HotnessType Hotness = CalleeInfo::HotnessType::Unknown; 70020b57cec5SDimitry Andric uint64_t RelBF = 0; 7003bdd1243dSDimitry Andric ValueInfo Callee = std::get<0>(getValueInfoFromValueId(Record[I])); 70040b57cec5SDimitry Andric if (IsOldProfileFormat) { 70050b57cec5SDimitry Andric I += 1; // Skip old callsitecount field 70060b57cec5SDimitry Andric if (HasProfile) 70070b57cec5SDimitry Andric I += 1; // Skip old profilecount field 70080b57cec5SDimitry Andric } else if (HasProfile) 70090b57cec5SDimitry Andric Hotness = static_cast<CalleeInfo::HotnessType>(Record[++I]); 70100b57cec5SDimitry Andric else if (HasRelBF) 70110b57cec5SDimitry Andric RelBF = Record[++I]; 70120b57cec5SDimitry Andric Ret.push_back(FunctionSummary::EdgeTy{Callee, CalleeInfo(Hotness, RelBF)}); 70130b57cec5SDimitry Andric } 70140b57cec5SDimitry Andric return Ret; 70150b57cec5SDimitry Andric } 70160b57cec5SDimitry Andric 70170b57cec5SDimitry Andric static void 70180b57cec5SDimitry Andric parseWholeProgramDevirtResolutionByArg(ArrayRef<uint64_t> Record, size_t &Slot, 70190b57cec5SDimitry Andric WholeProgramDevirtResolution &Wpd) { 70200b57cec5SDimitry Andric uint64_t ArgNum = Record[Slot++]; 70210b57cec5SDimitry Andric WholeProgramDevirtResolution::ByArg &B = 70220b57cec5SDimitry Andric Wpd.ResByArg[{Record.begin() + Slot, Record.begin() + Slot + ArgNum}]; 70230b57cec5SDimitry Andric Slot += ArgNum; 70240b57cec5SDimitry Andric 70250b57cec5SDimitry Andric B.TheKind = 70260b57cec5SDimitry Andric static_cast<WholeProgramDevirtResolution::ByArg::Kind>(Record[Slot++]); 70270b57cec5SDimitry Andric B.Info = Record[Slot++]; 70280b57cec5SDimitry Andric B.Byte = Record[Slot++]; 70290b57cec5SDimitry Andric B.Bit = Record[Slot++]; 70300b57cec5SDimitry Andric } 70310b57cec5SDimitry Andric 70320b57cec5SDimitry Andric static void parseWholeProgramDevirtResolution(ArrayRef<uint64_t> Record, 70330b57cec5SDimitry Andric StringRef Strtab, size_t &Slot, 70340b57cec5SDimitry Andric TypeIdSummary &TypeId) { 70350b57cec5SDimitry Andric uint64_t Id = Record[Slot++]; 70360b57cec5SDimitry Andric WholeProgramDevirtResolution &Wpd = TypeId.WPDRes[Id]; 70370b57cec5SDimitry Andric 70380b57cec5SDimitry Andric Wpd.TheKind = static_cast<WholeProgramDevirtResolution::Kind>(Record[Slot++]); 70390b57cec5SDimitry Andric Wpd.SingleImplName = {Strtab.data() + Record[Slot], 70400b57cec5SDimitry Andric static_cast<size_t>(Record[Slot + 1])}; 70410b57cec5SDimitry Andric Slot += 2; 70420b57cec5SDimitry Andric 70430b57cec5SDimitry Andric uint64_t ResByArgNum = Record[Slot++]; 70440b57cec5SDimitry Andric for (uint64_t I = 0; I != ResByArgNum; ++I) 70450b57cec5SDimitry Andric parseWholeProgramDevirtResolutionByArg(Record, Slot, Wpd); 70460b57cec5SDimitry Andric } 70470b57cec5SDimitry Andric 70480b57cec5SDimitry Andric static void parseTypeIdSummaryRecord(ArrayRef<uint64_t> Record, 70490b57cec5SDimitry Andric StringRef Strtab, 70500b57cec5SDimitry Andric ModuleSummaryIndex &TheIndex) { 70510b57cec5SDimitry Andric size_t Slot = 0; 70520b57cec5SDimitry Andric TypeIdSummary &TypeId = TheIndex.getOrInsertTypeIdSummary( 70530b57cec5SDimitry Andric {Strtab.data() + Record[Slot], static_cast<size_t>(Record[Slot + 1])}); 70540b57cec5SDimitry Andric Slot += 2; 70550b57cec5SDimitry Andric 70560b57cec5SDimitry Andric TypeId.TTRes.TheKind = static_cast<TypeTestResolution::Kind>(Record[Slot++]); 70570b57cec5SDimitry Andric TypeId.TTRes.SizeM1BitWidth = Record[Slot++]; 70580b57cec5SDimitry Andric TypeId.TTRes.AlignLog2 = Record[Slot++]; 70590b57cec5SDimitry Andric TypeId.TTRes.SizeM1 = Record[Slot++]; 70600b57cec5SDimitry Andric TypeId.TTRes.BitMask = Record[Slot++]; 70610b57cec5SDimitry Andric TypeId.TTRes.InlineBits = Record[Slot++]; 70620b57cec5SDimitry Andric 70630b57cec5SDimitry Andric while (Slot < Record.size()) 70640b57cec5SDimitry Andric parseWholeProgramDevirtResolution(Record, Strtab, Slot, TypeId); 70650b57cec5SDimitry Andric } 70660b57cec5SDimitry Andric 7067e8d8bef9SDimitry Andric std::vector<FunctionSummary::ParamAccess> 7068e8d8bef9SDimitry Andric ModuleSummaryIndexBitcodeReader::parseParamAccesses(ArrayRef<uint64_t> Record) { 70695ffd83dbSDimitry Andric auto ReadRange = [&]() { 70705ffd83dbSDimitry Andric APInt Lower(FunctionSummary::ParamAccess::RangeWidth, 70715ffd83dbSDimitry Andric BitcodeReader::decodeSignRotatedValue(Record.front())); 70725ffd83dbSDimitry Andric Record = Record.drop_front(); 70735ffd83dbSDimitry Andric APInt Upper(FunctionSummary::ParamAccess::RangeWidth, 70745ffd83dbSDimitry Andric BitcodeReader::decodeSignRotatedValue(Record.front())); 70755ffd83dbSDimitry Andric Record = Record.drop_front(); 70765ffd83dbSDimitry Andric ConstantRange Range{Lower, Upper}; 70775ffd83dbSDimitry Andric assert(!Range.isFullSet()); 70785ffd83dbSDimitry Andric assert(!Range.isUpperSignWrapped()); 70795ffd83dbSDimitry Andric return Range; 70805ffd83dbSDimitry Andric }; 70815ffd83dbSDimitry Andric 70825ffd83dbSDimitry Andric std::vector<FunctionSummary::ParamAccess> PendingParamAccesses; 70835ffd83dbSDimitry Andric while (!Record.empty()) { 70845ffd83dbSDimitry Andric PendingParamAccesses.emplace_back(); 70855ffd83dbSDimitry Andric FunctionSummary::ParamAccess &ParamAccess = PendingParamAccesses.back(); 70865ffd83dbSDimitry Andric ParamAccess.ParamNo = Record.front(); 70875ffd83dbSDimitry Andric Record = Record.drop_front(); 70885ffd83dbSDimitry Andric ParamAccess.Use = ReadRange(); 70895ffd83dbSDimitry Andric ParamAccess.Calls.resize(Record.front()); 70905ffd83dbSDimitry Andric Record = Record.drop_front(); 70915ffd83dbSDimitry Andric for (auto &Call : ParamAccess.Calls) { 70925ffd83dbSDimitry Andric Call.ParamNo = Record.front(); 70935ffd83dbSDimitry Andric Record = Record.drop_front(); 7094bdd1243dSDimitry Andric Call.Callee = std::get<0>(getValueInfoFromValueId(Record.front())); 70955ffd83dbSDimitry Andric Record = Record.drop_front(); 70965ffd83dbSDimitry Andric Call.Offsets = ReadRange(); 70975ffd83dbSDimitry Andric } 70985ffd83dbSDimitry Andric } 70995ffd83dbSDimitry Andric return PendingParamAccesses; 71005ffd83dbSDimitry Andric } 71015ffd83dbSDimitry Andric 71020b57cec5SDimitry Andric void ModuleSummaryIndexBitcodeReader::parseTypeIdCompatibleVtableInfo( 71030b57cec5SDimitry Andric ArrayRef<uint64_t> Record, size_t &Slot, 71040b57cec5SDimitry Andric TypeIdCompatibleVtableInfo &TypeId) { 71050b57cec5SDimitry Andric uint64_t Offset = Record[Slot++]; 7106bdd1243dSDimitry Andric ValueInfo Callee = std::get<0>(getValueInfoFromValueId(Record[Slot++])); 71070b57cec5SDimitry Andric TypeId.push_back({Offset, Callee}); 71080b57cec5SDimitry Andric } 71090b57cec5SDimitry Andric 71100b57cec5SDimitry Andric void ModuleSummaryIndexBitcodeReader::parseTypeIdCompatibleVtableSummaryRecord( 71110b57cec5SDimitry Andric ArrayRef<uint64_t> Record) { 71120b57cec5SDimitry Andric size_t Slot = 0; 71130b57cec5SDimitry Andric TypeIdCompatibleVtableInfo &TypeId = 71140b57cec5SDimitry Andric TheIndex.getOrInsertTypeIdCompatibleVtableSummary( 71150b57cec5SDimitry Andric {Strtab.data() + Record[Slot], 71160b57cec5SDimitry Andric static_cast<size_t>(Record[Slot + 1])}); 71170b57cec5SDimitry Andric Slot += 2; 71180b57cec5SDimitry Andric 71190b57cec5SDimitry Andric while (Slot < Record.size()) 71200b57cec5SDimitry Andric parseTypeIdCompatibleVtableInfo(Record, Slot, TypeId); 71210b57cec5SDimitry Andric } 71220b57cec5SDimitry Andric 71230b57cec5SDimitry Andric static void setSpecialRefs(std::vector<ValueInfo> &Refs, unsigned ROCnt, 71240b57cec5SDimitry Andric unsigned WOCnt) { 71250b57cec5SDimitry Andric // Readonly and writeonly refs are in the end of the refs list. 71260b57cec5SDimitry Andric assert(ROCnt + WOCnt <= Refs.size()); 71270b57cec5SDimitry Andric unsigned FirstWORef = Refs.size() - WOCnt; 71280b57cec5SDimitry Andric unsigned RefNo = FirstWORef - ROCnt; 71290b57cec5SDimitry Andric for (; RefNo < FirstWORef; ++RefNo) 71300b57cec5SDimitry Andric Refs[RefNo].setReadOnly(); 71310b57cec5SDimitry Andric for (; RefNo < Refs.size(); ++RefNo) 71320b57cec5SDimitry Andric Refs[RefNo].setWriteOnly(); 71330b57cec5SDimitry Andric } 71340b57cec5SDimitry Andric 71350b57cec5SDimitry Andric // Eagerly parse the entire summary block. This populates the GlobalValueSummary 71360b57cec5SDimitry Andric // objects in the index. 71370b57cec5SDimitry Andric Error ModuleSummaryIndexBitcodeReader::parseEntireSummary(unsigned ID) { 71380b57cec5SDimitry Andric if (Error Err = Stream.EnterSubBlock(ID)) 71390b57cec5SDimitry Andric return Err; 71400b57cec5SDimitry Andric SmallVector<uint64_t, 64> Record; 71410b57cec5SDimitry Andric 71420b57cec5SDimitry Andric // Parse version 71430b57cec5SDimitry Andric { 71440b57cec5SDimitry Andric Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); 71450b57cec5SDimitry Andric if (!MaybeEntry) 71460b57cec5SDimitry Andric return MaybeEntry.takeError(); 71470b57cec5SDimitry Andric BitstreamEntry Entry = MaybeEntry.get(); 71480b57cec5SDimitry Andric 71490b57cec5SDimitry Andric if (Entry.Kind != BitstreamEntry::Record) 71500b57cec5SDimitry Andric return error("Invalid Summary Block: record for version expected"); 71510b57cec5SDimitry Andric Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record); 71520b57cec5SDimitry Andric if (!MaybeRecord) 71530b57cec5SDimitry Andric return MaybeRecord.takeError(); 71540b57cec5SDimitry Andric if (MaybeRecord.get() != bitc::FS_VERSION) 71550b57cec5SDimitry Andric return error("Invalid Summary Block: version expected"); 71560b57cec5SDimitry Andric } 71570b57cec5SDimitry Andric const uint64_t Version = Record[0]; 71580b57cec5SDimitry Andric const bool IsOldProfileFormat = Version == 1; 7159480093f4SDimitry Andric if (Version < 1 || Version > ModuleSummaryIndex::BitcodeSummaryVersion) 71600b57cec5SDimitry Andric return error("Invalid summary version " + Twine(Version) + 7161480093f4SDimitry Andric ". Version should be in the range [1-" + 7162480093f4SDimitry Andric Twine(ModuleSummaryIndex::BitcodeSummaryVersion) + 7163480093f4SDimitry Andric "]."); 71640b57cec5SDimitry Andric Record.clear(); 71650b57cec5SDimitry Andric 71660b57cec5SDimitry Andric // Keep around the last seen summary to be used when we see an optional 71670b57cec5SDimitry Andric // "OriginalName" attachement. 71680b57cec5SDimitry Andric GlobalValueSummary *LastSeenSummary = nullptr; 71690b57cec5SDimitry Andric GlobalValue::GUID LastSeenGUID = 0; 71700b57cec5SDimitry Andric 71710b57cec5SDimitry Andric // We can expect to see any number of type ID information records before 71720b57cec5SDimitry Andric // each function summary records; these variables store the information 71730b57cec5SDimitry Andric // collected so far so that it can be used to create the summary object. 71740b57cec5SDimitry Andric std::vector<GlobalValue::GUID> PendingTypeTests; 71750b57cec5SDimitry Andric std::vector<FunctionSummary::VFuncId> PendingTypeTestAssumeVCalls, 71760b57cec5SDimitry Andric PendingTypeCheckedLoadVCalls; 71770b57cec5SDimitry Andric std::vector<FunctionSummary::ConstVCall> PendingTypeTestAssumeConstVCalls, 71780b57cec5SDimitry Andric PendingTypeCheckedLoadConstVCalls; 71795ffd83dbSDimitry Andric std::vector<FunctionSummary::ParamAccess> PendingParamAccesses; 71800b57cec5SDimitry Andric 7181bdd1243dSDimitry Andric std::vector<CallsiteInfo> PendingCallsites; 7182bdd1243dSDimitry Andric std::vector<AllocInfo> PendingAllocs; 7183bdd1243dSDimitry Andric 71840b57cec5SDimitry Andric while (true) { 71850b57cec5SDimitry Andric Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); 71860b57cec5SDimitry Andric if (!MaybeEntry) 71870b57cec5SDimitry Andric return MaybeEntry.takeError(); 71880b57cec5SDimitry Andric BitstreamEntry Entry = MaybeEntry.get(); 71890b57cec5SDimitry Andric 71900b57cec5SDimitry Andric switch (Entry.Kind) { 71910b57cec5SDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already. 71920b57cec5SDimitry Andric case BitstreamEntry::Error: 71930b57cec5SDimitry Andric return error("Malformed block"); 71940b57cec5SDimitry Andric case BitstreamEntry::EndBlock: 71950b57cec5SDimitry Andric return Error::success(); 71960b57cec5SDimitry Andric case BitstreamEntry::Record: 71970b57cec5SDimitry Andric // The interesting case. 71980b57cec5SDimitry Andric break; 71990b57cec5SDimitry Andric } 72000b57cec5SDimitry Andric 72010b57cec5SDimitry Andric // Read a record. The record format depends on whether this 72020b57cec5SDimitry Andric // is a per-module index or a combined index file. In the per-module 72030b57cec5SDimitry Andric // case the records contain the associated value's ID for correlation 72040b57cec5SDimitry Andric // with VST entries. In the combined index the correlation is done 72050b57cec5SDimitry Andric // via the bitcode offset of the summary records (which were saved 72060b57cec5SDimitry Andric // in the combined index VST entries). The records also contain 72070b57cec5SDimitry Andric // information used for ThinLTO renaming and importing. 72080b57cec5SDimitry Andric Record.clear(); 72090b57cec5SDimitry Andric Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record); 72100b57cec5SDimitry Andric if (!MaybeBitCode) 72110b57cec5SDimitry Andric return MaybeBitCode.takeError(); 72120b57cec5SDimitry Andric switch (unsigned BitCode = MaybeBitCode.get()) { 72130b57cec5SDimitry Andric default: // Default behavior: ignore. 72140b57cec5SDimitry Andric break; 72150b57cec5SDimitry Andric case bitc::FS_FLAGS: { // [flags] 72165ffd83dbSDimitry Andric TheIndex.setFlags(Record[0]); 72170b57cec5SDimitry Andric break; 72180b57cec5SDimitry Andric } 72190b57cec5SDimitry Andric case bitc::FS_VALUE_GUID: { // [valueid, refguid] 72200b57cec5SDimitry Andric uint64_t ValueID = Record[0]; 72210b57cec5SDimitry Andric GlobalValue::GUID RefGUID = Record[1]; 7222bdd1243dSDimitry Andric ValueIdToValueInfoMap[ValueID] = std::make_tuple( 7223bdd1243dSDimitry Andric TheIndex.getOrInsertValueInfo(RefGUID), RefGUID, RefGUID); 72240b57cec5SDimitry Andric break; 72250b57cec5SDimitry Andric } 72260b57cec5SDimitry Andric // FS_PERMODULE: [valueid, flags, instcount, fflags, numrefs, 72270b57cec5SDimitry Andric // numrefs x valueid, n x (valueid)] 72280b57cec5SDimitry Andric // FS_PERMODULE_PROFILE: [valueid, flags, instcount, fflags, numrefs, 72290b57cec5SDimitry Andric // numrefs x valueid, 72300b57cec5SDimitry Andric // n x (valueid, hotness)] 72310b57cec5SDimitry Andric // FS_PERMODULE_RELBF: [valueid, flags, instcount, fflags, numrefs, 72320b57cec5SDimitry Andric // numrefs x valueid, 72330b57cec5SDimitry Andric // n x (valueid, relblockfreq)] 72340b57cec5SDimitry Andric case bitc::FS_PERMODULE: 72350b57cec5SDimitry Andric case bitc::FS_PERMODULE_RELBF: 72360b57cec5SDimitry Andric case bitc::FS_PERMODULE_PROFILE: { 72370b57cec5SDimitry Andric unsigned ValueID = Record[0]; 72380b57cec5SDimitry Andric uint64_t RawFlags = Record[1]; 72390b57cec5SDimitry Andric unsigned InstCount = Record[2]; 72400b57cec5SDimitry Andric uint64_t RawFunFlags = 0; 72410b57cec5SDimitry Andric unsigned NumRefs = Record[3]; 72420b57cec5SDimitry Andric unsigned NumRORefs = 0, NumWORefs = 0; 72430b57cec5SDimitry Andric int RefListStartIndex = 4; 72440b57cec5SDimitry Andric if (Version >= 4) { 72450b57cec5SDimitry Andric RawFunFlags = Record[3]; 72460b57cec5SDimitry Andric NumRefs = Record[4]; 72470b57cec5SDimitry Andric RefListStartIndex = 5; 72480b57cec5SDimitry Andric if (Version >= 5) { 72490b57cec5SDimitry Andric NumRORefs = Record[5]; 72500b57cec5SDimitry Andric RefListStartIndex = 6; 72510b57cec5SDimitry Andric if (Version >= 7) { 72520b57cec5SDimitry Andric NumWORefs = Record[6]; 72530b57cec5SDimitry Andric RefListStartIndex = 7; 72540b57cec5SDimitry Andric } 72550b57cec5SDimitry Andric } 72560b57cec5SDimitry Andric } 72570b57cec5SDimitry Andric 72580b57cec5SDimitry Andric auto Flags = getDecodedGVSummaryFlags(RawFlags, Version); 72590b57cec5SDimitry Andric // The module path string ref set in the summary must be owned by the 72600b57cec5SDimitry Andric // index's module string table. Since we don't have a module path 72610b57cec5SDimitry Andric // string table section in the per-module index, we create a single 72620b57cec5SDimitry Andric // module path string table entry with an empty (0) ID to take 72630b57cec5SDimitry Andric // ownership. 72640b57cec5SDimitry Andric int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs; 72650b57cec5SDimitry Andric assert(Record.size() >= RefListStartIndex + NumRefs && 72660b57cec5SDimitry Andric "Record size inconsistent with number of references"); 72670b57cec5SDimitry Andric std::vector<ValueInfo> Refs = makeRefList( 72680b57cec5SDimitry Andric ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs)); 72690b57cec5SDimitry Andric bool HasProfile = (BitCode == bitc::FS_PERMODULE_PROFILE); 72700b57cec5SDimitry Andric bool HasRelBF = (BitCode == bitc::FS_PERMODULE_RELBF); 72710b57cec5SDimitry Andric std::vector<FunctionSummary::EdgeTy> Calls = makeCallList( 72720b57cec5SDimitry Andric ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex), 72730b57cec5SDimitry Andric IsOldProfileFormat, HasProfile, HasRelBF); 72740b57cec5SDimitry Andric setSpecialRefs(Refs, NumRORefs, NumWORefs); 7275bdd1243dSDimitry Andric auto VIAndOriginalGUID = getValueInfoFromValueId(ValueID); 7276bdd1243dSDimitry Andric // In order to save memory, only record the memprof summaries if this is 7277bdd1243dSDimitry Andric // the prevailing copy of a symbol. The linker doesn't resolve local 7278bdd1243dSDimitry Andric // linkage values so don't check whether those are prevailing. 7279bdd1243dSDimitry Andric auto LT = (GlobalValue::LinkageTypes)Flags.Linkage; 7280bdd1243dSDimitry Andric if (IsPrevailing && 7281bdd1243dSDimitry Andric !GlobalValue::isLocalLinkage(LT) && 7282bdd1243dSDimitry Andric !IsPrevailing(std::get<2>(VIAndOriginalGUID))) { 7283bdd1243dSDimitry Andric PendingCallsites.clear(); 7284bdd1243dSDimitry Andric PendingAllocs.clear(); 7285bdd1243dSDimitry Andric } 72868bcb0991SDimitry Andric auto FS = std::make_unique<FunctionSummary>( 72870b57cec5SDimitry Andric Flags, InstCount, getDecodedFFlags(RawFunFlags), /*EntryCount=*/0, 72880b57cec5SDimitry Andric std::move(Refs), std::move(Calls), std::move(PendingTypeTests), 72890b57cec5SDimitry Andric std::move(PendingTypeTestAssumeVCalls), 72900b57cec5SDimitry Andric std::move(PendingTypeCheckedLoadVCalls), 72910b57cec5SDimitry Andric std::move(PendingTypeTestAssumeConstVCalls), 72925ffd83dbSDimitry Andric std::move(PendingTypeCheckedLoadConstVCalls), 7293bdd1243dSDimitry Andric std::move(PendingParamAccesses), std::move(PendingCallsites), 7294bdd1243dSDimitry Andric std::move(PendingAllocs)); 72950b57cec5SDimitry Andric FS->setModulePath(getThisModule()->first()); 7296bdd1243dSDimitry Andric FS->setOriginalName(std::get<1>(VIAndOriginalGUID)); 7297bdd1243dSDimitry Andric TheIndex.addGlobalValueSummary(std::get<0>(VIAndOriginalGUID), 7298bdd1243dSDimitry Andric std::move(FS)); 72990b57cec5SDimitry Andric break; 73000b57cec5SDimitry Andric } 73010b57cec5SDimitry Andric // FS_ALIAS: [valueid, flags, valueid] 73020b57cec5SDimitry Andric // Aliases must be emitted (and parsed) after all FS_PERMODULE entries, as 73030b57cec5SDimitry Andric // they expect all aliasee summaries to be available. 73040b57cec5SDimitry Andric case bitc::FS_ALIAS: { 73050b57cec5SDimitry Andric unsigned ValueID = Record[0]; 73060b57cec5SDimitry Andric uint64_t RawFlags = Record[1]; 73070b57cec5SDimitry Andric unsigned AliaseeID = Record[2]; 73080b57cec5SDimitry Andric auto Flags = getDecodedGVSummaryFlags(RawFlags, Version); 73098bcb0991SDimitry Andric auto AS = std::make_unique<AliasSummary>(Flags); 73100b57cec5SDimitry Andric // The module path string ref set in the summary must be owned by the 73110b57cec5SDimitry Andric // index's module string table. Since we don't have a module path 73120b57cec5SDimitry Andric // string table section in the per-module index, we create a single 73130b57cec5SDimitry Andric // module path string table entry with an empty (0) ID to take 73140b57cec5SDimitry Andric // ownership. 73150b57cec5SDimitry Andric AS->setModulePath(getThisModule()->first()); 73160b57cec5SDimitry Andric 7317bdd1243dSDimitry Andric auto AliaseeVI = std::get<0>(getValueInfoFromValueId(AliaseeID)); 73180b57cec5SDimitry Andric auto AliaseeInModule = TheIndex.findSummaryInModule(AliaseeVI, ModulePath); 73190b57cec5SDimitry Andric if (!AliaseeInModule) 73200b57cec5SDimitry Andric return error("Alias expects aliasee summary to be parsed"); 73210b57cec5SDimitry Andric AS->setAliasee(AliaseeVI, AliaseeInModule); 73220b57cec5SDimitry Andric 73230b57cec5SDimitry Andric auto GUID = getValueInfoFromValueId(ValueID); 7324bdd1243dSDimitry Andric AS->setOriginalName(std::get<1>(GUID)); 7325bdd1243dSDimitry Andric TheIndex.addGlobalValueSummary(std::get<0>(GUID), std::move(AS)); 73260b57cec5SDimitry Andric break; 73270b57cec5SDimitry Andric } 73280b57cec5SDimitry Andric // FS_PERMODULE_GLOBALVAR_INIT_REFS: [valueid, flags, varflags, n x valueid] 73290b57cec5SDimitry Andric case bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS: { 73300b57cec5SDimitry Andric unsigned ValueID = Record[0]; 73310b57cec5SDimitry Andric uint64_t RawFlags = Record[1]; 73320b57cec5SDimitry Andric unsigned RefArrayStart = 2; 73330b57cec5SDimitry Andric GlobalVarSummary::GVarFlags GVF(/* ReadOnly */ false, 73345ffd83dbSDimitry Andric /* WriteOnly */ false, 73355ffd83dbSDimitry Andric /* Constant */ false, 73365ffd83dbSDimitry Andric GlobalObject::VCallVisibilityPublic); 73370b57cec5SDimitry Andric auto Flags = getDecodedGVSummaryFlags(RawFlags, Version); 73380b57cec5SDimitry Andric if (Version >= 5) { 73390b57cec5SDimitry Andric GVF = getDecodedGVarFlags(Record[2]); 73400b57cec5SDimitry Andric RefArrayStart = 3; 73410b57cec5SDimitry Andric } 73420b57cec5SDimitry Andric std::vector<ValueInfo> Refs = 73430b57cec5SDimitry Andric makeRefList(ArrayRef<uint64_t>(Record).slice(RefArrayStart)); 73440b57cec5SDimitry Andric auto FS = 73458bcb0991SDimitry Andric std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs)); 73460b57cec5SDimitry Andric FS->setModulePath(getThisModule()->first()); 73470b57cec5SDimitry Andric auto GUID = getValueInfoFromValueId(ValueID); 7348bdd1243dSDimitry Andric FS->setOriginalName(std::get<1>(GUID)); 7349bdd1243dSDimitry Andric TheIndex.addGlobalValueSummary(std::get<0>(GUID), std::move(FS)); 73500b57cec5SDimitry Andric break; 73510b57cec5SDimitry Andric } 73520b57cec5SDimitry Andric // FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS: [valueid, flags, varflags, 73530b57cec5SDimitry Andric // numrefs, numrefs x valueid, 73540b57cec5SDimitry Andric // n x (valueid, offset)] 73550b57cec5SDimitry Andric case bitc::FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS: { 73560b57cec5SDimitry Andric unsigned ValueID = Record[0]; 73570b57cec5SDimitry Andric uint64_t RawFlags = Record[1]; 73580b57cec5SDimitry Andric GlobalVarSummary::GVarFlags GVF = getDecodedGVarFlags(Record[2]); 73590b57cec5SDimitry Andric unsigned NumRefs = Record[3]; 73600b57cec5SDimitry Andric unsigned RefListStartIndex = 4; 73610b57cec5SDimitry Andric unsigned VTableListStartIndex = RefListStartIndex + NumRefs; 73620b57cec5SDimitry Andric auto Flags = getDecodedGVSummaryFlags(RawFlags, Version); 73630b57cec5SDimitry Andric std::vector<ValueInfo> Refs = makeRefList( 73640b57cec5SDimitry Andric ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs)); 73650b57cec5SDimitry Andric VTableFuncList VTableFuncs; 73660b57cec5SDimitry Andric for (unsigned I = VTableListStartIndex, E = Record.size(); I != E; ++I) { 7367bdd1243dSDimitry Andric ValueInfo Callee = std::get<0>(getValueInfoFromValueId(Record[I])); 73680b57cec5SDimitry Andric uint64_t Offset = Record[++I]; 73690b57cec5SDimitry Andric VTableFuncs.push_back({Callee, Offset}); 73700b57cec5SDimitry Andric } 73710b57cec5SDimitry Andric auto VS = 73728bcb0991SDimitry Andric std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs)); 73730b57cec5SDimitry Andric VS->setModulePath(getThisModule()->first()); 73740b57cec5SDimitry Andric VS->setVTableFuncs(VTableFuncs); 73750b57cec5SDimitry Andric auto GUID = getValueInfoFromValueId(ValueID); 7376bdd1243dSDimitry Andric VS->setOriginalName(std::get<1>(GUID)); 7377bdd1243dSDimitry Andric TheIndex.addGlobalValueSummary(std::get<0>(GUID), std::move(VS)); 73780b57cec5SDimitry Andric break; 73790b57cec5SDimitry Andric } 73800b57cec5SDimitry Andric // FS_COMBINED: [valueid, modid, flags, instcount, fflags, numrefs, 73810b57cec5SDimitry Andric // numrefs x valueid, n x (valueid)] 73820b57cec5SDimitry Andric // FS_COMBINED_PROFILE: [valueid, modid, flags, instcount, fflags, numrefs, 73830b57cec5SDimitry Andric // numrefs x valueid, n x (valueid, hotness)] 73840b57cec5SDimitry Andric case bitc::FS_COMBINED: 73850b57cec5SDimitry Andric case bitc::FS_COMBINED_PROFILE: { 73860b57cec5SDimitry Andric unsigned ValueID = Record[0]; 73870b57cec5SDimitry Andric uint64_t ModuleId = Record[1]; 73880b57cec5SDimitry Andric uint64_t RawFlags = Record[2]; 73890b57cec5SDimitry Andric unsigned InstCount = Record[3]; 73900b57cec5SDimitry Andric uint64_t RawFunFlags = 0; 73910b57cec5SDimitry Andric uint64_t EntryCount = 0; 73920b57cec5SDimitry Andric unsigned NumRefs = Record[4]; 73930b57cec5SDimitry Andric unsigned NumRORefs = 0, NumWORefs = 0; 73940b57cec5SDimitry Andric int RefListStartIndex = 5; 73950b57cec5SDimitry Andric 73960b57cec5SDimitry Andric if (Version >= 4) { 73970b57cec5SDimitry Andric RawFunFlags = Record[4]; 73980b57cec5SDimitry Andric RefListStartIndex = 6; 73990b57cec5SDimitry Andric size_t NumRefsIndex = 5; 74000b57cec5SDimitry Andric if (Version >= 5) { 74010b57cec5SDimitry Andric unsigned NumRORefsOffset = 1; 74020b57cec5SDimitry Andric RefListStartIndex = 7; 74030b57cec5SDimitry Andric if (Version >= 6) { 74040b57cec5SDimitry Andric NumRefsIndex = 6; 74050b57cec5SDimitry Andric EntryCount = Record[5]; 74060b57cec5SDimitry Andric RefListStartIndex = 8; 74070b57cec5SDimitry Andric if (Version >= 7) { 74080b57cec5SDimitry Andric RefListStartIndex = 9; 74090b57cec5SDimitry Andric NumWORefs = Record[8]; 74100b57cec5SDimitry Andric NumRORefsOffset = 2; 74110b57cec5SDimitry Andric } 74120b57cec5SDimitry Andric } 74130b57cec5SDimitry Andric NumRORefs = Record[RefListStartIndex - NumRORefsOffset]; 74140b57cec5SDimitry Andric } 74150b57cec5SDimitry Andric NumRefs = Record[NumRefsIndex]; 74160b57cec5SDimitry Andric } 74170b57cec5SDimitry Andric 74180b57cec5SDimitry Andric auto Flags = getDecodedGVSummaryFlags(RawFlags, Version); 74190b57cec5SDimitry Andric int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs; 74200b57cec5SDimitry Andric assert(Record.size() >= RefListStartIndex + NumRefs && 74210b57cec5SDimitry Andric "Record size inconsistent with number of references"); 74220b57cec5SDimitry Andric std::vector<ValueInfo> Refs = makeRefList( 74230b57cec5SDimitry Andric ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs)); 74240b57cec5SDimitry Andric bool HasProfile = (BitCode == bitc::FS_COMBINED_PROFILE); 74250b57cec5SDimitry Andric std::vector<FunctionSummary::EdgeTy> Edges = makeCallList( 74260b57cec5SDimitry Andric ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex), 74270b57cec5SDimitry Andric IsOldProfileFormat, HasProfile, false); 7428bdd1243dSDimitry Andric ValueInfo VI = std::get<0>(getValueInfoFromValueId(ValueID)); 74290b57cec5SDimitry Andric setSpecialRefs(Refs, NumRORefs, NumWORefs); 74308bcb0991SDimitry Andric auto FS = std::make_unique<FunctionSummary>( 74310b57cec5SDimitry Andric Flags, InstCount, getDecodedFFlags(RawFunFlags), EntryCount, 74320b57cec5SDimitry Andric std::move(Refs), std::move(Edges), std::move(PendingTypeTests), 74330b57cec5SDimitry Andric std::move(PendingTypeTestAssumeVCalls), 74340b57cec5SDimitry Andric std::move(PendingTypeCheckedLoadVCalls), 74350b57cec5SDimitry Andric std::move(PendingTypeTestAssumeConstVCalls), 74365ffd83dbSDimitry Andric std::move(PendingTypeCheckedLoadConstVCalls), 7437bdd1243dSDimitry Andric std::move(PendingParamAccesses), std::move(PendingCallsites), 7438bdd1243dSDimitry Andric std::move(PendingAllocs)); 74390b57cec5SDimitry Andric LastSeenSummary = FS.get(); 74400b57cec5SDimitry Andric LastSeenGUID = VI.getGUID(); 74410b57cec5SDimitry Andric FS->setModulePath(ModuleIdMap[ModuleId]); 74420b57cec5SDimitry Andric TheIndex.addGlobalValueSummary(VI, std::move(FS)); 74430b57cec5SDimitry Andric break; 74440b57cec5SDimitry Andric } 74450b57cec5SDimitry Andric // FS_COMBINED_ALIAS: [valueid, modid, flags, valueid] 74460b57cec5SDimitry Andric // Aliases must be emitted (and parsed) after all FS_COMBINED entries, as 74470b57cec5SDimitry Andric // they expect all aliasee summaries to be available. 74480b57cec5SDimitry Andric case bitc::FS_COMBINED_ALIAS: { 74490b57cec5SDimitry Andric unsigned ValueID = Record[0]; 74500b57cec5SDimitry Andric uint64_t ModuleId = Record[1]; 74510b57cec5SDimitry Andric uint64_t RawFlags = Record[2]; 74520b57cec5SDimitry Andric unsigned AliaseeValueId = Record[3]; 74530b57cec5SDimitry Andric auto Flags = getDecodedGVSummaryFlags(RawFlags, Version); 74548bcb0991SDimitry Andric auto AS = std::make_unique<AliasSummary>(Flags); 74550b57cec5SDimitry Andric LastSeenSummary = AS.get(); 74560b57cec5SDimitry Andric AS->setModulePath(ModuleIdMap[ModuleId]); 74570b57cec5SDimitry Andric 7458bdd1243dSDimitry Andric auto AliaseeVI = std::get<0>(getValueInfoFromValueId(AliaseeValueId)); 74590b57cec5SDimitry Andric auto AliaseeInModule = TheIndex.findSummaryInModule(AliaseeVI, AS->modulePath()); 74600b57cec5SDimitry Andric AS->setAliasee(AliaseeVI, AliaseeInModule); 74610b57cec5SDimitry Andric 7462bdd1243dSDimitry Andric ValueInfo VI = std::get<0>(getValueInfoFromValueId(ValueID)); 74630b57cec5SDimitry Andric LastSeenGUID = VI.getGUID(); 74640b57cec5SDimitry Andric TheIndex.addGlobalValueSummary(VI, std::move(AS)); 74650b57cec5SDimitry Andric break; 74660b57cec5SDimitry Andric } 74670b57cec5SDimitry Andric // FS_COMBINED_GLOBALVAR_INIT_REFS: [valueid, modid, flags, n x valueid] 74680b57cec5SDimitry Andric case bitc::FS_COMBINED_GLOBALVAR_INIT_REFS: { 74690b57cec5SDimitry Andric unsigned ValueID = Record[0]; 74700b57cec5SDimitry Andric uint64_t ModuleId = Record[1]; 74710b57cec5SDimitry Andric uint64_t RawFlags = Record[2]; 74720b57cec5SDimitry Andric unsigned RefArrayStart = 3; 74730b57cec5SDimitry Andric GlobalVarSummary::GVarFlags GVF(/* ReadOnly */ false, 74745ffd83dbSDimitry Andric /* WriteOnly */ false, 74755ffd83dbSDimitry Andric /* Constant */ false, 74765ffd83dbSDimitry Andric GlobalObject::VCallVisibilityPublic); 74770b57cec5SDimitry Andric auto Flags = getDecodedGVSummaryFlags(RawFlags, Version); 74780b57cec5SDimitry Andric if (Version >= 5) { 74790b57cec5SDimitry Andric GVF = getDecodedGVarFlags(Record[3]); 74800b57cec5SDimitry Andric RefArrayStart = 4; 74810b57cec5SDimitry Andric } 74820b57cec5SDimitry Andric std::vector<ValueInfo> Refs = 74830b57cec5SDimitry Andric makeRefList(ArrayRef<uint64_t>(Record).slice(RefArrayStart)); 74840b57cec5SDimitry Andric auto FS = 74858bcb0991SDimitry Andric std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs)); 74860b57cec5SDimitry Andric LastSeenSummary = FS.get(); 74870b57cec5SDimitry Andric FS->setModulePath(ModuleIdMap[ModuleId]); 7488bdd1243dSDimitry Andric ValueInfo VI = std::get<0>(getValueInfoFromValueId(ValueID)); 74890b57cec5SDimitry Andric LastSeenGUID = VI.getGUID(); 74900b57cec5SDimitry Andric TheIndex.addGlobalValueSummary(VI, std::move(FS)); 74910b57cec5SDimitry Andric break; 74920b57cec5SDimitry Andric } 74930b57cec5SDimitry Andric // FS_COMBINED_ORIGINAL_NAME: [original_name] 74940b57cec5SDimitry Andric case bitc::FS_COMBINED_ORIGINAL_NAME: { 74950b57cec5SDimitry Andric uint64_t OriginalName = Record[0]; 74960b57cec5SDimitry Andric if (!LastSeenSummary) 74970b57cec5SDimitry Andric return error("Name attachment that does not follow a combined record"); 74980b57cec5SDimitry Andric LastSeenSummary->setOriginalName(OriginalName); 74990b57cec5SDimitry Andric TheIndex.addOriginalName(LastSeenGUID, OriginalName); 75000b57cec5SDimitry Andric // Reset the LastSeenSummary 75010b57cec5SDimitry Andric LastSeenSummary = nullptr; 75020b57cec5SDimitry Andric LastSeenGUID = 0; 75030b57cec5SDimitry Andric break; 75040b57cec5SDimitry Andric } 75050b57cec5SDimitry Andric case bitc::FS_TYPE_TESTS: 75060b57cec5SDimitry Andric assert(PendingTypeTests.empty()); 7507e8d8bef9SDimitry Andric llvm::append_range(PendingTypeTests, Record); 75080b57cec5SDimitry Andric break; 75090b57cec5SDimitry Andric 75100b57cec5SDimitry Andric case bitc::FS_TYPE_TEST_ASSUME_VCALLS: 75110b57cec5SDimitry Andric assert(PendingTypeTestAssumeVCalls.empty()); 75120b57cec5SDimitry Andric for (unsigned I = 0; I != Record.size(); I += 2) 75130b57cec5SDimitry Andric PendingTypeTestAssumeVCalls.push_back({Record[I], Record[I+1]}); 75140b57cec5SDimitry Andric break; 75150b57cec5SDimitry Andric 75160b57cec5SDimitry Andric case bitc::FS_TYPE_CHECKED_LOAD_VCALLS: 75170b57cec5SDimitry Andric assert(PendingTypeCheckedLoadVCalls.empty()); 75180b57cec5SDimitry Andric for (unsigned I = 0; I != Record.size(); I += 2) 75190b57cec5SDimitry Andric PendingTypeCheckedLoadVCalls.push_back({Record[I], Record[I+1]}); 75200b57cec5SDimitry Andric break; 75210b57cec5SDimitry Andric 75220b57cec5SDimitry Andric case bitc::FS_TYPE_TEST_ASSUME_CONST_VCALL: 75230b57cec5SDimitry Andric PendingTypeTestAssumeConstVCalls.push_back( 75240b57cec5SDimitry Andric {{Record[0], Record[1]}, {Record.begin() + 2, Record.end()}}); 75250b57cec5SDimitry Andric break; 75260b57cec5SDimitry Andric 75270b57cec5SDimitry Andric case bitc::FS_TYPE_CHECKED_LOAD_CONST_VCALL: 75280b57cec5SDimitry Andric PendingTypeCheckedLoadConstVCalls.push_back( 75290b57cec5SDimitry Andric {{Record[0], Record[1]}, {Record.begin() + 2, Record.end()}}); 75300b57cec5SDimitry Andric break; 75310b57cec5SDimitry Andric 75320b57cec5SDimitry Andric case bitc::FS_CFI_FUNCTION_DEFS: { 75330b57cec5SDimitry Andric std::set<std::string> &CfiFunctionDefs = TheIndex.cfiFunctionDefs(); 75340b57cec5SDimitry Andric for (unsigned I = 0; I != Record.size(); I += 2) 75350b57cec5SDimitry Andric CfiFunctionDefs.insert( 75360b57cec5SDimitry Andric {Strtab.data() + Record[I], static_cast<size_t>(Record[I + 1])}); 75370b57cec5SDimitry Andric break; 75380b57cec5SDimitry Andric } 75390b57cec5SDimitry Andric 75400b57cec5SDimitry Andric case bitc::FS_CFI_FUNCTION_DECLS: { 75410b57cec5SDimitry Andric std::set<std::string> &CfiFunctionDecls = TheIndex.cfiFunctionDecls(); 75420b57cec5SDimitry Andric for (unsigned I = 0; I != Record.size(); I += 2) 75430b57cec5SDimitry Andric CfiFunctionDecls.insert( 75440b57cec5SDimitry Andric {Strtab.data() + Record[I], static_cast<size_t>(Record[I + 1])}); 75450b57cec5SDimitry Andric break; 75460b57cec5SDimitry Andric } 75470b57cec5SDimitry Andric 75480b57cec5SDimitry Andric case bitc::FS_TYPE_ID: 75490b57cec5SDimitry Andric parseTypeIdSummaryRecord(Record, Strtab, TheIndex); 75500b57cec5SDimitry Andric break; 75510b57cec5SDimitry Andric 75520b57cec5SDimitry Andric case bitc::FS_TYPE_ID_METADATA: 75530b57cec5SDimitry Andric parseTypeIdCompatibleVtableSummaryRecord(Record); 75540b57cec5SDimitry Andric break; 75555ffd83dbSDimitry Andric 75565ffd83dbSDimitry Andric case bitc::FS_BLOCK_COUNT: 75575ffd83dbSDimitry Andric TheIndex.addBlockCount(Record[0]); 75585ffd83dbSDimitry Andric break; 75595ffd83dbSDimitry Andric 75605ffd83dbSDimitry Andric case bitc::FS_PARAM_ACCESS: { 75615ffd83dbSDimitry Andric PendingParamAccesses = parseParamAccesses(Record); 75625ffd83dbSDimitry Andric break; 75635ffd83dbSDimitry Andric } 7564bdd1243dSDimitry Andric 7565bdd1243dSDimitry Andric case bitc::FS_STACK_IDS: { // [n x stackid] 7566bdd1243dSDimitry Andric // Save stack ids in the reader to consult when adding stack ids from the 7567bdd1243dSDimitry Andric // lists in the stack node and alloc node entries. 7568bdd1243dSDimitry Andric StackIds = ArrayRef<uint64_t>(Record); 7569bdd1243dSDimitry Andric break; 7570bdd1243dSDimitry Andric } 7571bdd1243dSDimitry Andric 7572bdd1243dSDimitry Andric case bitc::FS_PERMODULE_CALLSITE_INFO: { 7573bdd1243dSDimitry Andric unsigned ValueID = Record[0]; 7574bdd1243dSDimitry Andric SmallVector<unsigned> StackIdList; 7575bdd1243dSDimitry Andric for (auto R = Record.begin() + 1; R != Record.end(); R++) { 7576bdd1243dSDimitry Andric assert(*R < StackIds.size()); 7577bdd1243dSDimitry Andric StackIdList.push_back(TheIndex.addOrGetStackIdIndex(StackIds[*R])); 7578bdd1243dSDimitry Andric } 7579bdd1243dSDimitry Andric ValueInfo VI = std::get<0>(getValueInfoFromValueId(ValueID)); 7580bdd1243dSDimitry Andric PendingCallsites.push_back(CallsiteInfo({VI, std::move(StackIdList)})); 7581bdd1243dSDimitry Andric break; 7582bdd1243dSDimitry Andric } 7583bdd1243dSDimitry Andric 7584bdd1243dSDimitry Andric case bitc::FS_COMBINED_CALLSITE_INFO: { 7585bdd1243dSDimitry Andric auto RecordIter = Record.begin(); 7586bdd1243dSDimitry Andric unsigned ValueID = *RecordIter++; 7587bdd1243dSDimitry Andric unsigned NumStackIds = *RecordIter++; 7588bdd1243dSDimitry Andric unsigned NumVersions = *RecordIter++; 7589bdd1243dSDimitry Andric assert(Record.size() == 3 + NumStackIds + NumVersions); 7590bdd1243dSDimitry Andric SmallVector<unsigned> StackIdList; 7591bdd1243dSDimitry Andric for (unsigned J = 0; J < NumStackIds; J++) { 7592bdd1243dSDimitry Andric assert(*RecordIter < StackIds.size()); 7593bdd1243dSDimitry Andric StackIdList.push_back( 7594bdd1243dSDimitry Andric TheIndex.addOrGetStackIdIndex(StackIds[*RecordIter++])); 7595bdd1243dSDimitry Andric } 7596bdd1243dSDimitry Andric SmallVector<unsigned> Versions; 7597bdd1243dSDimitry Andric for (unsigned J = 0; J < NumVersions; J++) 7598bdd1243dSDimitry Andric Versions.push_back(*RecordIter++); 7599bdd1243dSDimitry Andric ValueInfo VI = std::get<0>( 7600bdd1243dSDimitry Andric getValueInfoFromValueId</*AllowNullValueInfo*/ true>(ValueID)); 7601bdd1243dSDimitry Andric PendingCallsites.push_back( 7602bdd1243dSDimitry Andric CallsiteInfo({VI, std::move(Versions), std::move(StackIdList)})); 7603bdd1243dSDimitry Andric break; 7604bdd1243dSDimitry Andric } 7605bdd1243dSDimitry Andric 7606bdd1243dSDimitry Andric case bitc::FS_PERMODULE_ALLOC_INFO: { 7607bdd1243dSDimitry Andric unsigned I = 0; 7608bdd1243dSDimitry Andric std::vector<MIBInfo> MIBs; 7609bdd1243dSDimitry Andric while (I < Record.size()) { 7610bdd1243dSDimitry Andric assert(Record.size() - I >= 2); 7611bdd1243dSDimitry Andric AllocationType AllocType = (AllocationType)Record[I++]; 7612bdd1243dSDimitry Andric unsigned NumStackEntries = Record[I++]; 7613bdd1243dSDimitry Andric assert(Record.size() - I >= NumStackEntries); 7614bdd1243dSDimitry Andric SmallVector<unsigned> StackIdList; 7615bdd1243dSDimitry Andric for (unsigned J = 0; J < NumStackEntries; J++) { 7616bdd1243dSDimitry Andric assert(Record[I] < StackIds.size()); 7617bdd1243dSDimitry Andric StackIdList.push_back( 7618bdd1243dSDimitry Andric TheIndex.addOrGetStackIdIndex(StackIds[Record[I++]])); 7619bdd1243dSDimitry Andric } 7620bdd1243dSDimitry Andric MIBs.push_back(MIBInfo(AllocType, std::move(StackIdList))); 7621bdd1243dSDimitry Andric } 7622bdd1243dSDimitry Andric PendingAllocs.push_back(AllocInfo(std::move(MIBs))); 7623bdd1243dSDimitry Andric break; 7624bdd1243dSDimitry Andric } 7625bdd1243dSDimitry Andric 7626bdd1243dSDimitry Andric case bitc::FS_COMBINED_ALLOC_INFO: { 7627bdd1243dSDimitry Andric unsigned I = 0; 7628bdd1243dSDimitry Andric std::vector<MIBInfo> MIBs; 7629bdd1243dSDimitry Andric unsigned NumMIBs = Record[I++]; 7630bdd1243dSDimitry Andric unsigned NumVersions = Record[I++]; 7631bdd1243dSDimitry Andric unsigned MIBsRead = 0; 7632bdd1243dSDimitry Andric while (MIBsRead++ < NumMIBs) { 7633bdd1243dSDimitry Andric assert(Record.size() - I >= 2); 7634bdd1243dSDimitry Andric AllocationType AllocType = (AllocationType)Record[I++]; 7635bdd1243dSDimitry Andric unsigned NumStackEntries = Record[I++]; 7636bdd1243dSDimitry Andric assert(Record.size() - I >= NumStackEntries); 7637bdd1243dSDimitry Andric SmallVector<unsigned> StackIdList; 7638bdd1243dSDimitry Andric for (unsigned J = 0; J < NumStackEntries; J++) { 7639bdd1243dSDimitry Andric assert(Record[I] < StackIds.size()); 7640bdd1243dSDimitry Andric StackIdList.push_back( 7641bdd1243dSDimitry Andric TheIndex.addOrGetStackIdIndex(StackIds[Record[I++]])); 7642bdd1243dSDimitry Andric } 7643bdd1243dSDimitry Andric MIBs.push_back(MIBInfo(AllocType, std::move(StackIdList))); 7644bdd1243dSDimitry Andric } 7645bdd1243dSDimitry Andric assert(Record.size() - I >= NumVersions); 7646bdd1243dSDimitry Andric SmallVector<uint8_t> Versions; 7647bdd1243dSDimitry Andric for (unsigned J = 0; J < NumVersions; J++) 7648bdd1243dSDimitry Andric Versions.push_back(Record[I++]); 7649bdd1243dSDimitry Andric PendingAllocs.push_back( 7650bdd1243dSDimitry Andric AllocInfo(std::move(Versions), std::move(MIBs))); 7651bdd1243dSDimitry Andric break; 7652bdd1243dSDimitry Andric } 76530b57cec5SDimitry Andric } 76540b57cec5SDimitry Andric } 76550b57cec5SDimitry Andric llvm_unreachable("Exit infinite loop"); 76560b57cec5SDimitry Andric } 76570b57cec5SDimitry Andric 76580b57cec5SDimitry Andric // Parse the module string table block into the Index. 76590b57cec5SDimitry Andric // This populates the ModulePathStringTable map in the index. 76600b57cec5SDimitry Andric Error ModuleSummaryIndexBitcodeReader::parseModuleStringTable() { 76610b57cec5SDimitry Andric if (Error Err = Stream.EnterSubBlock(bitc::MODULE_STRTAB_BLOCK_ID)) 76620b57cec5SDimitry Andric return Err; 76630b57cec5SDimitry Andric 76640b57cec5SDimitry Andric SmallVector<uint64_t, 64> Record; 76650b57cec5SDimitry Andric 76660b57cec5SDimitry Andric SmallString<128> ModulePath; 76670b57cec5SDimitry Andric ModuleSummaryIndex::ModuleInfo *LastSeenModule = nullptr; 76680b57cec5SDimitry Andric 76690b57cec5SDimitry Andric while (true) { 76700b57cec5SDimitry Andric Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); 76710b57cec5SDimitry Andric if (!MaybeEntry) 76720b57cec5SDimitry Andric return MaybeEntry.takeError(); 76730b57cec5SDimitry Andric BitstreamEntry Entry = MaybeEntry.get(); 76740b57cec5SDimitry Andric 76750b57cec5SDimitry Andric switch (Entry.Kind) { 76760b57cec5SDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already. 76770b57cec5SDimitry Andric case BitstreamEntry::Error: 76780b57cec5SDimitry Andric return error("Malformed block"); 76790b57cec5SDimitry Andric case BitstreamEntry::EndBlock: 76800b57cec5SDimitry Andric return Error::success(); 76810b57cec5SDimitry Andric case BitstreamEntry::Record: 76820b57cec5SDimitry Andric // The interesting case. 76830b57cec5SDimitry Andric break; 76840b57cec5SDimitry Andric } 76850b57cec5SDimitry Andric 76860b57cec5SDimitry Andric Record.clear(); 76870b57cec5SDimitry Andric Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record); 76880b57cec5SDimitry Andric if (!MaybeRecord) 76890b57cec5SDimitry Andric return MaybeRecord.takeError(); 76900b57cec5SDimitry Andric switch (MaybeRecord.get()) { 76910b57cec5SDimitry Andric default: // Default behavior: ignore. 76920b57cec5SDimitry Andric break; 76930b57cec5SDimitry Andric case bitc::MST_CODE_ENTRY: { 76940b57cec5SDimitry Andric // MST_ENTRY: [modid, namechar x N] 76950b57cec5SDimitry Andric uint64_t ModuleId = Record[0]; 76960b57cec5SDimitry Andric 76970b57cec5SDimitry Andric if (convertToString(Record, 1, ModulePath)) 76980b57cec5SDimitry Andric return error("Invalid record"); 76990b57cec5SDimitry Andric 77000b57cec5SDimitry Andric LastSeenModule = TheIndex.addModule(ModulePath, ModuleId); 77010b57cec5SDimitry Andric ModuleIdMap[ModuleId] = LastSeenModule->first(); 77020b57cec5SDimitry Andric 77030b57cec5SDimitry Andric ModulePath.clear(); 77040b57cec5SDimitry Andric break; 77050b57cec5SDimitry Andric } 77060b57cec5SDimitry Andric /// MST_CODE_HASH: [5*i32] 77070b57cec5SDimitry Andric case bitc::MST_CODE_HASH: { 77080b57cec5SDimitry Andric if (Record.size() != 5) 77090b57cec5SDimitry Andric return error("Invalid hash length " + Twine(Record.size()).str()); 77100b57cec5SDimitry Andric if (!LastSeenModule) 77110b57cec5SDimitry Andric return error("Invalid hash that does not follow a module path"); 77120b57cec5SDimitry Andric int Pos = 0; 77130b57cec5SDimitry Andric for (auto &Val : Record) { 77140b57cec5SDimitry Andric assert(!(Val >> 32) && "Unexpected high bits set"); 77150b57cec5SDimitry Andric LastSeenModule->second.second[Pos++] = Val; 77160b57cec5SDimitry Andric } 77170b57cec5SDimitry Andric // Reset LastSeenModule to avoid overriding the hash unexpectedly. 77180b57cec5SDimitry Andric LastSeenModule = nullptr; 77190b57cec5SDimitry Andric break; 77200b57cec5SDimitry Andric } 77210b57cec5SDimitry Andric } 77220b57cec5SDimitry Andric } 77230b57cec5SDimitry Andric llvm_unreachable("Exit infinite loop"); 77240b57cec5SDimitry Andric } 77250b57cec5SDimitry Andric 77260b57cec5SDimitry Andric namespace { 77270b57cec5SDimitry Andric 77280b57cec5SDimitry Andric // FIXME: This class is only here to support the transition to llvm::Error. It 77290b57cec5SDimitry Andric // will be removed once this transition is complete. Clients should prefer to 77300b57cec5SDimitry Andric // deal with the Error value directly, rather than converting to error_code. 77310b57cec5SDimitry Andric class BitcodeErrorCategoryType : public std::error_category { 77320b57cec5SDimitry Andric const char *name() const noexcept override { 77330b57cec5SDimitry Andric return "llvm.bitcode"; 77340b57cec5SDimitry Andric } 77350b57cec5SDimitry Andric 77360b57cec5SDimitry Andric std::string message(int IE) const override { 77370b57cec5SDimitry Andric BitcodeError E = static_cast<BitcodeError>(IE); 77380b57cec5SDimitry Andric switch (E) { 77390b57cec5SDimitry Andric case BitcodeError::CorruptedBitcode: 77400b57cec5SDimitry Andric return "Corrupted bitcode"; 77410b57cec5SDimitry Andric } 77420b57cec5SDimitry Andric llvm_unreachable("Unknown error type!"); 77430b57cec5SDimitry Andric } 77440b57cec5SDimitry Andric }; 77450b57cec5SDimitry Andric 77460b57cec5SDimitry Andric } // end anonymous namespace 77470b57cec5SDimitry Andric 77480b57cec5SDimitry Andric const std::error_category &llvm::BitcodeErrorCategory() { 7749753f127fSDimitry Andric static BitcodeErrorCategoryType ErrorCategory; 7750753f127fSDimitry Andric return ErrorCategory; 77510b57cec5SDimitry Andric } 77520b57cec5SDimitry Andric 77530b57cec5SDimitry Andric static Expected<StringRef> readBlobInRecord(BitstreamCursor &Stream, 77540b57cec5SDimitry Andric unsigned Block, unsigned RecordID) { 77550b57cec5SDimitry Andric if (Error Err = Stream.EnterSubBlock(Block)) 77560b57cec5SDimitry Andric return std::move(Err); 77570b57cec5SDimitry Andric 77580b57cec5SDimitry Andric StringRef Strtab; 77590b57cec5SDimitry Andric while (true) { 77600b57cec5SDimitry Andric Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance(); 77610b57cec5SDimitry Andric if (!MaybeEntry) 77620b57cec5SDimitry Andric return MaybeEntry.takeError(); 77630b57cec5SDimitry Andric llvm::BitstreamEntry Entry = MaybeEntry.get(); 77640b57cec5SDimitry Andric 77650b57cec5SDimitry Andric switch (Entry.Kind) { 77660b57cec5SDimitry Andric case BitstreamEntry::EndBlock: 77670b57cec5SDimitry Andric return Strtab; 77680b57cec5SDimitry Andric 77690b57cec5SDimitry Andric case BitstreamEntry::Error: 77700b57cec5SDimitry Andric return error("Malformed block"); 77710b57cec5SDimitry Andric 77720b57cec5SDimitry Andric case BitstreamEntry::SubBlock: 77730b57cec5SDimitry Andric if (Error Err = Stream.SkipBlock()) 77740b57cec5SDimitry Andric return std::move(Err); 77750b57cec5SDimitry Andric break; 77760b57cec5SDimitry Andric 77770b57cec5SDimitry Andric case BitstreamEntry::Record: 77780b57cec5SDimitry Andric StringRef Blob; 77790b57cec5SDimitry Andric SmallVector<uint64_t, 1> Record; 77800b57cec5SDimitry Andric Expected<unsigned> MaybeRecord = 77810b57cec5SDimitry Andric Stream.readRecord(Entry.ID, Record, &Blob); 77820b57cec5SDimitry Andric if (!MaybeRecord) 77830b57cec5SDimitry Andric return MaybeRecord.takeError(); 77840b57cec5SDimitry Andric if (MaybeRecord.get() == RecordID) 77850b57cec5SDimitry Andric Strtab = Blob; 77860b57cec5SDimitry Andric break; 77870b57cec5SDimitry Andric } 77880b57cec5SDimitry Andric } 77890b57cec5SDimitry Andric } 77900b57cec5SDimitry Andric 77910b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 77920b57cec5SDimitry Andric // External interface 77930b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 77940b57cec5SDimitry Andric 77950b57cec5SDimitry Andric Expected<std::vector<BitcodeModule>> 77960b57cec5SDimitry Andric llvm::getBitcodeModuleList(MemoryBufferRef Buffer) { 77970b57cec5SDimitry Andric auto FOrErr = getBitcodeFileContents(Buffer); 77980b57cec5SDimitry Andric if (!FOrErr) 77990b57cec5SDimitry Andric return FOrErr.takeError(); 78000b57cec5SDimitry Andric return std::move(FOrErr->Mods); 78010b57cec5SDimitry Andric } 78020b57cec5SDimitry Andric 78030b57cec5SDimitry Andric Expected<BitcodeFileContents> 78040b57cec5SDimitry Andric llvm::getBitcodeFileContents(MemoryBufferRef Buffer) { 78050b57cec5SDimitry Andric Expected<BitstreamCursor> StreamOrErr = initStream(Buffer); 78060b57cec5SDimitry Andric if (!StreamOrErr) 78070b57cec5SDimitry Andric return StreamOrErr.takeError(); 78080b57cec5SDimitry Andric BitstreamCursor &Stream = *StreamOrErr; 78090b57cec5SDimitry Andric 78100b57cec5SDimitry Andric BitcodeFileContents F; 78110b57cec5SDimitry Andric while (true) { 78120b57cec5SDimitry Andric uint64_t BCBegin = Stream.getCurrentByteNo(); 78130b57cec5SDimitry Andric 78140b57cec5SDimitry Andric // We may be consuming bitcode from a client that leaves garbage at the end 78150b57cec5SDimitry Andric // of the bitcode stream (e.g. Apple's ar tool). If we are close enough to 78160b57cec5SDimitry Andric // the end that there cannot possibly be another module, stop looking. 78170b57cec5SDimitry Andric if (BCBegin + 8 >= Stream.getBitcodeBytes().size()) 78180b57cec5SDimitry Andric return F; 78190b57cec5SDimitry Andric 78200b57cec5SDimitry Andric Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance(); 78210b57cec5SDimitry Andric if (!MaybeEntry) 78220b57cec5SDimitry Andric return MaybeEntry.takeError(); 78230b57cec5SDimitry Andric llvm::BitstreamEntry Entry = MaybeEntry.get(); 78240b57cec5SDimitry Andric 78250b57cec5SDimitry Andric switch (Entry.Kind) { 78260b57cec5SDimitry Andric case BitstreamEntry::EndBlock: 78270b57cec5SDimitry Andric case BitstreamEntry::Error: 78280b57cec5SDimitry Andric return error("Malformed block"); 78290b57cec5SDimitry Andric 78300b57cec5SDimitry Andric case BitstreamEntry::SubBlock: { 78310b57cec5SDimitry Andric uint64_t IdentificationBit = -1ull; 78320b57cec5SDimitry Andric if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) { 78330b57cec5SDimitry Andric IdentificationBit = Stream.GetCurrentBitNo() - BCBegin * 8; 78340b57cec5SDimitry Andric if (Error Err = Stream.SkipBlock()) 78350b57cec5SDimitry Andric return std::move(Err); 78360b57cec5SDimitry Andric 78370b57cec5SDimitry Andric { 78380b57cec5SDimitry Andric Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance(); 78390b57cec5SDimitry Andric if (!MaybeEntry) 78400b57cec5SDimitry Andric return MaybeEntry.takeError(); 78410b57cec5SDimitry Andric Entry = MaybeEntry.get(); 78420b57cec5SDimitry Andric } 78430b57cec5SDimitry Andric 78440b57cec5SDimitry Andric if (Entry.Kind != BitstreamEntry::SubBlock || 78450b57cec5SDimitry Andric Entry.ID != bitc::MODULE_BLOCK_ID) 78460b57cec5SDimitry Andric return error("Malformed block"); 78470b57cec5SDimitry Andric } 78480b57cec5SDimitry Andric 78490b57cec5SDimitry Andric if (Entry.ID == bitc::MODULE_BLOCK_ID) { 78500b57cec5SDimitry Andric uint64_t ModuleBit = Stream.GetCurrentBitNo() - BCBegin * 8; 78510b57cec5SDimitry Andric if (Error Err = Stream.SkipBlock()) 78520b57cec5SDimitry Andric return std::move(Err); 78530b57cec5SDimitry Andric 78540b57cec5SDimitry Andric F.Mods.push_back({Stream.getBitcodeBytes().slice( 78550b57cec5SDimitry Andric BCBegin, Stream.getCurrentByteNo() - BCBegin), 78560b57cec5SDimitry Andric Buffer.getBufferIdentifier(), IdentificationBit, 78570b57cec5SDimitry Andric ModuleBit}); 78580b57cec5SDimitry Andric continue; 78590b57cec5SDimitry Andric } 78600b57cec5SDimitry Andric 78610b57cec5SDimitry Andric if (Entry.ID == bitc::STRTAB_BLOCK_ID) { 78620b57cec5SDimitry Andric Expected<StringRef> Strtab = 78630b57cec5SDimitry Andric readBlobInRecord(Stream, bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB); 78640b57cec5SDimitry Andric if (!Strtab) 78650b57cec5SDimitry Andric return Strtab.takeError(); 78660b57cec5SDimitry Andric // This string table is used by every preceding bitcode module that does 78670b57cec5SDimitry Andric // not have its own string table. A bitcode file may have multiple 78680b57cec5SDimitry Andric // string tables if it was created by binary concatenation, for example 78690b57cec5SDimitry Andric // with "llvm-cat -b". 78700eae32dcSDimitry Andric for (BitcodeModule &I : llvm::reverse(F.Mods)) { 78710eae32dcSDimitry Andric if (!I.Strtab.empty()) 78720b57cec5SDimitry Andric break; 78730eae32dcSDimitry Andric I.Strtab = *Strtab; 78740b57cec5SDimitry Andric } 78750b57cec5SDimitry Andric // Similarly, the string table is used by every preceding symbol table; 78760b57cec5SDimitry Andric // normally there will be just one unless the bitcode file was created 78770b57cec5SDimitry Andric // by binary concatenation. 78780b57cec5SDimitry Andric if (!F.Symtab.empty() && F.StrtabForSymtab.empty()) 78790b57cec5SDimitry Andric F.StrtabForSymtab = *Strtab; 78800b57cec5SDimitry Andric continue; 78810b57cec5SDimitry Andric } 78820b57cec5SDimitry Andric 78830b57cec5SDimitry Andric if (Entry.ID == bitc::SYMTAB_BLOCK_ID) { 78840b57cec5SDimitry Andric Expected<StringRef> SymtabOrErr = 78850b57cec5SDimitry Andric readBlobInRecord(Stream, bitc::SYMTAB_BLOCK_ID, bitc::SYMTAB_BLOB); 78860b57cec5SDimitry Andric if (!SymtabOrErr) 78870b57cec5SDimitry Andric return SymtabOrErr.takeError(); 78880b57cec5SDimitry Andric 78890b57cec5SDimitry Andric // We can expect the bitcode file to have multiple symbol tables if it 78900b57cec5SDimitry Andric // was created by binary concatenation. In that case we silently 78910b57cec5SDimitry Andric // ignore any subsequent symbol tables, which is fine because this is a 78920b57cec5SDimitry Andric // low level function. The client is expected to notice that the number 78930b57cec5SDimitry Andric // of modules in the symbol table does not match the number of modules 78940b57cec5SDimitry Andric // in the input file and regenerate the symbol table. 78950b57cec5SDimitry Andric if (F.Symtab.empty()) 78960b57cec5SDimitry Andric F.Symtab = *SymtabOrErr; 78970b57cec5SDimitry Andric continue; 78980b57cec5SDimitry Andric } 78990b57cec5SDimitry Andric 79000b57cec5SDimitry Andric if (Error Err = Stream.SkipBlock()) 79010b57cec5SDimitry Andric return std::move(Err); 79020b57cec5SDimitry Andric continue; 79030b57cec5SDimitry Andric } 79040b57cec5SDimitry Andric case BitstreamEntry::Record: 7905349cc55cSDimitry Andric if (Error E = Stream.skipRecord(Entry.ID).takeError()) 7906349cc55cSDimitry Andric return std::move(E); 79070b57cec5SDimitry Andric continue; 79080b57cec5SDimitry Andric } 79090b57cec5SDimitry Andric } 79100b57cec5SDimitry Andric } 79110b57cec5SDimitry Andric 79120b57cec5SDimitry Andric /// Get a lazy one-at-time loading module from bitcode. 79130b57cec5SDimitry Andric /// 79140b57cec5SDimitry Andric /// This isn't always used in a lazy context. In particular, it's also used by 79150b57cec5SDimitry Andric /// \a parseModule(). If this is truly lazy, then we need to eagerly pull 79160b57cec5SDimitry Andric /// in forward-referenced functions from block address references. 79170b57cec5SDimitry Andric /// 79180b57cec5SDimitry Andric /// \param[in] MaterializeAll Set to \c true if we should materialize 79190b57cec5SDimitry Andric /// everything. 79200b57cec5SDimitry Andric Expected<std::unique_ptr<Module>> 79210b57cec5SDimitry Andric BitcodeModule::getModuleImpl(LLVMContext &Context, bool MaterializeAll, 79225ffd83dbSDimitry Andric bool ShouldLazyLoadMetadata, bool IsImporting, 7923bdd1243dSDimitry Andric ParserCallbacks Callbacks) { 79240b57cec5SDimitry Andric BitstreamCursor Stream(Buffer); 79250b57cec5SDimitry Andric 79260b57cec5SDimitry Andric std::string ProducerIdentification; 79270b57cec5SDimitry Andric if (IdentificationBit != -1ull) { 79280b57cec5SDimitry Andric if (Error JumpFailed = Stream.JumpToBit(IdentificationBit)) 79290b57cec5SDimitry Andric return std::move(JumpFailed); 7930349cc55cSDimitry Andric if (Error E = 7931349cc55cSDimitry Andric readIdentificationBlock(Stream).moveInto(ProducerIdentification)) 7932349cc55cSDimitry Andric return std::move(E); 79330b57cec5SDimitry Andric } 79340b57cec5SDimitry Andric 79350b57cec5SDimitry Andric if (Error JumpFailed = Stream.JumpToBit(ModuleBit)) 79360b57cec5SDimitry Andric return std::move(JumpFailed); 79370b57cec5SDimitry Andric auto *R = new BitcodeReader(std::move(Stream), Strtab, ProducerIdentification, 79380b57cec5SDimitry Andric Context); 79390b57cec5SDimitry Andric 79400b57cec5SDimitry Andric std::unique_ptr<Module> M = 79418bcb0991SDimitry Andric std::make_unique<Module>(ModuleIdentifier, Context); 79420b57cec5SDimitry Andric M->setMaterializer(R); 79430b57cec5SDimitry Andric 79440b57cec5SDimitry Andric // Delay parsing Metadata if ShouldLazyLoadMetadata is true. 79455ffd83dbSDimitry Andric if (Error Err = R->parseBitcodeInto(M.get(), ShouldLazyLoadMetadata, 7946bdd1243dSDimitry Andric IsImporting, Callbacks)) 79470b57cec5SDimitry Andric return std::move(Err); 79480b57cec5SDimitry Andric 79490b57cec5SDimitry Andric if (MaterializeAll) { 79500b57cec5SDimitry Andric // Read in the entire module, and destroy the BitcodeReader. 79510b57cec5SDimitry Andric if (Error Err = M->materializeAll()) 79520b57cec5SDimitry Andric return std::move(Err); 79530b57cec5SDimitry Andric } else { 79540b57cec5SDimitry Andric // Resolve forward references from blockaddresses. 79550b57cec5SDimitry Andric if (Error Err = R->materializeForwardReferencedFunctions()) 79560b57cec5SDimitry Andric return std::move(Err); 79570b57cec5SDimitry Andric } 79580b57cec5SDimitry Andric return std::move(M); 79590b57cec5SDimitry Andric } 79600b57cec5SDimitry Andric 79610b57cec5SDimitry Andric Expected<std::unique_ptr<Module>> 79620b57cec5SDimitry Andric BitcodeModule::getLazyModule(LLVMContext &Context, bool ShouldLazyLoadMetadata, 7963bdd1243dSDimitry Andric bool IsImporting, ParserCallbacks Callbacks) { 79645ffd83dbSDimitry Andric return getModuleImpl(Context, false, ShouldLazyLoadMetadata, IsImporting, 7965bdd1243dSDimitry Andric Callbacks); 79660b57cec5SDimitry Andric } 79670b57cec5SDimitry Andric 79680b57cec5SDimitry Andric // Parse the specified bitcode buffer and merge the index into CombinedIndex. 79690b57cec5SDimitry Andric // We don't use ModuleIdentifier here because the client may need to control the 79700b57cec5SDimitry Andric // module path used in the combined summary (e.g. when reading summaries for 79710b57cec5SDimitry Andric // regular LTO modules). 7972bdd1243dSDimitry Andric Error BitcodeModule::readSummary( 7973bdd1243dSDimitry Andric ModuleSummaryIndex &CombinedIndex, StringRef ModulePath, uint64_t ModuleId, 7974bdd1243dSDimitry Andric std::function<bool(GlobalValue::GUID)> IsPrevailing) { 79750b57cec5SDimitry Andric BitstreamCursor Stream(Buffer); 79760b57cec5SDimitry Andric if (Error JumpFailed = Stream.JumpToBit(ModuleBit)) 79770b57cec5SDimitry Andric return JumpFailed; 79780b57cec5SDimitry Andric 79790b57cec5SDimitry Andric ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, CombinedIndex, 7980bdd1243dSDimitry Andric ModulePath, ModuleId, IsPrevailing); 79810b57cec5SDimitry Andric return R.parseModule(); 79820b57cec5SDimitry Andric } 79830b57cec5SDimitry Andric 79840b57cec5SDimitry Andric // Parse the specified bitcode buffer, returning the function info index. 79850b57cec5SDimitry Andric Expected<std::unique_ptr<ModuleSummaryIndex>> BitcodeModule::getSummary() { 79860b57cec5SDimitry Andric BitstreamCursor Stream(Buffer); 79870b57cec5SDimitry Andric if (Error JumpFailed = Stream.JumpToBit(ModuleBit)) 79880b57cec5SDimitry Andric return std::move(JumpFailed); 79890b57cec5SDimitry Andric 79908bcb0991SDimitry Andric auto Index = std::make_unique<ModuleSummaryIndex>(/*HaveGVs=*/false); 79910b57cec5SDimitry Andric ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, *Index, 79920b57cec5SDimitry Andric ModuleIdentifier, 0); 79930b57cec5SDimitry Andric 79940b57cec5SDimitry Andric if (Error Err = R.parseModule()) 79950b57cec5SDimitry Andric return std::move(Err); 79960b57cec5SDimitry Andric 79970b57cec5SDimitry Andric return std::move(Index); 79980b57cec5SDimitry Andric } 79990b57cec5SDimitry Andric 8000*fe013be4SDimitry Andric static Expected<std::pair<bool, bool>> 8001*fe013be4SDimitry Andric getEnableSplitLTOUnitAndUnifiedFlag(BitstreamCursor &Stream, 8002*fe013be4SDimitry Andric unsigned ID, 8003*fe013be4SDimitry Andric BitcodeLTOInfo <OInfo) { 80040b57cec5SDimitry Andric if (Error Err = Stream.EnterSubBlock(ID)) 80050b57cec5SDimitry Andric return std::move(Err); 80060b57cec5SDimitry Andric SmallVector<uint64_t, 64> Record; 80070b57cec5SDimitry Andric 80080b57cec5SDimitry Andric while (true) { 8009349cc55cSDimitry Andric BitstreamEntry Entry; 8010*fe013be4SDimitry Andric std::pair<bool, bool> Result = {false,false}; 8011349cc55cSDimitry Andric if (Error E = Stream.advanceSkippingSubblocks().moveInto(Entry)) 8012349cc55cSDimitry Andric return std::move(E); 80130b57cec5SDimitry Andric 80140b57cec5SDimitry Andric switch (Entry.Kind) { 80150b57cec5SDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already. 80160b57cec5SDimitry Andric case BitstreamEntry::Error: 80170b57cec5SDimitry Andric return error("Malformed block"); 8018*fe013be4SDimitry Andric case BitstreamEntry::EndBlock: { 8019*fe013be4SDimitry Andric // If no flags record found, set both flags to false. 8020*fe013be4SDimitry Andric return Result; 8021*fe013be4SDimitry Andric } 80220b57cec5SDimitry Andric case BitstreamEntry::Record: 80230b57cec5SDimitry Andric // The interesting case. 80240b57cec5SDimitry Andric break; 80250b57cec5SDimitry Andric } 80260b57cec5SDimitry Andric 80270b57cec5SDimitry Andric // Look for the FS_FLAGS record. 80280b57cec5SDimitry Andric Record.clear(); 80290b57cec5SDimitry Andric Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record); 80300b57cec5SDimitry Andric if (!MaybeBitCode) 80310b57cec5SDimitry Andric return MaybeBitCode.takeError(); 80320b57cec5SDimitry Andric switch (MaybeBitCode.get()) { 80330b57cec5SDimitry Andric default: // Default behavior: ignore. 80340b57cec5SDimitry Andric break; 80350b57cec5SDimitry Andric case bitc::FS_FLAGS: { // [flags] 80360b57cec5SDimitry Andric uint64_t Flags = Record[0]; 80370b57cec5SDimitry Andric // Scan flags. 8038*fe013be4SDimitry Andric assert(Flags <= 0x2ff && "Unexpected bits in flag"); 80390b57cec5SDimitry Andric 8040*fe013be4SDimitry Andric bool EnableSplitLTOUnit = Flags & 0x8; 8041*fe013be4SDimitry Andric bool UnifiedLTO = Flags & 0x200; 8042*fe013be4SDimitry Andric Result = {EnableSplitLTOUnit, UnifiedLTO}; 8043*fe013be4SDimitry Andric 8044*fe013be4SDimitry Andric return Result; 80450b57cec5SDimitry Andric } 80460b57cec5SDimitry Andric } 80470b57cec5SDimitry Andric } 80480b57cec5SDimitry Andric llvm_unreachable("Exit infinite loop"); 80490b57cec5SDimitry Andric } 80500b57cec5SDimitry Andric 80510b57cec5SDimitry Andric // Check if the given bitcode buffer contains a global value summary block. 80520b57cec5SDimitry Andric Expected<BitcodeLTOInfo> BitcodeModule::getLTOInfo() { 80530b57cec5SDimitry Andric BitstreamCursor Stream(Buffer); 80540b57cec5SDimitry Andric if (Error JumpFailed = Stream.JumpToBit(ModuleBit)) 80550b57cec5SDimitry Andric return std::move(JumpFailed); 80560b57cec5SDimitry Andric 80570b57cec5SDimitry Andric if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID)) 80580b57cec5SDimitry Andric return std::move(Err); 80590b57cec5SDimitry Andric 80600b57cec5SDimitry Andric while (true) { 8061349cc55cSDimitry Andric llvm::BitstreamEntry Entry; 8062349cc55cSDimitry Andric if (Error E = Stream.advance().moveInto(Entry)) 8063349cc55cSDimitry Andric return std::move(E); 80640b57cec5SDimitry Andric 80650b57cec5SDimitry Andric switch (Entry.Kind) { 80660b57cec5SDimitry Andric case BitstreamEntry::Error: 80670b57cec5SDimitry Andric return error("Malformed block"); 80680b57cec5SDimitry Andric case BitstreamEntry::EndBlock: 80690b57cec5SDimitry Andric return BitcodeLTOInfo{/*IsThinLTO=*/false, /*HasSummary=*/false, 8070*fe013be4SDimitry Andric /*EnableSplitLTOUnit=*/false, /*UnifiedLTO=*/false}; 80710b57cec5SDimitry Andric 80720b57cec5SDimitry Andric case BitstreamEntry::SubBlock: 80730b57cec5SDimitry Andric if (Entry.ID == bitc::GLOBALVAL_SUMMARY_BLOCK_ID) { 8074*fe013be4SDimitry Andric BitcodeLTOInfo LTOInfo; 8075*fe013be4SDimitry Andric Expected<std::pair<bool, bool>> Flags = 8076*fe013be4SDimitry Andric getEnableSplitLTOUnitAndUnifiedFlag(Stream, Entry.ID, LTOInfo); 8077*fe013be4SDimitry Andric if (!Flags) 8078*fe013be4SDimitry Andric return Flags.takeError(); 8079*fe013be4SDimitry Andric std::tie(LTOInfo.EnableSplitLTOUnit, LTOInfo.UnifiedLTO) = Flags.get(); 8080*fe013be4SDimitry Andric LTOInfo.IsThinLTO = true; 8081*fe013be4SDimitry Andric LTOInfo.HasSummary = true; 8082*fe013be4SDimitry Andric return LTOInfo; 80830b57cec5SDimitry Andric } 80840b57cec5SDimitry Andric 80850b57cec5SDimitry Andric if (Entry.ID == bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID) { 8086*fe013be4SDimitry Andric BitcodeLTOInfo LTOInfo; 8087*fe013be4SDimitry Andric Expected<std::pair<bool, bool>> Flags = 8088*fe013be4SDimitry Andric getEnableSplitLTOUnitAndUnifiedFlag(Stream, Entry.ID, LTOInfo); 8089*fe013be4SDimitry Andric if (!Flags) 8090*fe013be4SDimitry Andric return Flags.takeError(); 8091*fe013be4SDimitry Andric std::tie(LTOInfo.EnableSplitLTOUnit, LTOInfo.UnifiedLTO) = Flags.get(); 8092*fe013be4SDimitry Andric LTOInfo.IsThinLTO = false; 8093*fe013be4SDimitry Andric LTOInfo.HasSummary = true; 8094*fe013be4SDimitry Andric return LTOInfo; 80950b57cec5SDimitry Andric } 80960b57cec5SDimitry Andric 80970b57cec5SDimitry Andric // Ignore other sub-blocks. 80980b57cec5SDimitry Andric if (Error Err = Stream.SkipBlock()) 80990b57cec5SDimitry Andric return std::move(Err); 81000b57cec5SDimitry Andric continue; 81010b57cec5SDimitry Andric 81020b57cec5SDimitry Andric case BitstreamEntry::Record: 81030b57cec5SDimitry Andric if (Expected<unsigned> StreamFailed = Stream.skipRecord(Entry.ID)) 81040b57cec5SDimitry Andric continue; 81050b57cec5SDimitry Andric else 81060b57cec5SDimitry Andric return StreamFailed.takeError(); 81070b57cec5SDimitry Andric } 81080b57cec5SDimitry Andric } 81090b57cec5SDimitry Andric } 81100b57cec5SDimitry Andric 81110b57cec5SDimitry Andric static Expected<BitcodeModule> getSingleModule(MemoryBufferRef Buffer) { 81120b57cec5SDimitry Andric Expected<std::vector<BitcodeModule>> MsOrErr = getBitcodeModuleList(Buffer); 81130b57cec5SDimitry Andric if (!MsOrErr) 81140b57cec5SDimitry Andric return MsOrErr.takeError(); 81150b57cec5SDimitry Andric 81160b57cec5SDimitry Andric if (MsOrErr->size() != 1) 81170b57cec5SDimitry Andric return error("Expected a single module"); 81180b57cec5SDimitry Andric 81190b57cec5SDimitry Andric return (*MsOrErr)[0]; 81200b57cec5SDimitry Andric } 81210b57cec5SDimitry Andric 81220b57cec5SDimitry Andric Expected<std::unique_ptr<Module>> 81230b57cec5SDimitry Andric llvm::getLazyBitcodeModule(MemoryBufferRef Buffer, LLVMContext &Context, 8124bdd1243dSDimitry Andric bool ShouldLazyLoadMetadata, bool IsImporting, 8125bdd1243dSDimitry Andric ParserCallbacks Callbacks) { 81260b57cec5SDimitry Andric Expected<BitcodeModule> BM = getSingleModule(Buffer); 81270b57cec5SDimitry Andric if (!BM) 81280b57cec5SDimitry Andric return BM.takeError(); 81290b57cec5SDimitry Andric 8130bdd1243dSDimitry Andric return BM->getLazyModule(Context, ShouldLazyLoadMetadata, IsImporting, 8131bdd1243dSDimitry Andric Callbacks); 81320b57cec5SDimitry Andric } 81330b57cec5SDimitry Andric 81340b57cec5SDimitry Andric Expected<std::unique_ptr<Module>> llvm::getOwningLazyBitcodeModule( 81350b57cec5SDimitry Andric std::unique_ptr<MemoryBuffer> &&Buffer, LLVMContext &Context, 8136bdd1243dSDimitry Andric bool ShouldLazyLoadMetadata, bool IsImporting, ParserCallbacks Callbacks) { 81370b57cec5SDimitry Andric auto MOrErr = getLazyBitcodeModule(*Buffer, Context, ShouldLazyLoadMetadata, 8138bdd1243dSDimitry Andric IsImporting, Callbacks); 81390b57cec5SDimitry Andric if (MOrErr) 81400b57cec5SDimitry Andric (*MOrErr)->setOwnedMemoryBuffer(std::move(Buffer)); 81410b57cec5SDimitry Andric return MOrErr; 81420b57cec5SDimitry Andric } 81430b57cec5SDimitry Andric 81440b57cec5SDimitry Andric Expected<std::unique_ptr<Module>> 8145bdd1243dSDimitry Andric BitcodeModule::parseModule(LLVMContext &Context, ParserCallbacks Callbacks) { 8146bdd1243dSDimitry Andric return getModuleImpl(Context, true, false, false, Callbacks); 81470b57cec5SDimitry Andric // TODO: Restore the use-lists to the in-memory state when the bitcode was 81480b57cec5SDimitry Andric // written. We must defer until the Module has been fully materialized. 81490b57cec5SDimitry Andric } 81500b57cec5SDimitry Andric 81515ffd83dbSDimitry Andric Expected<std::unique_ptr<Module>> 81525ffd83dbSDimitry Andric llvm::parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context, 8153bdd1243dSDimitry Andric ParserCallbacks Callbacks) { 81540b57cec5SDimitry Andric Expected<BitcodeModule> BM = getSingleModule(Buffer); 81550b57cec5SDimitry Andric if (!BM) 81560b57cec5SDimitry Andric return BM.takeError(); 81570b57cec5SDimitry Andric 8158bdd1243dSDimitry Andric return BM->parseModule(Context, Callbacks); 81590b57cec5SDimitry Andric } 81600b57cec5SDimitry Andric 81610b57cec5SDimitry Andric Expected<std::string> llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer) { 81620b57cec5SDimitry Andric Expected<BitstreamCursor> StreamOrErr = initStream(Buffer); 81630b57cec5SDimitry Andric if (!StreamOrErr) 81640b57cec5SDimitry Andric return StreamOrErr.takeError(); 81650b57cec5SDimitry Andric 81660b57cec5SDimitry Andric return readTriple(*StreamOrErr); 81670b57cec5SDimitry Andric } 81680b57cec5SDimitry Andric 81690b57cec5SDimitry Andric Expected<bool> llvm::isBitcodeContainingObjCCategory(MemoryBufferRef Buffer) { 81700b57cec5SDimitry Andric Expected<BitstreamCursor> StreamOrErr = initStream(Buffer); 81710b57cec5SDimitry Andric if (!StreamOrErr) 81720b57cec5SDimitry Andric return StreamOrErr.takeError(); 81730b57cec5SDimitry Andric 81740b57cec5SDimitry Andric return hasObjCCategory(*StreamOrErr); 81750b57cec5SDimitry Andric } 81760b57cec5SDimitry Andric 81770b57cec5SDimitry Andric Expected<std::string> llvm::getBitcodeProducerString(MemoryBufferRef Buffer) { 81780b57cec5SDimitry Andric Expected<BitstreamCursor> StreamOrErr = initStream(Buffer); 81790b57cec5SDimitry Andric if (!StreamOrErr) 81800b57cec5SDimitry Andric return StreamOrErr.takeError(); 81810b57cec5SDimitry Andric 81820b57cec5SDimitry Andric return readIdentificationCode(*StreamOrErr); 81830b57cec5SDimitry Andric } 81840b57cec5SDimitry Andric 81850b57cec5SDimitry Andric Error llvm::readModuleSummaryIndex(MemoryBufferRef Buffer, 81860b57cec5SDimitry Andric ModuleSummaryIndex &CombinedIndex, 81870b57cec5SDimitry Andric uint64_t ModuleId) { 81880b57cec5SDimitry Andric Expected<BitcodeModule> BM = getSingleModule(Buffer); 81890b57cec5SDimitry Andric if (!BM) 81900b57cec5SDimitry Andric return BM.takeError(); 81910b57cec5SDimitry Andric 81920b57cec5SDimitry Andric return BM->readSummary(CombinedIndex, BM->getModuleIdentifier(), ModuleId); 81930b57cec5SDimitry Andric } 81940b57cec5SDimitry Andric 81950b57cec5SDimitry Andric Expected<std::unique_ptr<ModuleSummaryIndex>> 81960b57cec5SDimitry Andric llvm::getModuleSummaryIndex(MemoryBufferRef Buffer) { 81970b57cec5SDimitry Andric Expected<BitcodeModule> BM = getSingleModule(Buffer); 81980b57cec5SDimitry Andric if (!BM) 81990b57cec5SDimitry Andric return BM.takeError(); 82000b57cec5SDimitry Andric 82010b57cec5SDimitry Andric return BM->getSummary(); 82020b57cec5SDimitry Andric } 82030b57cec5SDimitry Andric 82040b57cec5SDimitry Andric Expected<BitcodeLTOInfo> llvm::getBitcodeLTOInfo(MemoryBufferRef Buffer) { 82050b57cec5SDimitry Andric Expected<BitcodeModule> BM = getSingleModule(Buffer); 82060b57cec5SDimitry Andric if (!BM) 82070b57cec5SDimitry Andric return BM.takeError(); 82080b57cec5SDimitry Andric 82090b57cec5SDimitry Andric return BM->getLTOInfo(); 82100b57cec5SDimitry Andric } 82110b57cec5SDimitry Andric 82120b57cec5SDimitry Andric Expected<std::unique_ptr<ModuleSummaryIndex>> 82130b57cec5SDimitry Andric llvm::getModuleSummaryIndexForFile(StringRef Path, 82140b57cec5SDimitry Andric bool IgnoreEmptyThinLTOIndexFile) { 82150b57cec5SDimitry Andric ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr = 82160b57cec5SDimitry Andric MemoryBuffer::getFileOrSTDIN(Path); 82170b57cec5SDimitry Andric if (!FileOrErr) 82180b57cec5SDimitry Andric return errorCodeToError(FileOrErr.getError()); 82190b57cec5SDimitry Andric if (IgnoreEmptyThinLTOIndexFile && !(*FileOrErr)->getBufferSize()) 82200b57cec5SDimitry Andric return nullptr; 82210b57cec5SDimitry Andric return getModuleSummaryIndex(**FileOrErr); 82220b57cec5SDimitry Andric } 8223