1f22ef01cSRoman Divacky //===- BitcodeReader.cpp - Internal BitcodeReader implementation ----------===// 2f22ef01cSRoman Divacky // 3f22ef01cSRoman Divacky // The LLVM Compiler Infrastructure 4f22ef01cSRoman Divacky // 5f22ef01cSRoman Divacky // This file is distributed under the University of Illinois Open Source 6f22ef01cSRoman Divacky // License. See LICENSE.TXT for details. 7f22ef01cSRoman Divacky // 8f22ef01cSRoman Divacky //===----------------------------------------------------------------------===// 9f22ef01cSRoman Divacky 10d88c1a5aSDimitry Andric #include "llvm/Bitcode/BitcodeReader.h" 11d88c1a5aSDimitry Andric #include "MetadataLoader.h" 12d88c1a5aSDimitry Andric #include "ValueList.h" 13d88c1a5aSDimitry Andric 14d88c1a5aSDimitry Andric #include "llvm/ADT/APFloat.h" 15d88c1a5aSDimitry Andric #include "llvm/ADT/APInt.h" 16d88c1a5aSDimitry Andric #include "llvm/ADT/ArrayRef.h" 17d88c1a5aSDimitry Andric #include "llvm/ADT/DenseMap.h" 18d88c1a5aSDimitry Andric #include "llvm/ADT/None.h" 19ff0cc061SDimitry Andric #include "llvm/ADT/STLExtras.h" 20f22ef01cSRoman Divacky #include "llvm/ADT/SmallString.h" 21f22ef01cSRoman Divacky #include "llvm/ADT/SmallVector.h" 22d88c1a5aSDimitry Andric #include "llvm/ADT/StringRef.h" 23ff0cc061SDimitry Andric #include "llvm/ADT/Triple.h" 24d88c1a5aSDimitry Andric #include "llvm/ADT/Twine.h" 25ff0cc061SDimitry Andric #include "llvm/Bitcode/BitstreamReader.h" 26f785676fSDimitry Andric #include "llvm/Bitcode/LLVMBitCodes.h" 27d88c1a5aSDimitry Andric #include "llvm/IR/Argument.h" 28d88c1a5aSDimitry Andric #include "llvm/IR/Attributes.h" 2991bc56edSDimitry Andric #include "llvm/IR/AutoUpgrade.h" 30d88c1a5aSDimitry Andric #include "llvm/IR/BasicBlock.h" 313ca95b02SDimitry Andric #include "llvm/IR/CallSite.h" 32db17bf38SDimitry Andric #include "llvm/IR/CallingConv.h" 33d88c1a5aSDimitry Andric #include "llvm/IR/Comdat.h" 34d88c1a5aSDimitry Andric #include "llvm/IR/Constant.h" 35139f7f9bSDimitry Andric #include "llvm/IR/Constants.h" 36ff0cc061SDimitry Andric #include "llvm/IR/DebugInfo.h" 37ff0cc061SDimitry Andric #include "llvm/IR/DebugInfoMetadata.h" 38d88c1a5aSDimitry Andric #include "llvm/IR/DebugLoc.h" 39139f7f9bSDimitry Andric #include "llvm/IR/DerivedTypes.h" 40d88c1a5aSDimitry Andric #include "llvm/IR/DiagnosticInfo.h" 4139d628a0SDimitry Andric #include "llvm/IR/DiagnosticPrinter.h" 42d88c1a5aSDimitry Andric #include "llvm/IR/Function.h" 43db17bf38SDimitry Andric #include "llvm/IR/GVMaterializer.h" 44d88c1a5aSDimitry Andric #include "llvm/IR/GlobalAlias.h" 45d88c1a5aSDimitry Andric #include "llvm/IR/GlobalIFunc.h" 46d88c1a5aSDimitry Andric #include "llvm/IR/GlobalIndirectSymbol.h" 47d88c1a5aSDimitry Andric #include "llvm/IR/GlobalObject.h" 48d88c1a5aSDimitry Andric #include "llvm/IR/GlobalValue.h" 49d88c1a5aSDimitry Andric #include "llvm/IR/GlobalVariable.h" 50139f7f9bSDimitry Andric #include "llvm/IR/InlineAsm.h" 51d88c1a5aSDimitry Andric #include "llvm/IR/InstIterator.h" 52d88c1a5aSDimitry Andric #include "llvm/IR/InstrTypes.h" 53d88c1a5aSDimitry Andric #include "llvm/IR/Instruction.h" 54d88c1a5aSDimitry Andric #include "llvm/IR/Instructions.h" 55d88c1a5aSDimitry Andric #include "llvm/IR/Intrinsics.h" 56f785676fSDimitry Andric #include "llvm/IR/LLVMContext.h" 57139f7f9bSDimitry Andric #include "llvm/IR/Module.h" 583ca95b02SDimitry Andric #include "llvm/IR/ModuleSummaryIndex.h" 59139f7f9bSDimitry Andric #include "llvm/IR/OperandTraits.h" 60139f7f9bSDimitry Andric #include "llvm/IR/Operator.h" 61d88c1a5aSDimitry Andric #include "llvm/IR/TrackingMDRef.h" 62d88c1a5aSDimitry Andric #include "llvm/IR/Type.h" 63ff0cc061SDimitry Andric #include "llvm/IR/ValueHandle.h" 64d88c1a5aSDimitry Andric #include "llvm/IR/Verifier.h" 65d88c1a5aSDimitry Andric #include "llvm/Support/AtomicOrdering.h" 66d88c1a5aSDimitry Andric #include "llvm/Support/Casting.h" 673ca95b02SDimitry Andric #include "llvm/Support/CommandLine.h" 68d88c1a5aSDimitry Andric #include "llvm/Support/Compiler.h" 693ca95b02SDimitry Andric #include "llvm/Support/Debug.h" 70d88c1a5aSDimitry Andric #include "llvm/Support/Error.h" 71d88c1a5aSDimitry Andric #include "llvm/Support/ErrorHandling.h" 7239d628a0SDimitry Andric #include "llvm/Support/ManagedStatic.h" 73f22ef01cSRoman Divacky #include "llvm/Support/MemoryBuffer.h" 74f785676fSDimitry Andric #include "llvm/Support/raw_ostream.h" 75d88c1a5aSDimitry Andric #include <algorithm> 76d88c1a5aSDimitry Andric #include <cassert> 77d88c1a5aSDimitry Andric #include <cstddef> 78d88c1a5aSDimitry Andric #include <cstdint> 79ff0cc061SDimitry Andric #include <deque> 80d88c1a5aSDimitry Andric #include <limits> 81d88c1a5aSDimitry Andric #include <map> 82d88c1a5aSDimitry Andric #include <memory> 83d88c1a5aSDimitry Andric #include <string> 84d88c1a5aSDimitry Andric #include <system_error> 85d88c1a5aSDimitry Andric #include <tuple> 863ca95b02SDimitry Andric #include <utility> 87d88c1a5aSDimitry Andric #include <vector> 883ca95b02SDimitry Andric 89f22ef01cSRoman Divacky using namespace llvm; 90f22ef01cSRoman Divacky 913ca95b02SDimitry Andric static cl::opt<bool> PrintSummaryGUIDs( 923ca95b02SDimitry Andric "print-summary-global-ids", cl::init(false), cl::Hidden, 933ca95b02SDimitry Andric cl::desc( 943ca95b02SDimitry Andric "Print the global id for each value when reading the module summary")); 953ca95b02SDimitry Andric 96ff0cc061SDimitry Andric namespace { 97d88c1a5aSDimitry Andric 987ae0e2c9SDimitry Andric enum { 997ae0e2c9SDimitry Andric SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex 1007ae0e2c9SDimitry Andric }; 1017ae0e2c9SDimitry Andric 102d88c1a5aSDimitry Andric Error error(const Twine &Message) { 103d88c1a5aSDimitry Andric return make_error<StringError>( 104d88c1a5aSDimitry Andric Message, make_error_code(BitcodeError::CorruptedBitcode)); 105ff0cc061SDimitry Andric } 106ff0cc061SDimitry Andric 107d88c1a5aSDimitry Andric /// Helper to read the header common to all bitcode files. 108d88c1a5aSDimitry Andric bool hasValidBitcodeHeader(BitstreamCursor &Stream) { 109d88c1a5aSDimitry Andric // Sniff for the signature. 110d88c1a5aSDimitry Andric if (!Stream.canSkipToPos(4) || 111d88c1a5aSDimitry Andric Stream.Read(8) != 'B' || 112d88c1a5aSDimitry Andric Stream.Read(8) != 'C' || 113d88c1a5aSDimitry Andric Stream.Read(4) != 0x0 || 114d88c1a5aSDimitry Andric Stream.Read(4) != 0xC || 115d88c1a5aSDimitry Andric Stream.Read(4) != 0xE || 116d88c1a5aSDimitry Andric Stream.Read(4) != 0xD) 117d88c1a5aSDimitry Andric return false; 118d88c1a5aSDimitry Andric return true; 119ff0cc061SDimitry Andric } 120ff0cc061SDimitry Andric 121d88c1a5aSDimitry Andric Expected<BitstreamCursor> initStream(MemoryBufferRef Buffer) { 122d88c1a5aSDimitry Andric const unsigned char *BufPtr = (const unsigned char *)Buffer.getBufferStart(); 123d88c1a5aSDimitry Andric const unsigned char *BufEnd = BufPtr + Buffer.getBufferSize(); 124d88c1a5aSDimitry Andric 125d88c1a5aSDimitry Andric if (Buffer.getBufferSize() & 3) 126d88c1a5aSDimitry Andric return error("Invalid bitcode signature"); 127d88c1a5aSDimitry Andric 128d88c1a5aSDimitry Andric // If we have a wrapper header, parse it and ignore the non-bc file contents. 129d88c1a5aSDimitry Andric // The magic number is 0x0B17C0DE stored in little endian. 130d88c1a5aSDimitry Andric if (isBitcodeWrapper(BufPtr, BufEnd)) 131d88c1a5aSDimitry Andric if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true)) 132d88c1a5aSDimitry Andric return error("Invalid bitcode wrapper header"); 133d88c1a5aSDimitry Andric 134d88c1a5aSDimitry Andric BitstreamCursor Stream(ArrayRef<uint8_t>(BufPtr, BufEnd)); 135d88c1a5aSDimitry Andric if (!hasValidBitcodeHeader(Stream)) 136d88c1a5aSDimitry Andric return error("Invalid bitcode signature"); 137d88c1a5aSDimitry Andric 138d88c1a5aSDimitry Andric return std::move(Stream); 139ff0cc061SDimitry Andric } 140ff0cc061SDimitry Andric 141d88c1a5aSDimitry Andric /// Convert a string from a record into an std::string, return true on failure. 142d88c1a5aSDimitry Andric template <typename StrTy> 143d88c1a5aSDimitry Andric static bool convertToString(ArrayRef<uint64_t> Record, unsigned Idx, 144d88c1a5aSDimitry Andric StrTy &Result) { 145d88c1a5aSDimitry Andric if (Idx > Record.size()) 146d88c1a5aSDimitry Andric return true; 147d88c1a5aSDimitry Andric 148d88c1a5aSDimitry Andric for (unsigned i = Idx, e = Record.size(); i != e; ++i) 149d88c1a5aSDimitry Andric Result += (char)Record[i]; 150d88c1a5aSDimitry Andric return false; 151ff0cc061SDimitry Andric } 152ff0cc061SDimitry Andric 153d88c1a5aSDimitry Andric // Strip all the TBAA attachment for the module. 154d88c1a5aSDimitry Andric void stripTBAA(Module *M) { 155d88c1a5aSDimitry Andric for (auto &F : *M) { 156d88c1a5aSDimitry Andric if (F.isMaterializable()) 157d88c1a5aSDimitry Andric continue; 158d88c1a5aSDimitry Andric for (auto &I : instructions(F)) 159d88c1a5aSDimitry Andric I.setMetadata(LLVMContext::MD_tbaa, nullptr); 160d88c1a5aSDimitry Andric } 161d88c1a5aSDimitry Andric } 162ff0cc061SDimitry Andric 163d88c1a5aSDimitry Andric /// Read the "IDENTIFICATION_BLOCK_ID" block, do some basic enforcement on the 164d88c1a5aSDimitry Andric /// "epoch" encoded in the bitcode, and return the producer name if any. 165d88c1a5aSDimitry Andric Expected<std::string> readIdentificationBlock(BitstreamCursor &Stream) { 166d88c1a5aSDimitry Andric if (Stream.EnterSubBlock(bitc::IDENTIFICATION_BLOCK_ID)) 167d88c1a5aSDimitry Andric return error("Invalid record"); 168ff0cc061SDimitry Andric 169d88c1a5aSDimitry Andric // Read all the records. 170d88c1a5aSDimitry Andric SmallVector<uint64_t, 64> Record; 171d88c1a5aSDimitry Andric 172d88c1a5aSDimitry Andric std::string ProducerIdentification; 173d88c1a5aSDimitry Andric 174d88c1a5aSDimitry Andric while (true) { 175d88c1a5aSDimitry Andric BitstreamEntry Entry = Stream.advance(); 176d88c1a5aSDimitry Andric 177d88c1a5aSDimitry Andric switch (Entry.Kind) { 178d88c1a5aSDimitry Andric default: 179d88c1a5aSDimitry Andric case BitstreamEntry::Error: 180d88c1a5aSDimitry Andric return error("Malformed block"); 181d88c1a5aSDimitry Andric case BitstreamEntry::EndBlock: 182d88c1a5aSDimitry Andric return ProducerIdentification; 183d88c1a5aSDimitry Andric case BitstreamEntry::Record: 184d88c1a5aSDimitry Andric // The interesting case. 185d88c1a5aSDimitry Andric break; 186d88c1a5aSDimitry Andric } 187d88c1a5aSDimitry Andric 188d88c1a5aSDimitry Andric // Read a record. 189d88c1a5aSDimitry Andric Record.clear(); 190d88c1a5aSDimitry Andric unsigned BitCode = Stream.readRecord(Entry.ID, Record); 191d88c1a5aSDimitry Andric switch (BitCode) { 192d88c1a5aSDimitry Andric default: // Default behavior: reject 193d88c1a5aSDimitry Andric return error("Invalid value"); 194d88c1a5aSDimitry Andric case bitc::IDENTIFICATION_CODE_STRING: // IDENTIFICATION: [strchr x N] 195d88c1a5aSDimitry Andric convertToString(Record, 0, ProducerIdentification); 196d88c1a5aSDimitry Andric break; 197d88c1a5aSDimitry Andric case bitc::IDENTIFICATION_CODE_EPOCH: { // EPOCH: [epoch#] 198d88c1a5aSDimitry Andric unsigned epoch = (unsigned)Record[0]; 199d88c1a5aSDimitry Andric if (epoch != bitc::BITCODE_CURRENT_EPOCH) { 200d88c1a5aSDimitry Andric return error( 201d88c1a5aSDimitry Andric Twine("Incompatible epoch: Bitcode '") + Twine(epoch) + 202d88c1a5aSDimitry Andric "' vs current: '" + Twine(bitc::BITCODE_CURRENT_EPOCH) + "'"); 203d88c1a5aSDimitry Andric } 204d88c1a5aSDimitry Andric } 205d88c1a5aSDimitry Andric } 206d88c1a5aSDimitry Andric } 207d88c1a5aSDimitry Andric } 208d88c1a5aSDimitry Andric 209d88c1a5aSDimitry Andric Expected<std::string> readIdentificationCode(BitstreamCursor &Stream) { 210d88c1a5aSDimitry Andric // We expect a number of well-defined blocks, though we don't necessarily 211d88c1a5aSDimitry Andric // need to understand them all. 212d88c1a5aSDimitry Andric while (true) { 213d88c1a5aSDimitry Andric if (Stream.AtEndOfStream()) 214d88c1a5aSDimitry Andric return ""; 215d88c1a5aSDimitry Andric 216d88c1a5aSDimitry Andric BitstreamEntry Entry = Stream.advance(); 217d88c1a5aSDimitry Andric switch (Entry.Kind) { 218d88c1a5aSDimitry Andric case BitstreamEntry::EndBlock: 219d88c1a5aSDimitry Andric case BitstreamEntry::Error: 220d88c1a5aSDimitry Andric return error("Malformed block"); 221d88c1a5aSDimitry Andric 222d88c1a5aSDimitry Andric case BitstreamEntry::SubBlock: 223d88c1a5aSDimitry Andric if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) 224d88c1a5aSDimitry Andric return readIdentificationBlock(Stream); 225d88c1a5aSDimitry Andric 226d88c1a5aSDimitry Andric // Ignore other sub-blocks. 227d88c1a5aSDimitry Andric if (Stream.SkipBlock()) 228d88c1a5aSDimitry Andric return error("Malformed block"); 229d88c1a5aSDimitry Andric continue; 230d88c1a5aSDimitry Andric case BitstreamEntry::Record: 231d88c1a5aSDimitry Andric Stream.skipRecord(Entry.ID); 232d88c1a5aSDimitry Andric continue; 233d88c1a5aSDimitry Andric } 234d88c1a5aSDimitry Andric } 235d88c1a5aSDimitry Andric } 236d88c1a5aSDimitry Andric 237d88c1a5aSDimitry Andric Expected<bool> hasObjCCategoryInModule(BitstreamCursor &Stream) { 238d88c1a5aSDimitry Andric if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID)) 239d88c1a5aSDimitry Andric return error("Invalid record"); 240d88c1a5aSDimitry Andric 241d88c1a5aSDimitry Andric SmallVector<uint64_t, 64> Record; 242d88c1a5aSDimitry Andric // Read all the records for this module. 243d88c1a5aSDimitry Andric 244d88c1a5aSDimitry Andric while (true) { 245d88c1a5aSDimitry Andric BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 246d88c1a5aSDimitry Andric 247d88c1a5aSDimitry Andric switch (Entry.Kind) { 248d88c1a5aSDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already. 249d88c1a5aSDimitry Andric case BitstreamEntry::Error: 250d88c1a5aSDimitry Andric return error("Malformed block"); 251d88c1a5aSDimitry Andric case BitstreamEntry::EndBlock: 252d88c1a5aSDimitry Andric return false; 253d88c1a5aSDimitry Andric case BitstreamEntry::Record: 254d88c1a5aSDimitry Andric // The interesting case. 255d88c1a5aSDimitry Andric break; 256d88c1a5aSDimitry Andric } 257d88c1a5aSDimitry Andric 258d88c1a5aSDimitry Andric // Read a record. 259d88c1a5aSDimitry Andric switch (Stream.readRecord(Entry.ID, Record)) { 260d88c1a5aSDimitry Andric default: 261d88c1a5aSDimitry Andric break; // Default behavior, ignore unknown content. 262d88c1a5aSDimitry Andric case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N] 263d88c1a5aSDimitry Andric std::string S; 264d88c1a5aSDimitry Andric if (convertToString(Record, 0, S)) 265d88c1a5aSDimitry Andric return error("Invalid record"); 266d88c1a5aSDimitry Andric // Check for the i386 and other (x86_64, ARM) conventions 267d88c1a5aSDimitry Andric if (S.find("__DATA, __objc_catlist") != std::string::npos || 268d88c1a5aSDimitry Andric S.find("__OBJC,__category") != std::string::npos) 269d88c1a5aSDimitry Andric return true; 270d88c1a5aSDimitry Andric break; 271d88c1a5aSDimitry Andric } 272d88c1a5aSDimitry Andric } 273d88c1a5aSDimitry Andric Record.clear(); 274d88c1a5aSDimitry Andric } 275d88c1a5aSDimitry Andric llvm_unreachable("Exit infinite loop"); 276d88c1a5aSDimitry Andric } 277d88c1a5aSDimitry Andric 278d88c1a5aSDimitry Andric Expected<bool> hasObjCCategory(BitstreamCursor &Stream) { 279d88c1a5aSDimitry Andric // We expect a number of well-defined blocks, though we don't necessarily 280d88c1a5aSDimitry Andric // need to understand them all. 281d88c1a5aSDimitry Andric while (true) { 282d88c1a5aSDimitry Andric BitstreamEntry Entry = Stream.advance(); 283d88c1a5aSDimitry Andric 284d88c1a5aSDimitry Andric switch (Entry.Kind) { 285d88c1a5aSDimitry Andric case BitstreamEntry::Error: 286d88c1a5aSDimitry Andric return error("Malformed block"); 287d88c1a5aSDimitry Andric case BitstreamEntry::EndBlock: 288d88c1a5aSDimitry Andric return false; 289d88c1a5aSDimitry Andric 290d88c1a5aSDimitry Andric case BitstreamEntry::SubBlock: 291d88c1a5aSDimitry Andric if (Entry.ID == bitc::MODULE_BLOCK_ID) 292d88c1a5aSDimitry Andric return hasObjCCategoryInModule(Stream); 293d88c1a5aSDimitry Andric 294d88c1a5aSDimitry Andric // Ignore other sub-blocks. 295d88c1a5aSDimitry Andric if (Stream.SkipBlock()) 296d88c1a5aSDimitry Andric return error("Malformed block"); 297d88c1a5aSDimitry Andric continue; 298d88c1a5aSDimitry Andric 299d88c1a5aSDimitry Andric case BitstreamEntry::Record: 300d88c1a5aSDimitry Andric Stream.skipRecord(Entry.ID); 301d88c1a5aSDimitry Andric continue; 302d88c1a5aSDimitry Andric } 303d88c1a5aSDimitry Andric } 304d88c1a5aSDimitry Andric } 305d88c1a5aSDimitry Andric 306d88c1a5aSDimitry Andric Expected<std::string> readModuleTriple(BitstreamCursor &Stream) { 307d88c1a5aSDimitry Andric if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID)) 308d88c1a5aSDimitry Andric return error("Invalid record"); 309d88c1a5aSDimitry Andric 310d88c1a5aSDimitry Andric SmallVector<uint64_t, 64> Record; 311d88c1a5aSDimitry Andric 312d88c1a5aSDimitry Andric std::string Triple; 313d88c1a5aSDimitry Andric 314d88c1a5aSDimitry Andric // Read all the records for this module. 315d88c1a5aSDimitry Andric while (true) { 316d88c1a5aSDimitry Andric BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 317d88c1a5aSDimitry Andric 318d88c1a5aSDimitry Andric switch (Entry.Kind) { 319d88c1a5aSDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already. 320d88c1a5aSDimitry Andric case BitstreamEntry::Error: 321d88c1a5aSDimitry Andric return error("Malformed block"); 322d88c1a5aSDimitry Andric case BitstreamEntry::EndBlock: 323d88c1a5aSDimitry Andric return Triple; 324d88c1a5aSDimitry Andric case BitstreamEntry::Record: 325d88c1a5aSDimitry Andric // The interesting case. 326d88c1a5aSDimitry Andric break; 327d88c1a5aSDimitry Andric } 328d88c1a5aSDimitry Andric 329d88c1a5aSDimitry Andric // Read a record. 330d88c1a5aSDimitry Andric switch (Stream.readRecord(Entry.ID, Record)) { 331d88c1a5aSDimitry Andric default: break; // Default behavior, ignore unknown content. 332d88c1a5aSDimitry Andric case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N] 333d88c1a5aSDimitry Andric std::string S; 334d88c1a5aSDimitry Andric if (convertToString(Record, 0, S)) 335d88c1a5aSDimitry Andric return error("Invalid record"); 336d88c1a5aSDimitry Andric Triple = S; 337d88c1a5aSDimitry Andric break; 338d88c1a5aSDimitry Andric } 339d88c1a5aSDimitry Andric } 340d88c1a5aSDimitry Andric Record.clear(); 341d88c1a5aSDimitry Andric } 342d88c1a5aSDimitry Andric llvm_unreachable("Exit infinite loop"); 343d88c1a5aSDimitry Andric } 344d88c1a5aSDimitry Andric 345d88c1a5aSDimitry Andric Expected<std::string> readTriple(BitstreamCursor &Stream) { 346d88c1a5aSDimitry Andric // We expect a number of well-defined blocks, though we don't necessarily 347d88c1a5aSDimitry Andric // need to understand them all. 348d88c1a5aSDimitry Andric while (true) { 349d88c1a5aSDimitry Andric BitstreamEntry Entry = Stream.advance(); 350d88c1a5aSDimitry Andric 351d88c1a5aSDimitry Andric switch (Entry.Kind) { 352d88c1a5aSDimitry Andric case BitstreamEntry::Error: 353d88c1a5aSDimitry Andric return error("Malformed block"); 354d88c1a5aSDimitry Andric case BitstreamEntry::EndBlock: 355d88c1a5aSDimitry Andric return ""; 356d88c1a5aSDimitry Andric 357d88c1a5aSDimitry Andric case BitstreamEntry::SubBlock: 358d88c1a5aSDimitry Andric if (Entry.ID == bitc::MODULE_BLOCK_ID) 359d88c1a5aSDimitry Andric return readModuleTriple(Stream); 360d88c1a5aSDimitry Andric 361d88c1a5aSDimitry Andric // Ignore other sub-blocks. 362d88c1a5aSDimitry Andric if (Stream.SkipBlock()) 363d88c1a5aSDimitry Andric return error("Malformed block"); 364d88c1a5aSDimitry Andric continue; 365d88c1a5aSDimitry Andric 366d88c1a5aSDimitry Andric case BitstreamEntry::Record: 367d88c1a5aSDimitry Andric Stream.skipRecord(Entry.ID); 368d88c1a5aSDimitry Andric continue; 369d88c1a5aSDimitry Andric } 370d88c1a5aSDimitry Andric } 371d88c1a5aSDimitry Andric } 372d88c1a5aSDimitry Andric 373d88c1a5aSDimitry Andric class BitcodeReaderBase { 374d88c1a5aSDimitry Andric protected: 3756bc11b14SDimitry Andric BitcodeReaderBase(BitstreamCursor Stream, StringRef Strtab) 3766bc11b14SDimitry Andric : Stream(std::move(Stream)), Strtab(Strtab) { 377d88c1a5aSDimitry Andric this->Stream.setBlockInfo(&BlockInfo); 378d88c1a5aSDimitry Andric } 379d88c1a5aSDimitry Andric 380d88c1a5aSDimitry Andric BitstreamBlockInfo BlockInfo; 381d88c1a5aSDimitry Andric BitstreamCursor Stream; 3826bc11b14SDimitry Andric StringRef Strtab; 3836bc11b14SDimitry Andric 3846bc11b14SDimitry Andric /// In version 2 of the bitcode we store names of global values and comdats in 3856bc11b14SDimitry Andric /// a string table rather than in the VST. 3866bc11b14SDimitry Andric bool UseStrtab = false; 387d88c1a5aSDimitry Andric 3887a7e6055SDimitry Andric Expected<unsigned> parseVersionRecord(ArrayRef<uint64_t> Record); 3897a7e6055SDimitry Andric 3906bc11b14SDimitry Andric /// If this module uses a string table, pop the reference to the string table 3916bc11b14SDimitry Andric /// and return the referenced string and the rest of the record. Otherwise 3926bc11b14SDimitry Andric /// just return the record itself. 3936bc11b14SDimitry Andric std::pair<StringRef, ArrayRef<uint64_t>> 3946bc11b14SDimitry Andric readNameFromStrtab(ArrayRef<uint64_t> Record); 3956bc11b14SDimitry Andric 396d88c1a5aSDimitry Andric bool readBlockInfo(); 397d88c1a5aSDimitry Andric 398d88c1a5aSDimitry Andric // Contains an arbitrary and optional string identifying the bitcode producer 399d88c1a5aSDimitry Andric std::string ProducerIdentification; 400d88c1a5aSDimitry Andric 401d88c1a5aSDimitry Andric Error error(const Twine &Message); 402ff0cc061SDimitry Andric }; 403ff0cc061SDimitry Andric 404d88c1a5aSDimitry Andric Error BitcodeReaderBase::error(const Twine &Message) { 405d88c1a5aSDimitry Andric std::string FullMsg = Message.str(); 406d88c1a5aSDimitry Andric if (!ProducerIdentification.empty()) 407d88c1a5aSDimitry Andric FullMsg += " (Producer: '" + ProducerIdentification + "' Reader: 'LLVM " + 408d88c1a5aSDimitry Andric LLVM_VERSION_STRING "')"; 409d88c1a5aSDimitry Andric return ::error(FullMsg); 410ff0cc061SDimitry Andric } 411ff0cc061SDimitry Andric 4127a7e6055SDimitry Andric Expected<unsigned> 4137a7e6055SDimitry Andric BitcodeReaderBase::parseVersionRecord(ArrayRef<uint64_t> Record) { 4147a7e6055SDimitry Andric if (Record.size() < 1) 4157a7e6055SDimitry Andric return error("Invalid record"); 4167a7e6055SDimitry Andric unsigned ModuleVersion = Record[0]; 4176bc11b14SDimitry Andric if (ModuleVersion > 2) 4187a7e6055SDimitry Andric return error("Invalid value"); 4196bc11b14SDimitry Andric UseStrtab = ModuleVersion >= 2; 4207a7e6055SDimitry Andric return ModuleVersion; 4217a7e6055SDimitry Andric } 4227a7e6055SDimitry Andric 4236bc11b14SDimitry Andric std::pair<StringRef, ArrayRef<uint64_t>> 4246bc11b14SDimitry Andric BitcodeReaderBase::readNameFromStrtab(ArrayRef<uint64_t> Record) { 4256bc11b14SDimitry Andric if (!UseStrtab) 4266bc11b14SDimitry Andric return {"", Record}; 4276bc11b14SDimitry Andric // Invalid reference. Let the caller complain about the record being empty. 4286bc11b14SDimitry Andric if (Record[0] + Record[1] > Strtab.size()) 4296bc11b14SDimitry Andric return {"", {}}; 4306bc11b14SDimitry Andric return {StringRef(Strtab.data() + Record[0], Record[1]), Record.slice(2)}; 4316bc11b14SDimitry Andric } 4326bc11b14SDimitry Andric 433d88c1a5aSDimitry Andric class BitcodeReader : public BitcodeReaderBase, public GVMaterializer { 434ff0cc061SDimitry Andric LLVMContext &Context; 4358f0fd8f6SDimitry Andric Module *TheModule = nullptr; 4367d523365SDimitry Andric // Next offset to start scanning for lazy parsing of function bodies. 4378f0fd8f6SDimitry Andric uint64_t NextUnreadBit = 0; 4387d523365SDimitry Andric // Last function offset found in the VST. 4397d523365SDimitry Andric uint64_t LastFunctionBlockBit = 0; 4408f0fd8f6SDimitry Andric bool SeenValueSymbolTable = false; 4417d523365SDimitry Andric uint64_t VSTOffset = 0; 442ff0cc061SDimitry Andric 4437a7e6055SDimitry Andric std::vector<std::string> SectionTable; 4447a7e6055SDimitry Andric std::vector<std::string> GCTable; 4457a7e6055SDimitry Andric 446ff0cc061SDimitry Andric std::vector<Type*> TypeList; 447ff0cc061SDimitry Andric BitcodeReaderValueList ValueList; 448d88c1a5aSDimitry Andric Optional<MetadataLoader> MDLoader; 449ff0cc061SDimitry Andric std::vector<Comdat *> ComdatList; 450ff0cc061SDimitry Andric SmallVector<Instruction *, 64> InstructionList; 451ff0cc061SDimitry Andric 452ff0cc061SDimitry Andric std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInits; 4533ca95b02SDimitry Andric std::vector<std::pair<GlobalIndirectSymbol*, unsigned> > IndirectSymbolInits; 454ff0cc061SDimitry Andric std::vector<std::pair<Function*, unsigned> > FunctionPrefixes; 455ff0cc061SDimitry Andric std::vector<std::pair<Function*, unsigned> > FunctionPrologues; 4568f0fd8f6SDimitry Andric std::vector<std::pair<Function*, unsigned> > FunctionPersonalityFns; 457ff0cc061SDimitry Andric 4588f0fd8f6SDimitry Andric /// The set of attributes by index. Index zero in the file is for null, and 4598f0fd8f6SDimitry Andric /// is thus not represented here. As such all indices are off by one. 4607a7e6055SDimitry Andric std::vector<AttributeList> MAttributes; 461ff0cc061SDimitry Andric 4627d523365SDimitry Andric /// The set of attribute groups. 4637a7e6055SDimitry Andric std::map<unsigned, AttributeList> MAttributeGroups; 464ff0cc061SDimitry Andric 4658f0fd8f6SDimitry Andric /// While parsing a function body, this is a list of the basic blocks for the 4668f0fd8f6SDimitry Andric /// function. 467ff0cc061SDimitry Andric std::vector<BasicBlock*> FunctionBBs; 468ff0cc061SDimitry Andric 469ff0cc061SDimitry Andric // When reading the module header, this list is populated with functions that 470ff0cc061SDimitry Andric // have bodies later in the file. 471ff0cc061SDimitry Andric std::vector<Function*> FunctionsWithBodies; 472ff0cc061SDimitry Andric 473ff0cc061SDimitry Andric // When intrinsic functions are encountered which require upgrading they are 474ff0cc061SDimitry Andric // stored here with their replacement function. 4753ca95b02SDimitry Andric typedef DenseMap<Function*, Function*> UpdatedIntrinsicMap; 4763ca95b02SDimitry Andric UpdatedIntrinsicMap UpgradedIntrinsics; 4773ca95b02SDimitry Andric // Intrinsics which were remangled because of types rename 4783ca95b02SDimitry Andric UpdatedIntrinsicMap RemangledIntrinsics; 479ff0cc061SDimitry Andric 480ff0cc061SDimitry Andric // Several operations happen after the module header has been read, but 481ff0cc061SDimitry Andric // before function bodies are processed. This keeps track of whether 482ff0cc061SDimitry Andric // we've done this yet. 4838f0fd8f6SDimitry Andric bool SeenFirstFunctionBody = false; 484ff0cc061SDimitry Andric 4858f0fd8f6SDimitry Andric /// When function bodies are initially scanned, this map contains info about 4868f0fd8f6SDimitry Andric /// where to find deferred function body in the stream. 487ff0cc061SDimitry Andric DenseMap<Function*, uint64_t> DeferredFunctionInfo; 488ff0cc061SDimitry Andric 489ff0cc061SDimitry Andric /// When Metadata block is initially scanned when parsing the module, we may 490ff0cc061SDimitry Andric /// choose to defer parsing of the metadata. This vector contains info about 491ff0cc061SDimitry Andric /// which Metadata blocks are deferred. 492ff0cc061SDimitry Andric std::vector<uint64_t> DeferredMetadataInfo; 493ff0cc061SDimitry Andric 494ff0cc061SDimitry Andric /// These are basic blocks forward-referenced by block addresses. They are 495ff0cc061SDimitry Andric /// inserted lazily into functions when they're loaded. The basic block ID is 496ff0cc061SDimitry Andric /// its index into the vector. 497ff0cc061SDimitry Andric DenseMap<Function *, std::vector<BasicBlock *>> BasicBlockFwdRefs; 498ff0cc061SDimitry Andric std::deque<Function *> BasicBlockFwdRefQueue; 499ff0cc061SDimitry Andric 5008f0fd8f6SDimitry Andric /// Indicates that we are using a new encoding for instruction operands where 5018f0fd8f6SDimitry Andric /// most operands in the current FUNCTION_BLOCK are encoded relative to the 5028f0fd8f6SDimitry Andric /// instruction number, for a more compact encoding. Some instruction 5038f0fd8f6SDimitry Andric /// operands are not relative to the instruction ID: basic block numbers, and 5048f0fd8f6SDimitry Andric /// types. Once the old style function blocks have been phased out, we would 505ff0cc061SDimitry Andric /// not need this flag. 5068f0fd8f6SDimitry Andric bool UseRelativeIDs = false; 507ff0cc061SDimitry Andric 508ff0cc061SDimitry Andric /// True if all functions will be materialized, negating the need to process 509ff0cc061SDimitry Andric /// (e.g.) blockaddress forward references. 5108f0fd8f6SDimitry Andric bool WillMaterializeAllForwardRefs = false; 511ff0cc061SDimitry Andric 512ff0cc061SDimitry Andric bool StripDebugInfo = false; 513d88c1a5aSDimitry Andric TBAAVerifier TBAAVerifyHelper; 5147d523365SDimitry Andric 5157d523365SDimitry Andric std::vector<std::string> BundleTags; 516c4394386SDimitry Andric SmallVector<SyncScope::ID, 8> SSIDs; 5177d523365SDimitry Andric 518ff0cc061SDimitry Andric public: 5196bc11b14SDimitry Andric BitcodeReader(BitstreamCursor Stream, StringRef Strtab, 5206bc11b14SDimitry Andric StringRef ProducerIdentification, LLVMContext &Context); 521ff0cc061SDimitry Andric 522d88c1a5aSDimitry Andric Error materializeForwardReferencedFunctions(); 523ff0cc061SDimitry Andric 524d88c1a5aSDimitry Andric Error materialize(GlobalValue *GV) override; 525d88c1a5aSDimitry Andric Error materializeModule() override; 526ff0cc061SDimitry Andric std::vector<StructType *> getIdentifiedStructTypes() const override; 527ff0cc061SDimitry Andric 5288f0fd8f6SDimitry Andric /// \brief Main interface to parsing a bitcode buffer. 5298f0fd8f6SDimitry Andric /// \returns true if an error occurred. 530d88c1a5aSDimitry Andric Error parseBitcodeInto(Module *M, bool ShouldLazyLoadMetadata = false, 531d88c1a5aSDimitry Andric bool IsImporting = false); 5323ca95b02SDimitry Andric 533ff0cc061SDimitry Andric static uint64_t decodeSignRotatedValue(uint64_t V); 534ff0cc061SDimitry Andric 535ff0cc061SDimitry Andric /// Materialize any deferred Metadata block. 536d88c1a5aSDimitry Andric Error materializeMetadata() override; 537ff0cc061SDimitry Andric 538ff0cc061SDimitry Andric void setStripDebugInfo() override; 539ff0cc061SDimitry Andric 540ff0cc061SDimitry Andric private: 541ff0cc061SDimitry Andric std::vector<StructType *> IdentifiedStructTypes; 542ff0cc061SDimitry Andric StructType *createIdentifiedStructType(LLVMContext &Context, StringRef Name); 543ff0cc061SDimitry Andric StructType *createIdentifiedStructType(LLVMContext &Context); 544ff0cc061SDimitry Andric 545ff0cc061SDimitry Andric Type *getTypeByID(unsigned ID); 546d88c1a5aSDimitry Andric 547ff0cc061SDimitry Andric Value *getFnValueByID(unsigned ID, Type *Ty) { 548ff0cc061SDimitry Andric if (Ty && Ty->isMetadataTy()) 549ff0cc061SDimitry Andric return MetadataAsValue::get(Ty->getContext(), getFnMetadataByID(ID)); 550ff0cc061SDimitry Andric return ValueList.getValueFwdRef(ID, Ty); 551ff0cc061SDimitry Andric } 552d88c1a5aSDimitry Andric 553ff0cc061SDimitry Andric Metadata *getFnMetadataByID(unsigned ID) { 554f8496407SDimitry Andric return MDLoader->getMetadataFwdRefOrLoad(ID); 555ff0cc061SDimitry Andric } 556d88c1a5aSDimitry Andric 557ff0cc061SDimitry Andric BasicBlock *getBasicBlock(unsigned ID) const { 558ff0cc061SDimitry Andric if (ID >= FunctionBBs.size()) return nullptr; // Invalid ID 559ff0cc061SDimitry Andric return FunctionBBs[ID]; 560ff0cc061SDimitry Andric } 561d88c1a5aSDimitry Andric 5627a7e6055SDimitry Andric AttributeList getAttributes(unsigned i) const { 563ff0cc061SDimitry Andric if (i-1 < MAttributes.size()) 564ff0cc061SDimitry Andric return MAttributes[i-1]; 5657a7e6055SDimitry Andric return AttributeList(); 566ff0cc061SDimitry Andric } 567ff0cc061SDimitry Andric 5688f0fd8f6SDimitry Andric /// Read a value/type pair out of the specified record from slot 'Slot'. 5698f0fd8f6SDimitry Andric /// Increment Slot past the number of slots used in the record. Return true on 5708f0fd8f6SDimitry Andric /// failure. 571ff0cc061SDimitry Andric bool getValueTypePair(SmallVectorImpl<uint64_t> &Record, unsigned &Slot, 572ff0cc061SDimitry Andric unsigned InstNum, Value *&ResVal) { 573ff0cc061SDimitry Andric if (Slot == Record.size()) return true; 574ff0cc061SDimitry Andric unsigned ValNo = (unsigned)Record[Slot++]; 575ff0cc061SDimitry Andric // Adjust the ValNo, if it was encoded relative to the InstNum. 576ff0cc061SDimitry Andric if (UseRelativeIDs) 577ff0cc061SDimitry Andric ValNo = InstNum - ValNo; 578ff0cc061SDimitry Andric if (ValNo < InstNum) { 579ff0cc061SDimitry Andric // If this is not a forward reference, just return the value we already 580ff0cc061SDimitry Andric // have. 581ff0cc061SDimitry Andric ResVal = getFnValueByID(ValNo, nullptr); 582ff0cc061SDimitry Andric return ResVal == nullptr; 583ff0cc061SDimitry Andric } 584ff0cc061SDimitry Andric if (Slot == Record.size()) 585ff0cc061SDimitry Andric return true; 586ff0cc061SDimitry Andric 587ff0cc061SDimitry Andric unsigned TypeNo = (unsigned)Record[Slot++]; 588ff0cc061SDimitry Andric ResVal = getFnValueByID(ValNo, getTypeByID(TypeNo)); 589ff0cc061SDimitry Andric return ResVal == nullptr; 590ff0cc061SDimitry Andric } 591ff0cc061SDimitry Andric 5928f0fd8f6SDimitry Andric /// Read a value out of the specified record from slot 'Slot'. Increment Slot 5938f0fd8f6SDimitry Andric /// past the number of slots used by the value in the record. Return true if 5948f0fd8f6SDimitry Andric /// there is an error. 595ff0cc061SDimitry Andric bool popValue(SmallVectorImpl<uint64_t> &Record, unsigned &Slot, 596ff0cc061SDimitry Andric unsigned InstNum, Type *Ty, Value *&ResVal) { 597ff0cc061SDimitry Andric if (getValue(Record, Slot, InstNum, Ty, ResVal)) 598ff0cc061SDimitry Andric return true; 599ff0cc061SDimitry Andric // All values currently take a single record slot. 600ff0cc061SDimitry Andric ++Slot; 601ff0cc061SDimitry Andric return false; 602ff0cc061SDimitry Andric } 603ff0cc061SDimitry Andric 6048f0fd8f6SDimitry Andric /// Like popValue, but does not increment the Slot number. 605ff0cc061SDimitry Andric bool getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot, 606ff0cc061SDimitry Andric unsigned InstNum, Type *Ty, Value *&ResVal) { 607ff0cc061SDimitry Andric ResVal = getValue(Record, Slot, InstNum, Ty); 608ff0cc061SDimitry Andric return ResVal == nullptr; 609ff0cc061SDimitry Andric } 610ff0cc061SDimitry Andric 6118f0fd8f6SDimitry Andric /// Version of getValue that returns ResVal directly, or 0 if there is an 6128f0fd8f6SDimitry Andric /// error. 613ff0cc061SDimitry Andric Value *getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot, 614ff0cc061SDimitry Andric unsigned InstNum, Type *Ty) { 615ff0cc061SDimitry Andric if (Slot == Record.size()) return nullptr; 616ff0cc061SDimitry Andric unsigned ValNo = (unsigned)Record[Slot]; 617ff0cc061SDimitry Andric // Adjust the ValNo, if it was encoded relative to the InstNum. 618ff0cc061SDimitry Andric if (UseRelativeIDs) 619ff0cc061SDimitry Andric ValNo = InstNum - ValNo; 620ff0cc061SDimitry Andric return getFnValueByID(ValNo, Ty); 621ff0cc061SDimitry Andric } 622ff0cc061SDimitry Andric 6238f0fd8f6SDimitry Andric /// Like getValue, but decodes signed VBRs. 624ff0cc061SDimitry Andric Value *getValueSigned(SmallVectorImpl<uint64_t> &Record, unsigned Slot, 625ff0cc061SDimitry Andric unsigned InstNum, Type *Ty) { 626ff0cc061SDimitry Andric if (Slot == Record.size()) return nullptr; 627ff0cc061SDimitry Andric unsigned ValNo = (unsigned)decodeSignRotatedValue(Record[Slot]); 628ff0cc061SDimitry Andric // Adjust the ValNo, if it was encoded relative to the InstNum. 629ff0cc061SDimitry Andric if (UseRelativeIDs) 630ff0cc061SDimitry Andric ValNo = InstNum - ValNo; 631ff0cc061SDimitry Andric return getFnValueByID(ValNo, Ty); 632ff0cc061SDimitry Andric } 633ff0cc061SDimitry Andric 634ff0cc061SDimitry Andric /// Converts alignment exponent (i.e. power of two (or zero)) to the 635ff0cc061SDimitry Andric /// corresponding alignment to use. If alignment is too large, returns 636ff0cc061SDimitry Andric /// a corresponding error code. 637d88c1a5aSDimitry Andric Error parseAlignmentValue(uint64_t Exponent, unsigned &Alignment); 638d88c1a5aSDimitry Andric Error parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind); 639d88c1a5aSDimitry Andric Error parseModule(uint64_t ResumeBit, bool ShouldLazyLoadMetadata = false); 6407a7e6055SDimitry Andric 6417a7e6055SDimitry Andric Error parseComdatRecord(ArrayRef<uint64_t> Record); 6427a7e6055SDimitry Andric Error parseGlobalVarRecord(ArrayRef<uint64_t> Record); 6437a7e6055SDimitry Andric Error parseFunctionRecord(ArrayRef<uint64_t> Record); 6447a7e6055SDimitry Andric Error parseGlobalIndirectSymbolRecord(unsigned BitCode, 6457a7e6055SDimitry Andric ArrayRef<uint64_t> Record); 6467a7e6055SDimitry Andric 647d88c1a5aSDimitry Andric Error parseAttributeBlock(); 648d88c1a5aSDimitry Andric Error parseAttributeGroupBlock(); 649d88c1a5aSDimitry Andric Error parseTypeTable(); 650d88c1a5aSDimitry Andric Error parseTypeTableBody(); 651d88c1a5aSDimitry Andric Error parseOperandBundleTags(); 652c4394386SDimitry Andric Error parseSyncScopeNames(); 653ff0cc061SDimitry Andric 654d88c1a5aSDimitry Andric Expected<Value *> recordValue(SmallVectorImpl<uint64_t> &Record, 6557d523365SDimitry Andric unsigned NameIndex, Triple &TT); 6566bc11b14SDimitry Andric void setDeferredFunctionInfo(unsigned FuncBitcodeOffsetDelta, Function *F, 6576bc11b14SDimitry Andric ArrayRef<uint64_t> Record); 658d88c1a5aSDimitry Andric Error parseValueSymbolTable(uint64_t Offset = 0); 6596bc11b14SDimitry Andric Error parseGlobalValueSymbolTable(); 660d88c1a5aSDimitry Andric Error parseConstants(); 661d88c1a5aSDimitry Andric Error rememberAndSkipFunctionBodies(); 662d88c1a5aSDimitry Andric Error rememberAndSkipFunctionBody(); 663ff0cc061SDimitry Andric /// Save the positions of the Metadata blocks and skip parsing the blocks. 664d88c1a5aSDimitry Andric Error rememberAndSkipMetadata(); 665d88c1a5aSDimitry Andric Error typeCheckLoadStoreInst(Type *ValType, Type *PtrType); 666d88c1a5aSDimitry Andric Error parseFunctionBody(Function *F); 667d88c1a5aSDimitry Andric Error globalCleanup(); 668d88c1a5aSDimitry Andric Error resolveGlobalAndIndirectSymbolInits(); 669d88c1a5aSDimitry Andric Error parseUseLists(); 670d88c1a5aSDimitry Andric Error findFunctionInStream( 671ff0cc061SDimitry Andric Function *F, 672ff0cc061SDimitry Andric DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator); 673c4394386SDimitry Andric 674c4394386SDimitry Andric SyncScope::ID getDecodedSyncScopeID(unsigned Val); 675ff0cc061SDimitry Andric }; 6767d523365SDimitry Andric 6777d523365SDimitry Andric /// Class to manage reading and parsing function summary index bitcode 6787d523365SDimitry Andric /// files/sections. 679d88c1a5aSDimitry Andric class ModuleSummaryIndexBitcodeReader : public BitcodeReaderBase { 680d88c1a5aSDimitry Andric /// The module index built during parsing. 681d88c1a5aSDimitry Andric ModuleSummaryIndex &TheIndex; 6827d523365SDimitry Andric 6833ca95b02SDimitry Andric /// Indicates whether we have encountered a global value summary section 684d88c1a5aSDimitry Andric /// yet during parsing. 6853ca95b02SDimitry Andric bool SeenGlobalValSummary = false; 6867d523365SDimitry Andric 6873ca95b02SDimitry Andric /// Indicates whether we have already parsed the VST, used for error checking. 6883ca95b02SDimitry Andric bool SeenValueSymbolTable = false; 6893ca95b02SDimitry Andric 6903ca95b02SDimitry Andric /// Set to the offset of the VST recorded in the MODULE_CODE_VSTOFFSET record. 6913ca95b02SDimitry Andric /// Used to enable on-demand parsing of the VST. 6923ca95b02SDimitry Andric uint64_t VSTOffset = 0; 6933ca95b02SDimitry Andric 6940f5676f4SDimitry Andric // Map to save ValueId to ValueInfo association that was recorded in the 6953ca95b02SDimitry Andric // ValueSymbolTable. It is used after the VST is parsed to convert 6963ca95b02SDimitry Andric // call graph edges read from the function summary from referencing 6970f5676f4SDimitry Andric // callees by their ValueId to using the ValueInfo instead, which is how 6983ca95b02SDimitry Andric // they are recorded in the summary index being built. 6990f5676f4SDimitry Andric // We save a GUID which refers to the same global as the ValueInfo, but 7000f5676f4SDimitry Andric // ignoring the linkage, i.e. for values other than local linkage they are 7010f5676f4SDimitry Andric // identical. 7020f5676f4SDimitry Andric DenseMap<unsigned, std::pair<ValueInfo, GlobalValue::GUID>> 7030f5676f4SDimitry Andric ValueIdToValueInfoMap; 7047d523365SDimitry Andric 7057d523365SDimitry Andric /// Map populated during module path string table parsing, from the 7067d523365SDimitry Andric /// module ID to a string reference owned by the index's module 7073ca95b02SDimitry Andric /// path string table, used to correlate with combined index 7087d523365SDimitry Andric /// summary records. 7097d523365SDimitry Andric DenseMap<uint64_t, StringRef> ModuleIdMap; 7107d523365SDimitry Andric 7113ca95b02SDimitry Andric /// Original source file name recorded in a bitcode record. 7123ca95b02SDimitry Andric std::string SourceFileName; 7133ca95b02SDimitry Andric 714f37b6182SDimitry Andric /// The string identifier given to this module by the client, normally the 715f37b6182SDimitry Andric /// path to the bitcode file. 716f37b6182SDimitry Andric StringRef ModulePath; 717f37b6182SDimitry Andric 718f37b6182SDimitry Andric /// For per-module summary indexes, the unique numerical identifier given to 719f37b6182SDimitry Andric /// this module by the client. 720f37b6182SDimitry Andric unsigned ModuleId; 721f37b6182SDimitry Andric 7227d523365SDimitry Andric public: 7236bc11b14SDimitry Andric ModuleSummaryIndexBitcodeReader(BitstreamCursor Stream, StringRef Strtab, 724f37b6182SDimitry Andric ModuleSummaryIndex &TheIndex, 725f37b6182SDimitry Andric StringRef ModulePath, unsigned ModuleId); 7267d523365SDimitry Andric 727f37b6182SDimitry Andric Error parseModule(); 7287d523365SDimitry Andric 7297d523365SDimitry Andric private: 7306bc11b14SDimitry Andric void setValueGUID(uint64_t ValueID, StringRef ValueName, 7316bc11b14SDimitry Andric GlobalValue::LinkageTypes Linkage, 7326bc11b14SDimitry Andric StringRef SourceFileName); 733d88c1a5aSDimitry Andric Error parseValueSymbolTable( 7343ca95b02SDimitry Andric uint64_t Offset, 7353ca95b02SDimitry Andric DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap); 736d88c1a5aSDimitry Andric std::vector<ValueInfo> makeRefList(ArrayRef<uint64_t> Record); 737d88c1a5aSDimitry Andric std::vector<FunctionSummary::EdgeTy> makeCallList(ArrayRef<uint64_t> Record, 738d88c1a5aSDimitry Andric bool IsOldProfileFormat, 739d88c1a5aSDimitry Andric bool HasProfile); 74024d58133SDimitry Andric Error parseEntireSummary(unsigned ID); 741d88c1a5aSDimitry Andric Error parseModuleStringTable(); 742d88c1a5aSDimitry Andric 7430f5676f4SDimitry Andric std::pair<ValueInfo, GlobalValue::GUID> 7440f5676f4SDimitry Andric getValueInfoFromValueId(unsigned ValueId); 745f37b6182SDimitry Andric 74624d58133SDimitry Andric ModuleSummaryIndex::ModuleInfo *addThisModule(); 7477d523365SDimitry Andric }; 748d88c1a5aSDimitry Andric 7493ca95b02SDimitry Andric } // end anonymous namespace 750ff0cc061SDimitry Andric 751d88c1a5aSDimitry Andric std::error_code llvm::errorToErrorCodeAndEmitErrors(LLVMContext &Ctx, 752d88c1a5aSDimitry Andric Error Err) { 753d88c1a5aSDimitry Andric if (Err) { 754d88c1a5aSDimitry Andric std::error_code EC; 755d88c1a5aSDimitry Andric handleAllErrors(std::move(Err), [&](ErrorInfoBase &EIB) { 756d88c1a5aSDimitry Andric EC = EIB.convertToErrorCode(); 757d88c1a5aSDimitry Andric Ctx.emitError(EIB.message()); 758d88c1a5aSDimitry Andric }); 75939d628a0SDimitry Andric return EC; 760dff0c46cSDimitry Andric } 76139d628a0SDimitry Andric return std::error_code(); 762d88c1a5aSDimitry Andric } 763d88c1a5aSDimitry Andric 7646bc11b14SDimitry Andric BitcodeReader::BitcodeReader(BitstreamCursor Stream, StringRef Strtab, 765d88c1a5aSDimitry Andric StringRef ProducerIdentification, 766d88c1a5aSDimitry Andric LLVMContext &Context) 7676bc11b14SDimitry Andric : BitcodeReaderBase(std::move(Stream), Strtab), Context(Context), 768d88c1a5aSDimitry Andric ValueList(Context) { 769d88c1a5aSDimitry Andric this->ProducerIdentification = ProducerIdentification; 770d88c1a5aSDimitry Andric } 771d88c1a5aSDimitry Andric 772d88c1a5aSDimitry Andric Error BitcodeReader::materializeForwardReferencedFunctions() { 773d88c1a5aSDimitry Andric if (WillMaterializeAllForwardRefs) 774d88c1a5aSDimitry Andric return Error::success(); 77539d628a0SDimitry Andric 77639d628a0SDimitry Andric // Prevent recursion. 77739d628a0SDimitry Andric WillMaterializeAllForwardRefs = true; 77839d628a0SDimitry Andric 77939d628a0SDimitry Andric while (!BasicBlockFwdRefQueue.empty()) { 78039d628a0SDimitry Andric Function *F = BasicBlockFwdRefQueue.front(); 78139d628a0SDimitry Andric BasicBlockFwdRefQueue.pop_front(); 78239d628a0SDimitry Andric assert(F && "Expected valid function"); 78339d628a0SDimitry Andric if (!BasicBlockFwdRefs.count(F)) 78439d628a0SDimitry Andric // Already materialized. 78539d628a0SDimitry Andric continue; 78639d628a0SDimitry Andric 78739d628a0SDimitry Andric // Check for a function that isn't materializable to prevent an infinite 78839d628a0SDimitry Andric // loop. When parsing a blockaddress stored in a global variable, there 78939d628a0SDimitry Andric // isn't a trivial way to check if a function will have a body without a 79039d628a0SDimitry Andric // linear search through FunctionsWithBodies, so just check it here. 79139d628a0SDimitry Andric if (!F->isMaterializable()) 7928f0fd8f6SDimitry Andric return error("Never resolved function from blockaddress"); 79339d628a0SDimitry Andric 79439d628a0SDimitry Andric // Try to materialize F. 795d88c1a5aSDimitry Andric if (Error Err = materialize(F)) 796d88c1a5aSDimitry Andric return Err; 79739d628a0SDimitry Andric } 79839d628a0SDimitry Andric assert(BasicBlockFwdRefs.empty() && "Function missing from queue"); 79939d628a0SDimitry Andric 80039d628a0SDimitry Andric // Reset state. 80139d628a0SDimitry Andric WillMaterializeAllForwardRefs = false; 802d88c1a5aSDimitry Andric return Error::success(); 803f22ef01cSRoman Divacky } 804f22ef01cSRoman Divacky 805f22ef01cSRoman Divacky //===----------------------------------------------------------------------===// 806f22ef01cSRoman Divacky // Helper functions to implement forward reference resolution, etc. 807f22ef01cSRoman Divacky //===----------------------------------------------------------------------===// 808f22ef01cSRoman Divacky 809ff0cc061SDimitry Andric static bool hasImplicitComdat(size_t Val) { 810ff0cc061SDimitry Andric switch (Val) { 811ff0cc061SDimitry Andric default: 812ff0cc061SDimitry Andric return false; 813ff0cc061SDimitry Andric case 1: // Old WeakAnyLinkage 814ff0cc061SDimitry Andric case 4: // Old LinkOnceAnyLinkage 815ff0cc061SDimitry Andric case 10: // Old WeakODRLinkage 816ff0cc061SDimitry Andric case 11: // Old LinkOnceODRLinkage 817ff0cc061SDimitry Andric return true; 818ff0cc061SDimitry Andric } 819ff0cc061SDimitry Andric } 820ff0cc061SDimitry Andric 82139d628a0SDimitry Andric static GlobalValue::LinkageTypes getDecodedLinkage(unsigned Val) { 822f22ef01cSRoman Divacky switch (Val) { 823f22ef01cSRoman Divacky default: // Map unknown/new linkages to external 82439d628a0SDimitry Andric case 0: 82539d628a0SDimitry Andric return GlobalValue::ExternalLinkage; 82639d628a0SDimitry Andric case 2: 82739d628a0SDimitry Andric return GlobalValue::AppendingLinkage; 82839d628a0SDimitry Andric case 3: 82939d628a0SDimitry Andric return GlobalValue::InternalLinkage; 83039d628a0SDimitry Andric case 5: 83139d628a0SDimitry Andric return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage 83239d628a0SDimitry Andric case 6: 83339d628a0SDimitry Andric return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage 83439d628a0SDimitry Andric case 7: 83539d628a0SDimitry Andric return GlobalValue::ExternalWeakLinkage; 83639d628a0SDimitry Andric case 8: 83739d628a0SDimitry Andric return GlobalValue::CommonLinkage; 83839d628a0SDimitry Andric case 9: 83939d628a0SDimitry Andric return GlobalValue::PrivateLinkage; 84039d628a0SDimitry Andric case 12: 84139d628a0SDimitry Andric return GlobalValue::AvailableExternallyLinkage; 84291bc56edSDimitry Andric case 13: 84391bc56edSDimitry Andric return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage 84491bc56edSDimitry Andric case 14: 84591bc56edSDimitry Andric return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage 84639d628a0SDimitry Andric case 15: 84739d628a0SDimitry Andric return GlobalValue::ExternalLinkage; // Obsolete LinkOnceODRAutoHideLinkage 848ff0cc061SDimitry Andric case 1: // Old value with implicit comdat. 849ff0cc061SDimitry Andric case 16: 850ff0cc061SDimitry Andric return GlobalValue::WeakAnyLinkage; 851ff0cc061SDimitry Andric case 10: // Old value with implicit comdat. 852ff0cc061SDimitry Andric case 17: 853ff0cc061SDimitry Andric return GlobalValue::WeakODRLinkage; 854ff0cc061SDimitry Andric case 4: // Old value with implicit comdat. 855ff0cc061SDimitry Andric case 18: 856ff0cc061SDimitry Andric return GlobalValue::LinkOnceAnyLinkage; 857ff0cc061SDimitry Andric case 11: // Old value with implicit comdat. 858ff0cc061SDimitry Andric case 19: 859ff0cc061SDimitry Andric return GlobalValue::LinkOnceODRLinkage; 860f22ef01cSRoman Divacky } 861f22ef01cSRoman Divacky } 862f22ef01cSRoman Divacky 863d88c1a5aSDimitry Andric /// Decode the flags for GlobalValue in the summary. 8643ca95b02SDimitry Andric static GlobalValueSummary::GVFlags getDecodedGVSummaryFlags(uint64_t RawFlags, 8653ca95b02SDimitry Andric uint64_t Version) { 8663ca95b02SDimitry Andric // Summary were not emitted before LLVM 3.9, we don't need to upgrade Linkage 8673ca95b02SDimitry Andric // like getDecodedLinkage() above. Any future change to the linkage enum and 8683ca95b02SDimitry Andric // to getDecodedLinkage() will need to be taken into account here as above. 8693ca95b02SDimitry Andric auto Linkage = GlobalValue::LinkageTypes(RawFlags & 0xF); // 4 bits 8703ca95b02SDimitry Andric RawFlags = RawFlags >> 4; 87195ec533aSDimitry Andric bool NotEligibleToImport = (RawFlags & 0x1) || Version < 3; 8726d97bb29SDimitry Andric // The Live flag wasn't introduced until version 3. For dead stripping 87395ec533aSDimitry Andric // to work correctly on earlier versions, we must conservatively treat all 87495ec533aSDimitry Andric // values as live. 8756d97bb29SDimitry Andric bool Live = (RawFlags & 0x2) || Version < 3; 8766d97bb29SDimitry Andric return GlobalValueSummary::GVFlags(Linkage, NotEligibleToImport, Live); 8773ca95b02SDimitry Andric } 8783ca95b02SDimitry Andric 8798f0fd8f6SDimitry Andric static GlobalValue::VisibilityTypes getDecodedVisibility(unsigned Val) { 880f22ef01cSRoman Divacky switch (Val) { 881f22ef01cSRoman Divacky default: // Map unknown visibilities to default. 882f22ef01cSRoman Divacky case 0: return GlobalValue::DefaultVisibility; 883f22ef01cSRoman Divacky case 1: return GlobalValue::HiddenVisibility; 884f22ef01cSRoman Divacky case 2: return GlobalValue::ProtectedVisibility; 885f22ef01cSRoman Divacky } 886f22ef01cSRoman Divacky } 887f22ef01cSRoman Divacky 88891bc56edSDimitry Andric static GlobalValue::DLLStorageClassTypes 8898f0fd8f6SDimitry Andric getDecodedDLLStorageClass(unsigned Val) { 89091bc56edSDimitry Andric switch (Val) { 89191bc56edSDimitry Andric default: // Map unknown values to default. 89291bc56edSDimitry Andric case 0: return GlobalValue::DefaultStorageClass; 89391bc56edSDimitry Andric case 1: return GlobalValue::DLLImportStorageClass; 89491bc56edSDimitry Andric case 2: return GlobalValue::DLLExportStorageClass; 89591bc56edSDimitry Andric } 89691bc56edSDimitry Andric } 89791bc56edSDimitry Andric 8988f0fd8f6SDimitry Andric static GlobalVariable::ThreadLocalMode getDecodedThreadLocalMode(unsigned Val) { 8997ae0e2c9SDimitry Andric switch (Val) { 9007ae0e2c9SDimitry Andric case 0: return GlobalVariable::NotThreadLocal; 9017ae0e2c9SDimitry Andric default: // Map unknown non-zero value to general dynamic. 9027ae0e2c9SDimitry Andric case 1: return GlobalVariable::GeneralDynamicTLSModel; 9037ae0e2c9SDimitry Andric case 2: return GlobalVariable::LocalDynamicTLSModel; 9047ae0e2c9SDimitry Andric case 3: return GlobalVariable::InitialExecTLSModel; 9057ae0e2c9SDimitry Andric case 4: return GlobalVariable::LocalExecTLSModel; 9067ae0e2c9SDimitry Andric } 9077ae0e2c9SDimitry Andric } 9087ae0e2c9SDimitry Andric 9093ca95b02SDimitry Andric static GlobalVariable::UnnamedAddr getDecodedUnnamedAddrType(unsigned Val) { 9103ca95b02SDimitry Andric switch (Val) { 9113ca95b02SDimitry Andric default: // Map unknown to UnnamedAddr::None. 9123ca95b02SDimitry Andric case 0: return GlobalVariable::UnnamedAddr::None; 9133ca95b02SDimitry Andric case 1: return GlobalVariable::UnnamedAddr::Global; 9143ca95b02SDimitry Andric case 2: return GlobalVariable::UnnamedAddr::Local; 9153ca95b02SDimitry Andric } 9163ca95b02SDimitry Andric } 9173ca95b02SDimitry Andric 9188f0fd8f6SDimitry Andric static int getDecodedCastOpcode(unsigned Val) { 919f22ef01cSRoman Divacky switch (Val) { 920f22ef01cSRoman Divacky default: return -1; 921f22ef01cSRoman Divacky case bitc::CAST_TRUNC : return Instruction::Trunc; 922f22ef01cSRoman Divacky case bitc::CAST_ZEXT : return Instruction::ZExt; 923f22ef01cSRoman Divacky case bitc::CAST_SEXT : return Instruction::SExt; 924f22ef01cSRoman Divacky case bitc::CAST_FPTOUI : return Instruction::FPToUI; 925f22ef01cSRoman Divacky case bitc::CAST_FPTOSI : return Instruction::FPToSI; 926f22ef01cSRoman Divacky case bitc::CAST_UITOFP : return Instruction::UIToFP; 927f22ef01cSRoman Divacky case bitc::CAST_SITOFP : return Instruction::SIToFP; 928f22ef01cSRoman Divacky case bitc::CAST_FPTRUNC : return Instruction::FPTrunc; 929f22ef01cSRoman Divacky case bitc::CAST_FPEXT : return Instruction::FPExt; 930f22ef01cSRoman Divacky case bitc::CAST_PTRTOINT: return Instruction::PtrToInt; 931f22ef01cSRoman Divacky case bitc::CAST_INTTOPTR: return Instruction::IntToPtr; 932f22ef01cSRoman Divacky case bitc::CAST_BITCAST : return Instruction::BitCast; 933f785676fSDimitry Andric case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast; 934f22ef01cSRoman Divacky } 935f22ef01cSRoman Divacky } 936ff0cc061SDimitry Andric 9378f0fd8f6SDimitry Andric static int getDecodedBinaryOpcode(unsigned Val, Type *Ty) { 938ff0cc061SDimitry Andric bool IsFP = Ty->isFPOrFPVectorTy(); 939ff0cc061SDimitry Andric // BinOps are only valid for int/fp or vector of int/fp types 940ff0cc061SDimitry Andric if (!IsFP && !Ty->isIntOrIntVectorTy()) 941ff0cc061SDimitry Andric return -1; 942ff0cc061SDimitry Andric 943f22ef01cSRoman Divacky switch (Val) { 944ff0cc061SDimitry Andric default: 945ff0cc061SDimitry Andric return -1; 946f22ef01cSRoman Divacky case bitc::BINOP_ADD: 947ff0cc061SDimitry Andric return IsFP ? Instruction::FAdd : Instruction::Add; 948f22ef01cSRoman Divacky case bitc::BINOP_SUB: 949ff0cc061SDimitry Andric return IsFP ? Instruction::FSub : Instruction::Sub; 950f22ef01cSRoman Divacky case bitc::BINOP_MUL: 951ff0cc061SDimitry Andric return IsFP ? Instruction::FMul : Instruction::Mul; 952ff0cc061SDimitry Andric case bitc::BINOP_UDIV: 953ff0cc061SDimitry Andric return IsFP ? -1 : Instruction::UDiv; 954f22ef01cSRoman Divacky case bitc::BINOP_SDIV: 955ff0cc061SDimitry Andric return IsFP ? Instruction::FDiv : Instruction::SDiv; 956ff0cc061SDimitry Andric case bitc::BINOP_UREM: 957ff0cc061SDimitry Andric return IsFP ? -1 : Instruction::URem; 958f22ef01cSRoman Divacky case bitc::BINOP_SREM: 959ff0cc061SDimitry Andric return IsFP ? Instruction::FRem : Instruction::SRem; 960ff0cc061SDimitry Andric case bitc::BINOP_SHL: 961ff0cc061SDimitry Andric return IsFP ? -1 : Instruction::Shl; 962ff0cc061SDimitry Andric case bitc::BINOP_LSHR: 963ff0cc061SDimitry Andric return IsFP ? -1 : Instruction::LShr; 964ff0cc061SDimitry Andric case bitc::BINOP_ASHR: 965ff0cc061SDimitry Andric return IsFP ? -1 : Instruction::AShr; 966ff0cc061SDimitry Andric case bitc::BINOP_AND: 967ff0cc061SDimitry Andric return IsFP ? -1 : Instruction::And; 968ff0cc061SDimitry Andric case bitc::BINOP_OR: 969ff0cc061SDimitry Andric return IsFP ? -1 : Instruction::Or; 970ff0cc061SDimitry Andric case bitc::BINOP_XOR: 971ff0cc061SDimitry Andric return IsFP ? -1 : Instruction::Xor; 972f22ef01cSRoman Divacky } 973f22ef01cSRoman Divacky } 974f22ef01cSRoman Divacky 9758f0fd8f6SDimitry Andric static AtomicRMWInst::BinOp getDecodedRMWOperation(unsigned Val) { 9766122f3e6SDimitry Andric switch (Val) { 9776122f3e6SDimitry Andric default: return AtomicRMWInst::BAD_BINOP; 9786122f3e6SDimitry Andric case bitc::RMW_XCHG: return AtomicRMWInst::Xchg; 9796122f3e6SDimitry Andric case bitc::RMW_ADD: return AtomicRMWInst::Add; 9806122f3e6SDimitry Andric case bitc::RMW_SUB: return AtomicRMWInst::Sub; 9816122f3e6SDimitry Andric case bitc::RMW_AND: return AtomicRMWInst::And; 9826122f3e6SDimitry Andric case bitc::RMW_NAND: return AtomicRMWInst::Nand; 9836122f3e6SDimitry Andric case bitc::RMW_OR: return AtomicRMWInst::Or; 9846122f3e6SDimitry Andric case bitc::RMW_XOR: return AtomicRMWInst::Xor; 9856122f3e6SDimitry Andric case bitc::RMW_MAX: return AtomicRMWInst::Max; 9866122f3e6SDimitry Andric case bitc::RMW_MIN: return AtomicRMWInst::Min; 9876122f3e6SDimitry Andric case bitc::RMW_UMAX: return AtomicRMWInst::UMax; 9886122f3e6SDimitry Andric case bitc::RMW_UMIN: return AtomicRMWInst::UMin; 9896122f3e6SDimitry Andric } 9906122f3e6SDimitry Andric } 9916122f3e6SDimitry Andric 9928f0fd8f6SDimitry Andric static AtomicOrdering getDecodedOrdering(unsigned Val) { 9936122f3e6SDimitry Andric switch (Val) { 9943ca95b02SDimitry Andric case bitc::ORDERING_NOTATOMIC: return AtomicOrdering::NotAtomic; 9953ca95b02SDimitry Andric case bitc::ORDERING_UNORDERED: return AtomicOrdering::Unordered; 9963ca95b02SDimitry Andric case bitc::ORDERING_MONOTONIC: return AtomicOrdering::Monotonic; 9973ca95b02SDimitry Andric case bitc::ORDERING_ACQUIRE: return AtomicOrdering::Acquire; 9983ca95b02SDimitry Andric case bitc::ORDERING_RELEASE: return AtomicOrdering::Release; 9993ca95b02SDimitry Andric case bitc::ORDERING_ACQREL: return AtomicOrdering::AcquireRelease; 10006122f3e6SDimitry Andric default: // Map unknown orderings to sequentially-consistent. 10013ca95b02SDimitry Andric case bitc::ORDERING_SEQCST: return AtomicOrdering::SequentiallyConsistent; 10026122f3e6SDimitry Andric } 10036122f3e6SDimitry Andric } 10046122f3e6SDimitry Andric 100591bc56edSDimitry Andric static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val) { 100691bc56edSDimitry Andric switch (Val) { 100791bc56edSDimitry Andric default: // Map unknown selection kinds to any. 100891bc56edSDimitry Andric case bitc::COMDAT_SELECTION_KIND_ANY: 100991bc56edSDimitry Andric return Comdat::Any; 101091bc56edSDimitry Andric case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH: 101191bc56edSDimitry Andric return Comdat::ExactMatch; 101291bc56edSDimitry Andric case bitc::COMDAT_SELECTION_KIND_LARGEST: 101391bc56edSDimitry Andric return Comdat::Largest; 101491bc56edSDimitry Andric case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES: 101591bc56edSDimitry Andric return Comdat::NoDuplicates; 101691bc56edSDimitry Andric case bitc::COMDAT_SELECTION_KIND_SAME_SIZE: 101791bc56edSDimitry Andric return Comdat::SameSize; 101891bc56edSDimitry Andric } 101991bc56edSDimitry Andric } 102091bc56edSDimitry Andric 1021875ed548SDimitry Andric static FastMathFlags getDecodedFastMathFlags(unsigned Val) { 1022875ed548SDimitry Andric FastMathFlags FMF; 1023875ed548SDimitry Andric if (0 != (Val & FastMathFlags::UnsafeAlgebra)) 1024875ed548SDimitry Andric FMF.setUnsafeAlgebra(); 1025875ed548SDimitry Andric if (0 != (Val & FastMathFlags::NoNaNs)) 1026875ed548SDimitry Andric FMF.setNoNaNs(); 1027875ed548SDimitry Andric if (0 != (Val & FastMathFlags::NoInfs)) 1028875ed548SDimitry Andric FMF.setNoInfs(); 1029875ed548SDimitry Andric if (0 != (Val & FastMathFlags::NoSignedZeros)) 1030875ed548SDimitry Andric FMF.setNoSignedZeros(); 1031875ed548SDimitry Andric if (0 != (Val & FastMathFlags::AllowReciprocal)) 1032875ed548SDimitry Andric FMF.setAllowReciprocal(); 10337a7e6055SDimitry Andric if (0 != (Val & FastMathFlags::AllowContract)) 10347a7e6055SDimitry Andric FMF.setAllowContract(true); 1035875ed548SDimitry Andric return FMF; 1036875ed548SDimitry Andric } 1037875ed548SDimitry Andric 1038d88c1a5aSDimitry Andric static void upgradeDLLImportExportLinkage(GlobalValue *GV, unsigned Val) { 103991bc56edSDimitry Andric switch (Val) { 104091bc56edSDimitry Andric case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break; 104191bc56edSDimitry Andric case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break; 104291bc56edSDimitry Andric } 104391bc56edSDimitry Andric } 104491bc56edSDimitry Andric 10453ca95b02SDimitry Andric 104617a519f9SDimitry Andric Type *BitcodeReader::getTypeByID(unsigned ID) { 104717a519f9SDimitry Andric // The type table size is always specified correctly. 104817a519f9SDimitry Andric if (ID >= TypeList.size()) 104991bc56edSDimitry Andric return nullptr; 1050f22ef01cSRoman Divacky 105117a519f9SDimitry Andric if (Type *Ty = TypeList[ID]) 105217a519f9SDimitry Andric return Ty; 105317a519f9SDimitry Andric 105417a519f9SDimitry Andric // If we have a forward reference, the only possible case is when it is to a 105517a519f9SDimitry Andric // named struct. Just create a placeholder for now. 105639d628a0SDimitry Andric return TypeList[ID] = createIdentifiedStructType(Context); 105739d628a0SDimitry Andric } 105839d628a0SDimitry Andric 105939d628a0SDimitry Andric StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context, 106039d628a0SDimitry Andric StringRef Name) { 106139d628a0SDimitry Andric auto *Ret = StructType::create(Context, Name); 106239d628a0SDimitry Andric IdentifiedStructTypes.push_back(Ret); 106339d628a0SDimitry Andric return Ret; 106439d628a0SDimitry Andric } 106539d628a0SDimitry Andric 106639d628a0SDimitry Andric StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context) { 106739d628a0SDimitry Andric auto *Ret = StructType::create(Context); 106839d628a0SDimitry Andric IdentifiedStructTypes.push_back(Ret); 106939d628a0SDimitry Andric return Ret; 1070f22ef01cSRoman Divacky } 1071f22ef01cSRoman Divacky 1072f22ef01cSRoman Divacky //===----------------------------------------------------------------------===// 1073f22ef01cSRoman Divacky // Functions for parsing blocks from the bitcode file 1074f22ef01cSRoman Divacky //===----------------------------------------------------------------------===// 1075f22ef01cSRoman Divacky 1076d88c1a5aSDimitry Andric static uint64_t getRawAttributeMask(Attribute::AttrKind Val) { 1077d88c1a5aSDimitry Andric switch (Val) { 1078d88c1a5aSDimitry Andric case Attribute::EndAttrKinds: 1079d88c1a5aSDimitry Andric llvm_unreachable("Synthetic enumerators which should never get here"); 1080d88c1a5aSDimitry Andric 1081d88c1a5aSDimitry Andric case Attribute::None: return 0; 1082d88c1a5aSDimitry Andric case Attribute::ZExt: return 1 << 0; 1083d88c1a5aSDimitry Andric case Attribute::SExt: return 1 << 1; 1084d88c1a5aSDimitry Andric case Attribute::NoReturn: return 1 << 2; 1085d88c1a5aSDimitry Andric case Attribute::InReg: return 1 << 3; 1086d88c1a5aSDimitry Andric case Attribute::StructRet: return 1 << 4; 1087d88c1a5aSDimitry Andric case Attribute::NoUnwind: return 1 << 5; 1088d88c1a5aSDimitry Andric case Attribute::NoAlias: return 1 << 6; 1089d88c1a5aSDimitry Andric case Attribute::ByVal: return 1 << 7; 1090d88c1a5aSDimitry Andric case Attribute::Nest: return 1 << 8; 1091d88c1a5aSDimitry Andric case Attribute::ReadNone: return 1 << 9; 1092d88c1a5aSDimitry Andric case Attribute::ReadOnly: return 1 << 10; 1093d88c1a5aSDimitry Andric case Attribute::NoInline: return 1 << 11; 1094d88c1a5aSDimitry Andric case Attribute::AlwaysInline: return 1 << 12; 1095d88c1a5aSDimitry Andric case Attribute::OptimizeForSize: return 1 << 13; 1096d88c1a5aSDimitry Andric case Attribute::StackProtect: return 1 << 14; 1097d88c1a5aSDimitry Andric case Attribute::StackProtectReq: return 1 << 15; 1098d88c1a5aSDimitry Andric case Attribute::Alignment: return 31 << 16; 1099d88c1a5aSDimitry Andric case Attribute::NoCapture: return 1 << 21; 1100d88c1a5aSDimitry Andric case Attribute::NoRedZone: return 1 << 22; 1101d88c1a5aSDimitry Andric case Attribute::NoImplicitFloat: return 1 << 23; 1102d88c1a5aSDimitry Andric case Attribute::Naked: return 1 << 24; 1103d88c1a5aSDimitry Andric case Attribute::InlineHint: return 1 << 25; 1104d88c1a5aSDimitry Andric case Attribute::StackAlignment: return 7 << 26; 1105d88c1a5aSDimitry Andric case Attribute::ReturnsTwice: return 1 << 29; 1106d88c1a5aSDimitry Andric case Attribute::UWTable: return 1 << 30; 1107d88c1a5aSDimitry Andric case Attribute::NonLazyBind: return 1U << 31; 1108d88c1a5aSDimitry Andric case Attribute::SanitizeAddress: return 1ULL << 32; 1109d88c1a5aSDimitry Andric case Attribute::MinSize: return 1ULL << 33; 1110d88c1a5aSDimitry Andric case Attribute::NoDuplicate: return 1ULL << 34; 1111d88c1a5aSDimitry Andric case Attribute::StackProtectStrong: return 1ULL << 35; 1112d88c1a5aSDimitry Andric case Attribute::SanitizeThread: return 1ULL << 36; 1113d88c1a5aSDimitry Andric case Attribute::SanitizeMemory: return 1ULL << 37; 1114d88c1a5aSDimitry Andric case Attribute::NoBuiltin: return 1ULL << 38; 1115d88c1a5aSDimitry Andric case Attribute::Returned: return 1ULL << 39; 1116d88c1a5aSDimitry Andric case Attribute::Cold: return 1ULL << 40; 1117d88c1a5aSDimitry Andric case Attribute::Builtin: return 1ULL << 41; 1118d88c1a5aSDimitry Andric case Attribute::OptimizeNone: return 1ULL << 42; 1119d88c1a5aSDimitry Andric case Attribute::InAlloca: return 1ULL << 43; 1120d88c1a5aSDimitry Andric case Attribute::NonNull: return 1ULL << 44; 1121d88c1a5aSDimitry Andric case Attribute::JumpTable: return 1ULL << 45; 1122d88c1a5aSDimitry Andric case Attribute::Convergent: return 1ULL << 46; 1123d88c1a5aSDimitry Andric case Attribute::SafeStack: return 1ULL << 47; 1124d88c1a5aSDimitry Andric case Attribute::NoRecurse: return 1ULL << 48; 1125d88c1a5aSDimitry Andric case Attribute::InaccessibleMemOnly: return 1ULL << 49; 1126d88c1a5aSDimitry Andric case Attribute::InaccessibleMemOrArgMemOnly: return 1ULL << 50; 1127d88c1a5aSDimitry Andric case Attribute::SwiftSelf: return 1ULL << 51; 1128d88c1a5aSDimitry Andric case Attribute::SwiftError: return 1ULL << 52; 1129d88c1a5aSDimitry Andric case Attribute::WriteOnly: return 1ULL << 53; 1130f37b6182SDimitry Andric case Attribute::Speculatable: return 1ULL << 54; 1131d88c1a5aSDimitry Andric case Attribute::Dereferenceable: 1132d88c1a5aSDimitry Andric llvm_unreachable("dereferenceable attribute not supported in raw format"); 1133d88c1a5aSDimitry Andric break; 1134d88c1a5aSDimitry Andric case Attribute::DereferenceableOrNull: 1135d88c1a5aSDimitry Andric llvm_unreachable("dereferenceable_or_null attribute not supported in raw " 1136d88c1a5aSDimitry Andric "format"); 1137d88c1a5aSDimitry Andric break; 1138d88c1a5aSDimitry Andric case Attribute::ArgMemOnly: 1139d88c1a5aSDimitry Andric llvm_unreachable("argmemonly attribute not supported in raw format"); 1140d88c1a5aSDimitry Andric break; 1141d88c1a5aSDimitry Andric case Attribute::AllocSize: 1142d88c1a5aSDimitry Andric llvm_unreachable("allocsize not supported in raw format"); 1143d88c1a5aSDimitry Andric break; 1144d88c1a5aSDimitry Andric } 1145d88c1a5aSDimitry Andric llvm_unreachable("Unsupported attribute type"); 1146d88c1a5aSDimitry Andric } 1147d88c1a5aSDimitry Andric 1148d88c1a5aSDimitry Andric static void addRawAttributeValue(AttrBuilder &B, uint64_t Val) { 1149d88c1a5aSDimitry Andric if (!Val) return; 1150d88c1a5aSDimitry Andric 1151d88c1a5aSDimitry Andric for (Attribute::AttrKind I = Attribute::None; I != Attribute::EndAttrKinds; 1152d88c1a5aSDimitry Andric I = Attribute::AttrKind(I + 1)) { 1153d88c1a5aSDimitry Andric if (I == Attribute::Dereferenceable || 1154d88c1a5aSDimitry Andric I == Attribute::DereferenceableOrNull || 1155d88c1a5aSDimitry Andric I == Attribute::ArgMemOnly || 1156d88c1a5aSDimitry Andric I == Attribute::AllocSize) 1157d88c1a5aSDimitry Andric continue; 1158d88c1a5aSDimitry Andric if (uint64_t A = (Val & getRawAttributeMask(I))) { 1159d88c1a5aSDimitry Andric if (I == Attribute::Alignment) 1160d88c1a5aSDimitry Andric B.addAlignmentAttr(1ULL << ((A >> 16) - 1)); 1161d88c1a5aSDimitry Andric else if (I == Attribute::StackAlignment) 1162d88c1a5aSDimitry Andric B.addStackAlignmentAttr(1ULL << ((A >> 26)-1)); 1163d88c1a5aSDimitry Andric else 1164d88c1a5aSDimitry Andric B.addAttribute(I); 1165d88c1a5aSDimitry Andric } 1166d88c1a5aSDimitry Andric } 1167d88c1a5aSDimitry Andric } 1168139f7f9bSDimitry Andric 1169139f7f9bSDimitry Andric /// \brief This fills an AttrBuilder object with the LLVM attributes that have 1170139f7f9bSDimitry Andric /// been decoded from the given integer. This function must stay in sync with 1171139f7f9bSDimitry Andric /// 'encodeLLVMAttributesForBitcode'. 1172139f7f9bSDimitry Andric static void decodeLLVMAttributesForBitcode(AttrBuilder &B, 1173139f7f9bSDimitry Andric uint64_t EncodedAttrs) { 1174139f7f9bSDimitry Andric // FIXME: Remove in 4.0. 1175139f7f9bSDimitry Andric 1176139f7f9bSDimitry Andric // The alignment is stored as a 16-bit raw value from bits 31--16. We shift 1177139f7f9bSDimitry Andric // the bits above 31 down by 11 bits. 1178139f7f9bSDimitry Andric unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16; 1179139f7f9bSDimitry Andric assert((!Alignment || isPowerOf2_32(Alignment)) && 1180139f7f9bSDimitry Andric "Alignment must be a power of two."); 1181139f7f9bSDimitry Andric 1182139f7f9bSDimitry Andric if (Alignment) 1183139f7f9bSDimitry Andric B.addAlignmentAttr(Alignment); 1184d88c1a5aSDimitry Andric addRawAttributeValue(B, ((EncodedAttrs & (0xfffffULL << 32)) >> 11) | 1185139f7f9bSDimitry Andric (EncodedAttrs & 0xffff)); 1186139f7f9bSDimitry Andric } 1187139f7f9bSDimitry Andric 1188d88c1a5aSDimitry Andric Error BitcodeReader::parseAttributeBlock() { 1189f22ef01cSRoman Divacky if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID)) 11908f0fd8f6SDimitry Andric return error("Invalid record"); 1191f22ef01cSRoman Divacky 1192f22ef01cSRoman Divacky if (!MAttributes.empty()) 11938f0fd8f6SDimitry Andric return error("Invalid multiple blocks"); 1194f22ef01cSRoman Divacky 1195f22ef01cSRoman Divacky SmallVector<uint64_t, 64> Record; 1196f22ef01cSRoman Divacky 11977a7e6055SDimitry Andric SmallVector<AttributeList, 8> Attrs; 1198f22ef01cSRoman Divacky 1199f22ef01cSRoman Divacky // Read all the records. 1200d88c1a5aSDimitry Andric while (true) { 1201139f7f9bSDimitry Andric BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 1202139f7f9bSDimitry Andric 1203139f7f9bSDimitry Andric switch (Entry.Kind) { 1204139f7f9bSDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already. 1205139f7f9bSDimitry Andric case BitstreamEntry::Error: 12068f0fd8f6SDimitry Andric return error("Malformed block"); 1207139f7f9bSDimitry Andric case BitstreamEntry::EndBlock: 1208d88c1a5aSDimitry Andric return Error::success(); 1209139f7f9bSDimitry Andric case BitstreamEntry::Record: 1210139f7f9bSDimitry Andric // The interesting case. 1211139f7f9bSDimitry Andric break; 1212f22ef01cSRoman Divacky } 1213f22ef01cSRoman Divacky 1214f22ef01cSRoman Divacky // Read a record. 1215f22ef01cSRoman Divacky Record.clear(); 1216139f7f9bSDimitry Andric switch (Stream.readRecord(Entry.ID, Record)) { 1217f22ef01cSRoman Divacky default: // Default behavior: ignore. 1218f22ef01cSRoman Divacky break; 1219139f7f9bSDimitry Andric case bitc::PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...] 1220139f7f9bSDimitry Andric // FIXME: Remove in 4.0. 1221f22ef01cSRoman Divacky if (Record.size() & 1) 12228f0fd8f6SDimitry Andric return error("Invalid record"); 1223f22ef01cSRoman Divacky 1224f22ef01cSRoman Divacky for (unsigned i = 0, e = Record.size(); i != e; i += 2) { 1225139f7f9bSDimitry Andric AttrBuilder B; 1226139f7f9bSDimitry Andric decodeLLVMAttributesForBitcode(B, Record[i+1]); 12277a7e6055SDimitry Andric Attrs.push_back(AttributeList::get(Context, Record[i], B)); 1228f22ef01cSRoman Divacky } 1229f22ef01cSRoman Divacky 12307a7e6055SDimitry Andric MAttributes.push_back(AttributeList::get(Context, Attrs)); 1231f22ef01cSRoman Divacky Attrs.clear(); 1232f22ef01cSRoman Divacky break; 1233f22ef01cSRoman Divacky } 1234139f7f9bSDimitry Andric case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [attrgrp0, attrgrp1, ...] 1235139f7f9bSDimitry Andric for (unsigned i = 0, e = Record.size(); i != e; ++i) 1236139f7f9bSDimitry Andric Attrs.push_back(MAttributeGroups[Record[i]]); 1237139f7f9bSDimitry Andric 12387a7e6055SDimitry Andric MAttributes.push_back(AttributeList::get(Context, Attrs)); 1239139f7f9bSDimitry Andric Attrs.clear(); 1240139f7f9bSDimitry Andric break; 1241139f7f9bSDimitry Andric } 1242139f7f9bSDimitry Andric } 1243139f7f9bSDimitry Andric } 1244139f7f9bSDimitry Andric } 1245139f7f9bSDimitry Andric 1246f785676fSDimitry Andric // Returns Attribute::None on unrecognized codes. 12478f0fd8f6SDimitry Andric static Attribute::AttrKind getAttrFromCode(uint64_t Code) { 1248f785676fSDimitry Andric switch (Code) { 1249f785676fSDimitry Andric default: 1250f785676fSDimitry Andric return Attribute::None; 1251f785676fSDimitry Andric case bitc::ATTR_KIND_ALIGNMENT: 1252f785676fSDimitry Andric return Attribute::Alignment; 1253f785676fSDimitry Andric case bitc::ATTR_KIND_ALWAYS_INLINE: 1254f785676fSDimitry Andric return Attribute::AlwaysInline; 1255875ed548SDimitry Andric case bitc::ATTR_KIND_ARGMEMONLY: 1256875ed548SDimitry Andric return Attribute::ArgMemOnly; 1257f785676fSDimitry Andric case bitc::ATTR_KIND_BUILTIN: 1258f785676fSDimitry Andric return Attribute::Builtin; 1259f785676fSDimitry Andric case bitc::ATTR_KIND_BY_VAL: 1260f785676fSDimitry Andric return Attribute::ByVal; 126191bc56edSDimitry Andric case bitc::ATTR_KIND_IN_ALLOCA: 126291bc56edSDimitry Andric return Attribute::InAlloca; 1263f785676fSDimitry Andric case bitc::ATTR_KIND_COLD: 1264f785676fSDimitry Andric return Attribute::Cold; 1265ff0cc061SDimitry Andric case bitc::ATTR_KIND_CONVERGENT: 1266ff0cc061SDimitry Andric return Attribute::Convergent; 12677d523365SDimitry Andric case bitc::ATTR_KIND_INACCESSIBLEMEM_ONLY: 12687d523365SDimitry Andric return Attribute::InaccessibleMemOnly; 12697d523365SDimitry Andric case bitc::ATTR_KIND_INACCESSIBLEMEM_OR_ARGMEMONLY: 12707d523365SDimitry Andric return Attribute::InaccessibleMemOrArgMemOnly; 1271f785676fSDimitry Andric case bitc::ATTR_KIND_INLINE_HINT: 1272f785676fSDimitry Andric return Attribute::InlineHint; 1273f785676fSDimitry Andric case bitc::ATTR_KIND_IN_REG: 1274f785676fSDimitry Andric return Attribute::InReg; 127591bc56edSDimitry Andric case bitc::ATTR_KIND_JUMP_TABLE: 127691bc56edSDimitry Andric return Attribute::JumpTable; 1277f785676fSDimitry Andric case bitc::ATTR_KIND_MIN_SIZE: 1278f785676fSDimitry Andric return Attribute::MinSize; 1279f785676fSDimitry Andric case bitc::ATTR_KIND_NAKED: 1280f785676fSDimitry Andric return Attribute::Naked; 1281f785676fSDimitry Andric case bitc::ATTR_KIND_NEST: 1282f785676fSDimitry Andric return Attribute::Nest; 1283f785676fSDimitry Andric case bitc::ATTR_KIND_NO_ALIAS: 1284f785676fSDimitry Andric return Attribute::NoAlias; 1285f785676fSDimitry Andric case bitc::ATTR_KIND_NO_BUILTIN: 1286f785676fSDimitry Andric return Attribute::NoBuiltin; 1287f785676fSDimitry Andric case bitc::ATTR_KIND_NO_CAPTURE: 1288f785676fSDimitry Andric return Attribute::NoCapture; 1289f785676fSDimitry Andric case bitc::ATTR_KIND_NO_DUPLICATE: 1290f785676fSDimitry Andric return Attribute::NoDuplicate; 1291f785676fSDimitry Andric case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT: 1292f785676fSDimitry Andric return Attribute::NoImplicitFloat; 1293f785676fSDimitry Andric case bitc::ATTR_KIND_NO_INLINE: 1294f785676fSDimitry Andric return Attribute::NoInline; 12957d523365SDimitry Andric case bitc::ATTR_KIND_NO_RECURSE: 12967d523365SDimitry Andric return Attribute::NoRecurse; 1297f785676fSDimitry Andric case bitc::ATTR_KIND_NON_LAZY_BIND: 1298f785676fSDimitry Andric return Attribute::NonLazyBind; 129991bc56edSDimitry Andric case bitc::ATTR_KIND_NON_NULL: 130091bc56edSDimitry Andric return Attribute::NonNull; 130191bc56edSDimitry Andric case bitc::ATTR_KIND_DEREFERENCEABLE: 130291bc56edSDimitry Andric return Attribute::Dereferenceable; 1303ff0cc061SDimitry Andric case bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL: 1304ff0cc061SDimitry Andric return Attribute::DereferenceableOrNull; 13053ca95b02SDimitry Andric case bitc::ATTR_KIND_ALLOC_SIZE: 13063ca95b02SDimitry Andric return Attribute::AllocSize; 1307f785676fSDimitry Andric case bitc::ATTR_KIND_NO_RED_ZONE: 1308f785676fSDimitry Andric return Attribute::NoRedZone; 1309f785676fSDimitry Andric case bitc::ATTR_KIND_NO_RETURN: 1310f785676fSDimitry Andric return Attribute::NoReturn; 1311f785676fSDimitry Andric case bitc::ATTR_KIND_NO_UNWIND: 1312f785676fSDimitry Andric return Attribute::NoUnwind; 1313f785676fSDimitry Andric case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE: 1314f785676fSDimitry Andric return Attribute::OptimizeForSize; 1315f785676fSDimitry Andric case bitc::ATTR_KIND_OPTIMIZE_NONE: 1316f785676fSDimitry Andric return Attribute::OptimizeNone; 1317f785676fSDimitry Andric case bitc::ATTR_KIND_READ_NONE: 1318f785676fSDimitry Andric return Attribute::ReadNone; 1319f785676fSDimitry Andric case bitc::ATTR_KIND_READ_ONLY: 1320f785676fSDimitry Andric return Attribute::ReadOnly; 1321f785676fSDimitry Andric case bitc::ATTR_KIND_RETURNED: 1322f785676fSDimitry Andric return Attribute::Returned; 1323f785676fSDimitry Andric case bitc::ATTR_KIND_RETURNS_TWICE: 1324f785676fSDimitry Andric return Attribute::ReturnsTwice; 1325f785676fSDimitry Andric case bitc::ATTR_KIND_S_EXT: 1326f785676fSDimitry Andric return Attribute::SExt; 1327f37b6182SDimitry Andric case bitc::ATTR_KIND_SPECULATABLE: 1328f37b6182SDimitry Andric return Attribute::Speculatable; 1329f785676fSDimitry Andric case bitc::ATTR_KIND_STACK_ALIGNMENT: 1330f785676fSDimitry Andric return Attribute::StackAlignment; 1331f785676fSDimitry Andric case bitc::ATTR_KIND_STACK_PROTECT: 1332f785676fSDimitry Andric return Attribute::StackProtect; 1333f785676fSDimitry Andric case bitc::ATTR_KIND_STACK_PROTECT_REQ: 1334f785676fSDimitry Andric return Attribute::StackProtectReq; 1335f785676fSDimitry Andric case bitc::ATTR_KIND_STACK_PROTECT_STRONG: 1336f785676fSDimitry Andric return Attribute::StackProtectStrong; 13378f0fd8f6SDimitry Andric case bitc::ATTR_KIND_SAFESTACK: 13388f0fd8f6SDimitry Andric return Attribute::SafeStack; 1339f785676fSDimitry Andric case bitc::ATTR_KIND_STRUCT_RET: 1340f785676fSDimitry Andric return Attribute::StructRet; 1341f785676fSDimitry Andric case bitc::ATTR_KIND_SANITIZE_ADDRESS: 1342f785676fSDimitry Andric return Attribute::SanitizeAddress; 1343f785676fSDimitry Andric case bitc::ATTR_KIND_SANITIZE_THREAD: 1344f785676fSDimitry Andric return Attribute::SanitizeThread; 1345f785676fSDimitry Andric case bitc::ATTR_KIND_SANITIZE_MEMORY: 1346f785676fSDimitry Andric return Attribute::SanitizeMemory; 13473ca95b02SDimitry Andric case bitc::ATTR_KIND_SWIFT_ERROR: 13483ca95b02SDimitry Andric return Attribute::SwiftError; 13493ca95b02SDimitry Andric case bitc::ATTR_KIND_SWIFT_SELF: 13503ca95b02SDimitry Andric return Attribute::SwiftSelf; 1351f785676fSDimitry Andric case bitc::ATTR_KIND_UW_TABLE: 1352f785676fSDimitry Andric return Attribute::UWTable; 13533ca95b02SDimitry Andric case bitc::ATTR_KIND_WRITEONLY: 13543ca95b02SDimitry Andric return Attribute::WriteOnly; 1355f785676fSDimitry Andric case bitc::ATTR_KIND_Z_EXT: 1356f785676fSDimitry Andric return Attribute::ZExt; 1357f785676fSDimitry Andric } 1358f785676fSDimitry Andric } 1359f785676fSDimitry Andric 1360d88c1a5aSDimitry Andric Error BitcodeReader::parseAlignmentValue(uint64_t Exponent, 1361ff0cc061SDimitry Andric unsigned &Alignment) { 1362ff0cc061SDimitry Andric // Note: Alignment in bitcode files is incremented by 1, so that zero 1363ff0cc061SDimitry Andric // can be used for default alignment. 1364ff0cc061SDimitry Andric if (Exponent > Value::MaxAlignmentExponent + 1) 13658f0fd8f6SDimitry Andric return error("Invalid alignment value"); 1366ff0cc061SDimitry Andric Alignment = (1 << static_cast<unsigned>(Exponent)) >> 1; 1367d88c1a5aSDimitry Andric return Error::success(); 1368ff0cc061SDimitry Andric } 1369ff0cc061SDimitry Andric 1370d88c1a5aSDimitry Andric Error BitcodeReader::parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind) { 13718f0fd8f6SDimitry Andric *Kind = getAttrFromCode(Code); 1372f785676fSDimitry Andric if (*Kind == Attribute::None) 1373d88c1a5aSDimitry Andric return error("Unknown attribute kind (" + Twine(Code) + ")"); 1374d88c1a5aSDimitry Andric return Error::success(); 1375f785676fSDimitry Andric } 1376f785676fSDimitry Andric 1377d88c1a5aSDimitry Andric Error BitcodeReader::parseAttributeGroupBlock() { 1378139f7f9bSDimitry Andric if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID)) 13798f0fd8f6SDimitry Andric return error("Invalid record"); 1380139f7f9bSDimitry Andric 1381139f7f9bSDimitry Andric if (!MAttributeGroups.empty()) 13828f0fd8f6SDimitry Andric return error("Invalid multiple blocks"); 1383139f7f9bSDimitry Andric 1384139f7f9bSDimitry Andric SmallVector<uint64_t, 64> Record; 1385139f7f9bSDimitry Andric 1386139f7f9bSDimitry Andric // Read all the records. 1387d88c1a5aSDimitry Andric while (true) { 1388139f7f9bSDimitry Andric BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 1389139f7f9bSDimitry Andric 1390139f7f9bSDimitry Andric switch (Entry.Kind) { 1391139f7f9bSDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already. 1392139f7f9bSDimitry Andric case BitstreamEntry::Error: 13938f0fd8f6SDimitry Andric return error("Malformed block"); 1394139f7f9bSDimitry Andric case BitstreamEntry::EndBlock: 1395d88c1a5aSDimitry Andric return Error::success(); 1396139f7f9bSDimitry Andric case BitstreamEntry::Record: 1397139f7f9bSDimitry Andric // The interesting case. 1398139f7f9bSDimitry Andric break; 1399139f7f9bSDimitry Andric } 1400139f7f9bSDimitry Andric 1401139f7f9bSDimitry Andric // Read a record. 1402139f7f9bSDimitry Andric Record.clear(); 1403139f7f9bSDimitry Andric switch (Stream.readRecord(Entry.ID, Record)) { 1404139f7f9bSDimitry Andric default: // Default behavior: ignore. 1405139f7f9bSDimitry Andric break; 1406139f7f9bSDimitry Andric case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...] 1407139f7f9bSDimitry Andric if (Record.size() < 3) 14088f0fd8f6SDimitry Andric return error("Invalid record"); 1409139f7f9bSDimitry Andric 1410139f7f9bSDimitry Andric uint64_t GrpID = Record[0]; 1411139f7f9bSDimitry Andric uint64_t Idx = Record[1]; // Index of the object this attribute refers to. 1412139f7f9bSDimitry Andric 1413139f7f9bSDimitry Andric AttrBuilder B; 1414139f7f9bSDimitry Andric for (unsigned i = 2, e = Record.size(); i != e; ++i) { 1415139f7f9bSDimitry Andric if (Record[i] == 0) { // Enum attribute 1416f785676fSDimitry Andric Attribute::AttrKind Kind; 1417d88c1a5aSDimitry Andric if (Error Err = parseAttrKind(Record[++i], &Kind)) 1418d88c1a5aSDimitry Andric return Err; 1419f785676fSDimitry Andric 1420f785676fSDimitry Andric B.addAttribute(Kind); 142191bc56edSDimitry Andric } else if (Record[i] == 1) { // Integer attribute 1422f785676fSDimitry Andric Attribute::AttrKind Kind; 1423d88c1a5aSDimitry Andric if (Error Err = parseAttrKind(Record[++i], &Kind)) 1424d88c1a5aSDimitry Andric return Err; 1425f785676fSDimitry Andric if (Kind == Attribute::Alignment) 1426139f7f9bSDimitry Andric B.addAlignmentAttr(Record[++i]); 142791bc56edSDimitry Andric else if (Kind == Attribute::StackAlignment) 1428139f7f9bSDimitry Andric B.addStackAlignmentAttr(Record[++i]); 142991bc56edSDimitry Andric else if (Kind == Attribute::Dereferenceable) 143091bc56edSDimitry Andric B.addDereferenceableAttr(Record[++i]); 1431ff0cc061SDimitry Andric else if (Kind == Attribute::DereferenceableOrNull) 1432ff0cc061SDimitry Andric B.addDereferenceableOrNullAttr(Record[++i]); 14333ca95b02SDimitry Andric else if (Kind == Attribute::AllocSize) 14343ca95b02SDimitry Andric B.addAllocSizeAttrFromRawRepr(Record[++i]); 1435139f7f9bSDimitry Andric } else { // String attribute 1436139f7f9bSDimitry Andric assert((Record[i] == 3 || Record[i] == 4) && 1437139f7f9bSDimitry Andric "Invalid attribute group entry"); 1438139f7f9bSDimitry Andric bool HasValue = (Record[i++] == 4); 1439139f7f9bSDimitry Andric SmallString<64> KindStr; 1440139f7f9bSDimitry Andric SmallString<64> ValStr; 1441139f7f9bSDimitry Andric 1442139f7f9bSDimitry Andric while (Record[i] != 0 && i != e) 1443139f7f9bSDimitry Andric KindStr += Record[i++]; 1444139f7f9bSDimitry Andric assert(Record[i] == 0 && "Kind string not null terminated"); 1445139f7f9bSDimitry Andric 1446139f7f9bSDimitry Andric if (HasValue) { 1447139f7f9bSDimitry Andric // Has a value associated with it. 1448139f7f9bSDimitry Andric ++i; // Skip the '0' that terminates the "kind" string. 1449139f7f9bSDimitry Andric while (Record[i] != 0 && i != e) 1450139f7f9bSDimitry Andric ValStr += Record[i++]; 1451139f7f9bSDimitry Andric assert(Record[i] == 0 && "Value string not null terminated"); 1452139f7f9bSDimitry Andric } 1453139f7f9bSDimitry Andric 1454139f7f9bSDimitry Andric B.addAttribute(KindStr.str(), ValStr.str()); 1455139f7f9bSDimitry Andric } 1456139f7f9bSDimitry Andric } 1457139f7f9bSDimitry Andric 14587a7e6055SDimitry Andric MAttributeGroups[GrpID] = AttributeList::get(Context, Idx, B); 1459139f7f9bSDimitry Andric break; 1460139f7f9bSDimitry Andric } 1461f22ef01cSRoman Divacky } 1462f22ef01cSRoman Divacky } 1463f22ef01cSRoman Divacky } 1464f22ef01cSRoman Divacky 1465d88c1a5aSDimitry Andric Error BitcodeReader::parseTypeTable() { 146617a519f9SDimitry Andric if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW)) 14678f0fd8f6SDimitry Andric return error("Invalid record"); 1468f22ef01cSRoman Divacky 14698f0fd8f6SDimitry Andric return parseTypeTableBody(); 147017a519f9SDimitry Andric } 147117a519f9SDimitry Andric 1472d88c1a5aSDimitry Andric Error BitcodeReader::parseTypeTableBody() { 1473f22ef01cSRoman Divacky if (!TypeList.empty()) 14748f0fd8f6SDimitry Andric return error("Invalid multiple blocks"); 1475f22ef01cSRoman Divacky 1476f22ef01cSRoman Divacky SmallVector<uint64_t, 64> Record; 1477f22ef01cSRoman Divacky unsigned NumRecords = 0; 1478f22ef01cSRoman Divacky 147917a519f9SDimitry Andric SmallString<64> TypeName; 148017a519f9SDimitry Andric 1481f22ef01cSRoman Divacky // Read all the records for this type table. 1482d88c1a5aSDimitry Andric while (true) { 1483139f7f9bSDimitry Andric BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 1484139f7f9bSDimitry Andric 1485139f7f9bSDimitry Andric switch (Entry.Kind) { 1486139f7f9bSDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already. 1487139f7f9bSDimitry Andric case BitstreamEntry::Error: 14888f0fd8f6SDimitry Andric return error("Malformed block"); 1489139f7f9bSDimitry Andric case BitstreamEntry::EndBlock: 1490f22ef01cSRoman Divacky if (NumRecords != TypeList.size()) 14918f0fd8f6SDimitry Andric return error("Malformed block"); 1492d88c1a5aSDimitry Andric return Error::success(); 1493139f7f9bSDimitry Andric case BitstreamEntry::Record: 1494139f7f9bSDimitry Andric // The interesting case. 1495139f7f9bSDimitry Andric break; 1496f22ef01cSRoman Divacky } 1497f22ef01cSRoman Divacky 1498f22ef01cSRoman Divacky // Read a record. 1499f22ef01cSRoman Divacky Record.clear(); 150091bc56edSDimitry Andric Type *ResultTy = nullptr; 1501139f7f9bSDimitry Andric switch (Stream.readRecord(Entry.ID, Record)) { 1502f785676fSDimitry Andric default: 15038f0fd8f6SDimitry Andric return error("Invalid value"); 1504f22ef01cSRoman Divacky case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries] 1505f22ef01cSRoman Divacky // TYPE_CODE_NUMENTRY contains a count of the number of types in the 1506f22ef01cSRoman Divacky // type list. This allows us to reserve space. 1507f22ef01cSRoman Divacky if (Record.size() < 1) 15088f0fd8f6SDimitry Andric return error("Invalid record"); 150917a519f9SDimitry Andric TypeList.resize(Record[0]); 1510f22ef01cSRoman Divacky continue; 1511f22ef01cSRoman Divacky case bitc::TYPE_CODE_VOID: // VOID 1512f22ef01cSRoman Divacky ResultTy = Type::getVoidTy(Context); 1513f22ef01cSRoman Divacky break; 1514dff0c46cSDimitry Andric case bitc::TYPE_CODE_HALF: // HALF 1515dff0c46cSDimitry Andric ResultTy = Type::getHalfTy(Context); 1516dff0c46cSDimitry Andric break; 1517f22ef01cSRoman Divacky case bitc::TYPE_CODE_FLOAT: // FLOAT 1518f22ef01cSRoman Divacky ResultTy = Type::getFloatTy(Context); 1519f22ef01cSRoman Divacky break; 1520f22ef01cSRoman Divacky case bitc::TYPE_CODE_DOUBLE: // DOUBLE 1521f22ef01cSRoman Divacky ResultTy = Type::getDoubleTy(Context); 1522f22ef01cSRoman Divacky break; 1523f22ef01cSRoman Divacky case bitc::TYPE_CODE_X86_FP80: // X86_FP80 1524f22ef01cSRoman Divacky ResultTy = Type::getX86_FP80Ty(Context); 1525f22ef01cSRoman Divacky break; 1526f22ef01cSRoman Divacky case bitc::TYPE_CODE_FP128: // FP128 1527f22ef01cSRoman Divacky ResultTy = Type::getFP128Ty(Context); 1528f22ef01cSRoman Divacky break; 1529f22ef01cSRoman Divacky case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128 1530f22ef01cSRoman Divacky ResultTy = Type::getPPC_FP128Ty(Context); 1531f22ef01cSRoman Divacky break; 1532f22ef01cSRoman Divacky case bitc::TYPE_CODE_LABEL: // LABEL 1533f22ef01cSRoman Divacky ResultTy = Type::getLabelTy(Context); 1534f22ef01cSRoman Divacky break; 1535f22ef01cSRoman Divacky case bitc::TYPE_CODE_METADATA: // METADATA 1536f22ef01cSRoman Divacky ResultTy = Type::getMetadataTy(Context); 1537f22ef01cSRoman Divacky break; 15382754fe60SDimitry Andric case bitc::TYPE_CODE_X86_MMX: // X86_MMX 15392754fe60SDimitry Andric ResultTy = Type::getX86_MMXTy(Context); 15402754fe60SDimitry Andric break; 15417d523365SDimitry Andric case bitc::TYPE_CODE_TOKEN: // TOKEN 15427d523365SDimitry Andric ResultTy = Type::getTokenTy(Context); 15437d523365SDimitry Andric break; 1544ff0cc061SDimitry Andric case bitc::TYPE_CODE_INTEGER: { // INTEGER: [width] 1545f22ef01cSRoman Divacky if (Record.size() < 1) 15468f0fd8f6SDimitry Andric return error("Invalid record"); 1547f22ef01cSRoman Divacky 1548ff0cc061SDimitry Andric uint64_t NumBits = Record[0]; 1549ff0cc061SDimitry Andric if (NumBits < IntegerType::MIN_INT_BITS || 1550ff0cc061SDimitry Andric NumBits > IntegerType::MAX_INT_BITS) 15518f0fd8f6SDimitry Andric return error("Bitwidth for integer type out of range"); 1552ff0cc061SDimitry Andric ResultTy = IntegerType::get(Context, NumBits); 1553f22ef01cSRoman Divacky break; 1554ff0cc061SDimitry Andric } 1555f22ef01cSRoman Divacky case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or 1556f22ef01cSRoman Divacky // [pointee type, address space] 1557f22ef01cSRoman Divacky if (Record.size() < 1) 15588f0fd8f6SDimitry Andric return error("Invalid record"); 1559f22ef01cSRoman Divacky unsigned AddressSpace = 0; 1560f22ef01cSRoman Divacky if (Record.size() == 2) 1561f22ef01cSRoman Divacky AddressSpace = Record[1]; 156217a519f9SDimitry Andric ResultTy = getTypeByID(Record[0]); 1563ff0cc061SDimitry Andric if (!ResultTy || 1564ff0cc061SDimitry Andric !PointerType::isValidElementType(ResultTy)) 15658f0fd8f6SDimitry Andric return error("Invalid type"); 156617a519f9SDimitry Andric ResultTy = PointerType::get(ResultTy, AddressSpace); 1567f22ef01cSRoman Divacky break; 1568f22ef01cSRoman Divacky } 1569dff0c46cSDimitry Andric case bitc::TYPE_CODE_FUNCTION_OLD: { 15707ae0e2c9SDimitry Andric // FIXME: attrid is dead, remove it in LLVM 4.0 1571f22ef01cSRoman Divacky // FUNCTION: [vararg, attrid, retty, paramty x N] 1572f22ef01cSRoman Divacky if (Record.size() < 3) 15738f0fd8f6SDimitry Andric return error("Invalid record"); 1574dff0c46cSDimitry Andric SmallVector<Type*, 8> ArgTys; 157517a519f9SDimitry Andric for (unsigned i = 3, e = Record.size(); i != e; ++i) { 157617a519f9SDimitry Andric if (Type *T = getTypeByID(Record[i])) 157717a519f9SDimitry Andric ArgTys.push_back(T); 157817a519f9SDimitry Andric else 1579f22ef01cSRoman Divacky break; 1580f22ef01cSRoman Divacky } 158117a519f9SDimitry Andric 158217a519f9SDimitry Andric ResultTy = getTypeByID(Record[2]); 158391bc56edSDimitry Andric if (!ResultTy || ArgTys.size() < Record.size()-3) 15848f0fd8f6SDimitry Andric return error("Invalid type"); 158517a519f9SDimitry Andric 158617a519f9SDimitry Andric ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]); 158717a519f9SDimitry Andric break; 158817a519f9SDimitry Andric } 1589dff0c46cSDimitry Andric case bitc::TYPE_CODE_FUNCTION: { 1590dff0c46cSDimitry Andric // FUNCTION: [vararg, retty, paramty x N] 1591dff0c46cSDimitry Andric if (Record.size() < 2) 15928f0fd8f6SDimitry Andric return error("Invalid record"); 1593dff0c46cSDimitry Andric SmallVector<Type*, 8> ArgTys; 1594dff0c46cSDimitry Andric for (unsigned i = 2, e = Record.size(); i != e; ++i) { 1595ff0cc061SDimitry Andric if (Type *T = getTypeByID(Record[i])) { 1596ff0cc061SDimitry Andric if (!FunctionType::isValidArgumentType(T)) 15978f0fd8f6SDimitry Andric return error("Invalid function argument type"); 1598dff0c46cSDimitry Andric ArgTys.push_back(T); 1599ff0cc061SDimitry Andric } 1600dff0c46cSDimitry Andric else 1601dff0c46cSDimitry Andric break; 1602dff0c46cSDimitry Andric } 1603dff0c46cSDimitry Andric 1604dff0c46cSDimitry Andric ResultTy = getTypeByID(Record[1]); 160591bc56edSDimitry Andric if (!ResultTy || ArgTys.size() < Record.size()-2) 16068f0fd8f6SDimitry Andric return error("Invalid type"); 1607dff0c46cSDimitry Andric 1608dff0c46cSDimitry Andric ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]); 1609dff0c46cSDimitry Andric break; 1610dff0c46cSDimitry Andric } 161117a519f9SDimitry Andric case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N] 1612f22ef01cSRoman Divacky if (Record.size() < 1) 16138f0fd8f6SDimitry Andric return error("Invalid record"); 1614dff0c46cSDimitry Andric SmallVector<Type*, 8> EltTys; 161517a519f9SDimitry Andric for (unsigned i = 1, e = Record.size(); i != e; ++i) { 161617a519f9SDimitry Andric if (Type *T = getTypeByID(Record[i])) 161717a519f9SDimitry Andric EltTys.push_back(T); 161817a519f9SDimitry Andric else 161917a519f9SDimitry Andric break; 162017a519f9SDimitry Andric } 162117a519f9SDimitry Andric if (EltTys.size() != Record.size()-1) 16228f0fd8f6SDimitry Andric return error("Invalid type"); 1623f22ef01cSRoman Divacky ResultTy = StructType::get(Context, EltTys, Record[0]); 1624f22ef01cSRoman Divacky break; 1625f22ef01cSRoman Divacky } 162617a519f9SDimitry Andric case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N] 16278f0fd8f6SDimitry Andric if (convertToString(Record, 0, TypeName)) 16288f0fd8f6SDimitry Andric return error("Invalid record"); 162917a519f9SDimitry Andric continue; 163017a519f9SDimitry Andric 163117a519f9SDimitry Andric case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N] 163217a519f9SDimitry Andric if (Record.size() < 1) 16338f0fd8f6SDimitry Andric return error("Invalid record"); 163417a519f9SDimitry Andric 163517a519f9SDimitry Andric if (NumRecords >= TypeList.size()) 16368f0fd8f6SDimitry Andric return error("Invalid TYPE table"); 163717a519f9SDimitry Andric 163817a519f9SDimitry Andric // Check to see if this was forward referenced, if so fill in the temp. 163917a519f9SDimitry Andric StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]); 164017a519f9SDimitry Andric if (Res) { 164117a519f9SDimitry Andric Res->setName(TypeName); 164291bc56edSDimitry Andric TypeList[NumRecords] = nullptr; 164317a519f9SDimitry Andric } else // Otherwise, create a new struct. 164439d628a0SDimitry Andric Res = createIdentifiedStructType(Context, TypeName); 164517a519f9SDimitry Andric TypeName.clear(); 164617a519f9SDimitry Andric 164717a519f9SDimitry Andric SmallVector<Type*, 8> EltTys; 164817a519f9SDimitry Andric for (unsigned i = 1, e = Record.size(); i != e; ++i) { 164917a519f9SDimitry Andric if (Type *T = getTypeByID(Record[i])) 165017a519f9SDimitry Andric EltTys.push_back(T); 165117a519f9SDimitry Andric else 165217a519f9SDimitry Andric break; 165317a519f9SDimitry Andric } 165417a519f9SDimitry Andric if (EltTys.size() != Record.size()-1) 16558f0fd8f6SDimitry Andric return error("Invalid record"); 165617a519f9SDimitry Andric Res->setBody(EltTys, Record[0]); 165717a519f9SDimitry Andric ResultTy = Res; 165817a519f9SDimitry Andric break; 165917a519f9SDimitry Andric } 166017a519f9SDimitry Andric case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: [] 166117a519f9SDimitry Andric if (Record.size() != 1) 16628f0fd8f6SDimitry Andric return error("Invalid record"); 166317a519f9SDimitry Andric 166417a519f9SDimitry Andric if (NumRecords >= TypeList.size()) 16658f0fd8f6SDimitry Andric return error("Invalid TYPE table"); 166617a519f9SDimitry Andric 166717a519f9SDimitry Andric // Check to see if this was forward referenced, if so fill in the temp. 166817a519f9SDimitry Andric StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]); 166917a519f9SDimitry Andric if (Res) { 167017a519f9SDimitry Andric Res->setName(TypeName); 167191bc56edSDimitry Andric TypeList[NumRecords] = nullptr; 167217a519f9SDimitry Andric } else // Otherwise, create a new struct with no body. 167339d628a0SDimitry Andric Res = createIdentifiedStructType(Context, TypeName); 167417a519f9SDimitry Andric TypeName.clear(); 167517a519f9SDimitry Andric ResultTy = Res; 167617a519f9SDimitry Andric break; 167717a519f9SDimitry Andric } 1678f22ef01cSRoman Divacky case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty] 1679f22ef01cSRoman Divacky if (Record.size() < 2) 16808f0fd8f6SDimitry Andric return error("Invalid record"); 1681ff0cc061SDimitry Andric ResultTy = getTypeByID(Record[1]); 1682ff0cc061SDimitry Andric if (!ResultTy || !ArrayType::isValidElementType(ResultTy)) 16838f0fd8f6SDimitry Andric return error("Invalid type"); 1684ff0cc061SDimitry Andric ResultTy = ArrayType::get(ResultTy, Record[0]); 1685f22ef01cSRoman Divacky break; 1686f22ef01cSRoman Divacky case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty] 1687f22ef01cSRoman Divacky if (Record.size() < 2) 16888f0fd8f6SDimitry Andric return error("Invalid record"); 168997bc6c73SDimitry Andric if (Record[0] == 0) 16908f0fd8f6SDimitry Andric return error("Invalid vector length"); 1691ff0cc061SDimitry Andric ResultTy = getTypeByID(Record[1]); 1692ff0cc061SDimitry Andric if (!ResultTy || !StructType::isValidElementType(ResultTy)) 16938f0fd8f6SDimitry Andric return error("Invalid type"); 1694ff0cc061SDimitry Andric ResultTy = VectorType::get(ResultTy, Record[0]); 1695f22ef01cSRoman Divacky break; 1696f22ef01cSRoman Divacky } 1697f22ef01cSRoman Divacky 169817a519f9SDimitry Andric if (NumRecords >= TypeList.size()) 16998f0fd8f6SDimitry Andric return error("Invalid TYPE table"); 1700ff0cc061SDimitry Andric if (TypeList[NumRecords]) 17018f0fd8f6SDimitry Andric return error( 1702ff0cc061SDimitry Andric "Invalid TYPE table: Only named structs can be forward referenced"); 170317a519f9SDimitry Andric assert(ResultTy && "Didn't read a type?"); 170417a519f9SDimitry Andric TypeList[NumRecords++] = ResultTy; 1705f22ef01cSRoman Divacky } 1706f22ef01cSRoman Divacky } 170717a519f9SDimitry Andric 1708d88c1a5aSDimitry Andric Error BitcodeReader::parseOperandBundleTags() { 17097d523365SDimitry Andric if (Stream.EnterSubBlock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID)) 17107d523365SDimitry Andric return error("Invalid record"); 17117d523365SDimitry Andric 17127d523365SDimitry Andric if (!BundleTags.empty()) 17137d523365SDimitry Andric return error("Invalid multiple blocks"); 17147d523365SDimitry Andric 17157d523365SDimitry Andric SmallVector<uint64_t, 64> Record; 17167d523365SDimitry Andric 1717d88c1a5aSDimitry Andric while (true) { 17187d523365SDimitry Andric BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 17197d523365SDimitry Andric 17207d523365SDimitry Andric switch (Entry.Kind) { 17217d523365SDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already. 17227d523365SDimitry Andric case BitstreamEntry::Error: 17237d523365SDimitry Andric return error("Malformed block"); 17247d523365SDimitry Andric case BitstreamEntry::EndBlock: 1725d88c1a5aSDimitry Andric return Error::success(); 17267d523365SDimitry Andric case BitstreamEntry::Record: 17277d523365SDimitry Andric // The interesting case. 17287d523365SDimitry Andric break; 17297d523365SDimitry Andric } 17307d523365SDimitry Andric 17317d523365SDimitry Andric // Tags are implicitly mapped to integers by their order. 17327d523365SDimitry Andric 17337d523365SDimitry Andric if (Stream.readRecord(Entry.ID, Record) != bitc::OPERAND_BUNDLE_TAG) 17347d523365SDimitry Andric return error("Invalid record"); 17357d523365SDimitry Andric 17367d523365SDimitry Andric // OPERAND_BUNDLE_TAG: [strchr x N] 17377d523365SDimitry Andric BundleTags.emplace_back(); 17387d523365SDimitry Andric if (convertToString(Record, 0, BundleTags.back())) 17397d523365SDimitry Andric return error("Invalid record"); 17407d523365SDimitry Andric Record.clear(); 17417d523365SDimitry Andric } 17427d523365SDimitry Andric } 17437d523365SDimitry Andric 1744c4394386SDimitry Andric Error BitcodeReader::parseSyncScopeNames() { 1745c4394386SDimitry Andric if (Stream.EnterSubBlock(bitc::SYNC_SCOPE_NAMES_BLOCK_ID)) 1746c4394386SDimitry Andric return error("Invalid record"); 1747c4394386SDimitry Andric 1748c4394386SDimitry Andric if (!SSIDs.empty()) 1749c4394386SDimitry Andric return error("Invalid multiple synchronization scope names blocks"); 1750c4394386SDimitry Andric 1751c4394386SDimitry Andric SmallVector<uint64_t, 64> Record; 1752c4394386SDimitry Andric while (true) { 1753c4394386SDimitry Andric BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 1754c4394386SDimitry Andric switch (Entry.Kind) { 1755c4394386SDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already. 1756c4394386SDimitry Andric case BitstreamEntry::Error: 1757c4394386SDimitry Andric return error("Malformed block"); 1758c4394386SDimitry Andric case BitstreamEntry::EndBlock: 1759c4394386SDimitry Andric if (SSIDs.empty()) 1760c4394386SDimitry Andric return error("Invalid empty synchronization scope names block"); 1761c4394386SDimitry Andric return Error::success(); 1762c4394386SDimitry Andric case BitstreamEntry::Record: 1763c4394386SDimitry Andric // The interesting case. 1764c4394386SDimitry Andric break; 1765c4394386SDimitry Andric } 1766c4394386SDimitry Andric 1767c4394386SDimitry Andric // Synchronization scope names are implicitly mapped to synchronization 1768c4394386SDimitry Andric // scope IDs by their order. 1769c4394386SDimitry Andric 1770c4394386SDimitry Andric if (Stream.readRecord(Entry.ID, Record) != bitc::SYNC_SCOPE_NAME) 1771c4394386SDimitry Andric return error("Invalid record"); 1772c4394386SDimitry Andric 1773c4394386SDimitry Andric SmallString<16> SSN; 1774c4394386SDimitry Andric if (convertToString(Record, 0, SSN)) 1775c4394386SDimitry Andric return error("Invalid record"); 1776c4394386SDimitry Andric 1777c4394386SDimitry Andric SSIDs.push_back(Context.getOrInsertSyncScopeID(SSN)); 1778c4394386SDimitry Andric Record.clear(); 1779c4394386SDimitry Andric } 1780c4394386SDimitry Andric } 1781c4394386SDimitry Andric 17827d523365SDimitry Andric /// Associate a value with its name from the given index in the provided record. 1783d88c1a5aSDimitry Andric Expected<Value *> BitcodeReader::recordValue(SmallVectorImpl<uint64_t> &Record, 17847d523365SDimitry Andric unsigned NameIndex, Triple &TT) { 17857d523365SDimitry Andric SmallString<128> ValueName; 17867d523365SDimitry Andric if (convertToString(Record, NameIndex, ValueName)) 17877d523365SDimitry Andric return error("Invalid record"); 17887d523365SDimitry Andric unsigned ValueID = Record[0]; 17897d523365SDimitry Andric if (ValueID >= ValueList.size() || !ValueList[ValueID]) 17907d523365SDimitry Andric return error("Invalid record"); 17917d523365SDimitry Andric Value *V = ValueList[ValueID]; 17927d523365SDimitry Andric 17937d523365SDimitry Andric StringRef NameStr(ValueName.data(), ValueName.size()); 17947d523365SDimitry Andric if (NameStr.find_first_of(0) != StringRef::npos) 17957d523365SDimitry Andric return error("Invalid value name"); 17967d523365SDimitry Andric V->setName(NameStr); 17977d523365SDimitry Andric auto *GO = dyn_cast<GlobalObject>(V); 17987d523365SDimitry Andric if (GO) { 17997d523365SDimitry Andric if (GO->getComdat() == reinterpret_cast<Comdat *>(1)) { 18007d523365SDimitry Andric if (TT.isOSBinFormatMachO()) 18017d523365SDimitry Andric GO->setComdat(nullptr); 18027d523365SDimitry Andric else 18037d523365SDimitry Andric GO->setComdat(TheModule->getOrInsertComdat(V->getName())); 18047d523365SDimitry Andric } 18057d523365SDimitry Andric } 18067d523365SDimitry Andric return V; 18077d523365SDimitry Andric } 18087d523365SDimitry Andric 18093ca95b02SDimitry Andric /// Helper to note and return the current location, and jump to the given 18103ca95b02SDimitry Andric /// offset. 18113ca95b02SDimitry Andric static uint64_t jumpToValueSymbolTable(uint64_t Offset, 18123ca95b02SDimitry Andric BitstreamCursor &Stream) { 18137d523365SDimitry Andric // Save the current parsing location so we can jump back at the end 18147d523365SDimitry Andric // of the VST read. 18153ca95b02SDimitry Andric uint64_t CurrentBit = Stream.GetCurrentBitNo(); 18167d523365SDimitry Andric Stream.JumpToBit(Offset * 32); 18177d523365SDimitry Andric #ifndef NDEBUG 18187d523365SDimitry Andric // Do some checking if we are in debug mode. 18197d523365SDimitry Andric BitstreamEntry Entry = Stream.advance(); 18207d523365SDimitry Andric assert(Entry.Kind == BitstreamEntry::SubBlock); 18217d523365SDimitry Andric assert(Entry.ID == bitc::VALUE_SYMTAB_BLOCK_ID); 18227d523365SDimitry Andric #else 18237d523365SDimitry Andric // In NDEBUG mode ignore the output so we don't get an unused variable 18247d523365SDimitry Andric // warning. 18257d523365SDimitry Andric Stream.advance(); 18267d523365SDimitry Andric #endif 18273ca95b02SDimitry Andric return CurrentBit; 18287d523365SDimitry Andric } 18297d523365SDimitry Andric 18306bc11b14SDimitry Andric void BitcodeReader::setDeferredFunctionInfo(unsigned FuncBitcodeOffsetDelta, 18316bc11b14SDimitry Andric Function *F, 18326bc11b14SDimitry Andric ArrayRef<uint64_t> Record) { 18336bc11b14SDimitry Andric // Note that we subtract 1 here because the offset is relative to one word 18346bc11b14SDimitry Andric // before the start of the identification or module block, which was 18356bc11b14SDimitry Andric // historically always the start of the regular bitcode header. 18366bc11b14SDimitry Andric uint64_t FuncWordOffset = Record[1] - 1; 18376bc11b14SDimitry Andric uint64_t FuncBitOffset = FuncWordOffset * 32; 18386bc11b14SDimitry Andric DeferredFunctionInfo[F] = FuncBitOffset + FuncBitcodeOffsetDelta; 18396bc11b14SDimitry Andric // Set the LastFunctionBlockBit to point to the last function block. 18406bc11b14SDimitry Andric // Later when parsing is resumed after function materialization, 18416bc11b14SDimitry Andric // we can simply skip that last function block. 18426bc11b14SDimitry Andric if (FuncBitOffset > LastFunctionBlockBit) 18436bc11b14SDimitry Andric LastFunctionBlockBit = FuncBitOffset; 18446bc11b14SDimitry Andric } 18456bc11b14SDimitry Andric 18466bc11b14SDimitry Andric /// Read a new-style GlobalValue symbol table. 18476bc11b14SDimitry Andric Error BitcodeReader::parseGlobalValueSymbolTable() { 18486bc11b14SDimitry Andric unsigned FuncBitcodeOffsetDelta = 18496bc11b14SDimitry Andric Stream.getAbbrevIDWidth() + bitc::BlockIDWidth; 18506bc11b14SDimitry Andric 18516bc11b14SDimitry Andric if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID)) 18526bc11b14SDimitry Andric return error("Invalid record"); 18536bc11b14SDimitry Andric 18546bc11b14SDimitry Andric SmallVector<uint64_t, 64> Record; 18556bc11b14SDimitry Andric while (true) { 18566bc11b14SDimitry Andric BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 18576bc11b14SDimitry Andric 18586bc11b14SDimitry Andric switch (Entry.Kind) { 18596bc11b14SDimitry Andric case BitstreamEntry::SubBlock: 18606bc11b14SDimitry Andric case BitstreamEntry::Error: 18616bc11b14SDimitry Andric return error("Malformed block"); 18626bc11b14SDimitry Andric case BitstreamEntry::EndBlock: 18636bc11b14SDimitry Andric return Error::success(); 18646bc11b14SDimitry Andric case BitstreamEntry::Record: 18656bc11b14SDimitry Andric break; 18666bc11b14SDimitry Andric } 18676bc11b14SDimitry Andric 18686bc11b14SDimitry Andric Record.clear(); 18696bc11b14SDimitry Andric switch (Stream.readRecord(Entry.ID, Record)) { 18706bc11b14SDimitry Andric case bitc::VST_CODE_FNENTRY: // [valueid, offset] 18716bc11b14SDimitry Andric setDeferredFunctionInfo(FuncBitcodeOffsetDelta, 18726bc11b14SDimitry Andric cast<Function>(ValueList[Record[0]]), Record); 18736bc11b14SDimitry Andric break; 18746bc11b14SDimitry Andric } 18756bc11b14SDimitry Andric } 18766bc11b14SDimitry Andric } 18776bc11b14SDimitry Andric 18783ca95b02SDimitry Andric /// Parse the value symbol table at either the current parsing location or 18793ca95b02SDimitry Andric /// at the given bit offset if provided. 1880d88c1a5aSDimitry Andric Error BitcodeReader::parseValueSymbolTable(uint64_t Offset) { 18813ca95b02SDimitry Andric uint64_t CurrentBit; 18823ca95b02SDimitry Andric // Pass in the Offset to distinguish between calling for the module-level 18833ca95b02SDimitry Andric // VST (where we want to jump to the VST offset) and the function-level 18843ca95b02SDimitry Andric // VST (where we don't). 18856bc11b14SDimitry Andric if (Offset > 0) { 18863ca95b02SDimitry Andric CurrentBit = jumpToValueSymbolTable(Offset, Stream); 18876bc11b14SDimitry Andric // If this module uses a string table, read this as a module-level VST. 18886bc11b14SDimitry Andric if (UseStrtab) { 18896bc11b14SDimitry Andric if (Error Err = parseGlobalValueSymbolTable()) 18906bc11b14SDimitry Andric return Err; 18916bc11b14SDimitry Andric Stream.JumpToBit(CurrentBit); 18926bc11b14SDimitry Andric return Error::success(); 18936bc11b14SDimitry Andric } 18946bc11b14SDimitry Andric // Otherwise, the VST will be in a similar format to a function-level VST, 18956bc11b14SDimitry Andric // and will contain symbol names. 18966bc11b14SDimitry Andric } 18973ca95b02SDimitry Andric 18987d523365SDimitry Andric // Compute the delta between the bitcode indices in the VST (the word offset 18997d523365SDimitry Andric // to the word-aligned ENTER_SUBBLOCK for the function block, and that 19007d523365SDimitry Andric // expected by the lazy reader. The reader's EnterSubBlock expects to have 19017d523365SDimitry Andric // already read the ENTER_SUBBLOCK code (size getAbbrevIDWidth) and BlockID 19027d523365SDimitry Andric // (size BlockIDWidth). Note that we access the stream's AbbrevID width here 19037d523365SDimitry Andric // just before entering the VST subblock because: 1) the EnterSubBlock 19047d523365SDimitry Andric // changes the AbbrevID width; 2) the VST block is nested within the same 19057d523365SDimitry Andric // outer MODULE_BLOCK as the FUNCTION_BLOCKs and therefore have the same 19067d523365SDimitry Andric // AbbrevID width before calling EnterSubBlock; and 3) when we want to 19077d523365SDimitry Andric // jump to the FUNCTION_BLOCK using this offset later, we don't want 19087d523365SDimitry Andric // to rely on the stream's AbbrevID width being that of the MODULE_BLOCK. 19097d523365SDimitry Andric unsigned FuncBitcodeOffsetDelta = 19107d523365SDimitry Andric Stream.getAbbrevIDWidth() + bitc::BlockIDWidth; 19117d523365SDimitry Andric 1912f22ef01cSRoman Divacky if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID)) 19138f0fd8f6SDimitry Andric return error("Invalid record"); 1914f22ef01cSRoman Divacky 1915f22ef01cSRoman Divacky SmallVector<uint64_t, 64> Record; 1916f22ef01cSRoman Divacky 1917ff0cc061SDimitry Andric Triple TT(TheModule->getTargetTriple()); 1918ff0cc061SDimitry Andric 1919f22ef01cSRoman Divacky // Read all the records for this value table. 1920f22ef01cSRoman Divacky SmallString<128> ValueName; 1921d88c1a5aSDimitry Andric 1922d88c1a5aSDimitry Andric while (true) { 1923139f7f9bSDimitry Andric BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 1924f22ef01cSRoman Divacky 1925139f7f9bSDimitry Andric switch (Entry.Kind) { 1926139f7f9bSDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already. 1927139f7f9bSDimitry Andric case BitstreamEntry::Error: 19288f0fd8f6SDimitry Andric return error("Malformed block"); 1929139f7f9bSDimitry Andric case BitstreamEntry::EndBlock: 19307d523365SDimitry Andric if (Offset > 0) 19317d523365SDimitry Andric Stream.JumpToBit(CurrentBit); 1932d88c1a5aSDimitry Andric return Error::success(); 1933139f7f9bSDimitry Andric case BitstreamEntry::Record: 1934139f7f9bSDimitry Andric // The interesting case. 1935139f7f9bSDimitry Andric break; 1936f22ef01cSRoman Divacky } 1937f22ef01cSRoman Divacky 1938f22ef01cSRoman Divacky // Read a record. 1939f22ef01cSRoman Divacky Record.clear(); 1940139f7f9bSDimitry Andric switch (Stream.readRecord(Entry.ID, Record)) { 1941f22ef01cSRoman Divacky default: // Default behavior: unknown type. 1942f22ef01cSRoman Divacky break; 19433ca95b02SDimitry Andric case bitc::VST_CODE_ENTRY: { // VST_CODE_ENTRY: [valueid, namechar x N] 1944d88c1a5aSDimitry Andric Expected<Value *> ValOrErr = recordValue(Record, 1, TT); 1945d88c1a5aSDimitry Andric if (Error Err = ValOrErr.takeError()) 1946d88c1a5aSDimitry Andric return Err; 19477d523365SDimitry Andric ValOrErr.get(); 19487d523365SDimitry Andric break; 19497d523365SDimitry Andric } 19507d523365SDimitry Andric case bitc::VST_CODE_FNENTRY: { 19513ca95b02SDimitry Andric // VST_CODE_FNENTRY: [valueid, offset, namechar x N] 1952d88c1a5aSDimitry Andric Expected<Value *> ValOrErr = recordValue(Record, 2, TT); 1953d88c1a5aSDimitry Andric if (Error Err = ValOrErr.takeError()) 1954d88c1a5aSDimitry Andric return Err; 19557d523365SDimitry Andric Value *V = ValOrErr.get(); 1956f22ef01cSRoman Divacky 19577a7e6055SDimitry Andric // Ignore function offsets emitted for aliases of functions in older 19587a7e6055SDimitry Andric // versions of LLVM. 19596bc11b14SDimitry Andric if (auto *F = dyn_cast<Function>(V)) 19606bc11b14SDimitry Andric setDeferredFunctionInfo(FuncBitcodeOffsetDelta, F, Record); 1961f22ef01cSRoman Divacky break; 1962f22ef01cSRoman Divacky } 1963f22ef01cSRoman Divacky case bitc::VST_CODE_BBENTRY: { 19648f0fd8f6SDimitry Andric if (convertToString(Record, 1, ValueName)) 19658f0fd8f6SDimitry Andric return error("Invalid record"); 1966f22ef01cSRoman Divacky BasicBlock *BB = getBasicBlock(Record[0]); 196791bc56edSDimitry Andric if (!BB) 19688f0fd8f6SDimitry Andric return error("Invalid record"); 1969f22ef01cSRoman Divacky 1970f22ef01cSRoman Divacky BB->setName(StringRef(ValueName.data(), ValueName.size())); 1971f22ef01cSRoman Divacky ValueName.clear(); 1972f22ef01cSRoman Divacky break; 1973f22ef01cSRoman Divacky } 1974f22ef01cSRoman Divacky } 1975f22ef01cSRoman Divacky } 1976f22ef01cSRoman Divacky } 1977f22ef01cSRoman Divacky 19788f0fd8f6SDimitry Andric /// Decode a signed value stored with the sign bit in the LSB for dense VBR 19798f0fd8f6SDimitry Andric /// encoding. 19803861d79fSDimitry Andric uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) { 1981f22ef01cSRoman Divacky if ((V & 1) == 0) 1982f22ef01cSRoman Divacky return V >> 1; 1983f22ef01cSRoman Divacky if (V != 1) 1984f22ef01cSRoman Divacky return -(V >> 1); 1985f22ef01cSRoman Divacky // There is no such thing as -0 with integers. "-0" really means MININT. 1986f22ef01cSRoman Divacky return 1ULL << 63; 1987f22ef01cSRoman Divacky } 1988f22ef01cSRoman Divacky 19898f0fd8f6SDimitry Andric /// Resolve all of the initializers for global values and aliases that we can. 1990d88c1a5aSDimitry Andric Error BitcodeReader::resolveGlobalAndIndirectSymbolInits() { 1991f22ef01cSRoman Divacky std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist; 19923ca95b02SDimitry Andric std::vector<std::pair<GlobalIndirectSymbol*, unsigned> > 19933ca95b02SDimitry Andric IndirectSymbolInitWorklist; 1994f785676fSDimitry Andric std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist; 199539d628a0SDimitry Andric std::vector<std::pair<Function*, unsigned> > FunctionPrologueWorklist; 19968f0fd8f6SDimitry Andric std::vector<std::pair<Function*, unsigned> > FunctionPersonalityFnWorklist; 1997f22ef01cSRoman Divacky 1998f22ef01cSRoman Divacky GlobalInitWorklist.swap(GlobalInits); 19993ca95b02SDimitry Andric IndirectSymbolInitWorklist.swap(IndirectSymbolInits); 2000f785676fSDimitry Andric FunctionPrefixWorklist.swap(FunctionPrefixes); 200139d628a0SDimitry Andric FunctionPrologueWorklist.swap(FunctionPrologues); 20028f0fd8f6SDimitry Andric FunctionPersonalityFnWorklist.swap(FunctionPersonalityFns); 2003f22ef01cSRoman Divacky 2004f22ef01cSRoman Divacky while (!GlobalInitWorklist.empty()) { 2005f22ef01cSRoman Divacky unsigned ValID = GlobalInitWorklist.back().second; 2006f22ef01cSRoman Divacky if (ValID >= ValueList.size()) { 2007f22ef01cSRoman Divacky // Not ready to resolve this yet, it requires something later in the file. 2008f22ef01cSRoman Divacky GlobalInits.push_back(GlobalInitWorklist.back()); 2009f22ef01cSRoman Divacky } else { 201091bc56edSDimitry Andric if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID])) 2011f22ef01cSRoman Divacky GlobalInitWorklist.back().first->setInitializer(C); 2012f22ef01cSRoman Divacky else 20138f0fd8f6SDimitry Andric return error("Expected a constant"); 2014f22ef01cSRoman Divacky } 2015f22ef01cSRoman Divacky GlobalInitWorklist.pop_back(); 2016f22ef01cSRoman Divacky } 2017f22ef01cSRoman Divacky 20183ca95b02SDimitry Andric while (!IndirectSymbolInitWorklist.empty()) { 20193ca95b02SDimitry Andric unsigned ValID = IndirectSymbolInitWorklist.back().second; 2020f22ef01cSRoman Divacky if (ValID >= ValueList.size()) { 20213ca95b02SDimitry Andric IndirectSymbolInits.push_back(IndirectSymbolInitWorklist.back()); 2022f22ef01cSRoman Divacky } else { 202397bc6c73SDimitry Andric Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]); 202497bc6c73SDimitry Andric if (!C) 20258f0fd8f6SDimitry Andric return error("Expected a constant"); 20263ca95b02SDimitry Andric GlobalIndirectSymbol *GIS = IndirectSymbolInitWorklist.back().first; 20273ca95b02SDimitry Andric if (isa<GlobalAlias>(GIS) && C->getType() != GIS->getType()) 20288f0fd8f6SDimitry Andric return error("Alias and aliasee types don't match"); 20293ca95b02SDimitry Andric GIS->setIndirectSymbol(C); 2030f22ef01cSRoman Divacky } 20313ca95b02SDimitry Andric IndirectSymbolInitWorklist.pop_back(); 2032f22ef01cSRoman Divacky } 2033f785676fSDimitry Andric 2034f785676fSDimitry Andric while (!FunctionPrefixWorklist.empty()) { 2035f785676fSDimitry Andric unsigned ValID = FunctionPrefixWorklist.back().second; 2036f785676fSDimitry Andric if (ValID >= ValueList.size()) { 2037f785676fSDimitry Andric FunctionPrefixes.push_back(FunctionPrefixWorklist.back()); 2038f785676fSDimitry Andric } else { 203991bc56edSDimitry Andric if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID])) 2040f785676fSDimitry Andric FunctionPrefixWorklist.back().first->setPrefixData(C); 2041f785676fSDimitry Andric else 20428f0fd8f6SDimitry Andric return error("Expected a constant"); 2043f785676fSDimitry Andric } 2044f785676fSDimitry Andric FunctionPrefixWorklist.pop_back(); 2045f785676fSDimitry Andric } 2046f785676fSDimitry Andric 204739d628a0SDimitry Andric while (!FunctionPrologueWorklist.empty()) { 204839d628a0SDimitry Andric unsigned ValID = FunctionPrologueWorklist.back().second; 204939d628a0SDimitry Andric if (ValID >= ValueList.size()) { 205039d628a0SDimitry Andric FunctionPrologues.push_back(FunctionPrologueWorklist.back()); 205139d628a0SDimitry Andric } else { 205239d628a0SDimitry Andric if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID])) 205339d628a0SDimitry Andric FunctionPrologueWorklist.back().first->setPrologueData(C); 205439d628a0SDimitry Andric else 20558f0fd8f6SDimitry Andric return error("Expected a constant"); 205639d628a0SDimitry Andric } 205739d628a0SDimitry Andric FunctionPrologueWorklist.pop_back(); 205839d628a0SDimitry Andric } 205939d628a0SDimitry Andric 20608f0fd8f6SDimitry Andric while (!FunctionPersonalityFnWorklist.empty()) { 20618f0fd8f6SDimitry Andric unsigned ValID = FunctionPersonalityFnWorklist.back().second; 20628f0fd8f6SDimitry Andric if (ValID >= ValueList.size()) { 20638f0fd8f6SDimitry Andric FunctionPersonalityFns.push_back(FunctionPersonalityFnWorklist.back()); 20648f0fd8f6SDimitry Andric } else { 20658f0fd8f6SDimitry Andric if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID])) 20668f0fd8f6SDimitry Andric FunctionPersonalityFnWorklist.back().first->setPersonalityFn(C); 20678f0fd8f6SDimitry Andric else 20688f0fd8f6SDimitry Andric return error("Expected a constant"); 20698f0fd8f6SDimitry Andric } 20708f0fd8f6SDimitry Andric FunctionPersonalityFnWorklist.pop_back(); 20718f0fd8f6SDimitry Andric } 20728f0fd8f6SDimitry Andric 2073d88c1a5aSDimitry Andric return Error::success(); 2074f22ef01cSRoman Divacky } 2075f22ef01cSRoman Divacky 20768f0fd8f6SDimitry Andric static APInt readWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) { 20777ae0e2c9SDimitry Andric SmallVector<uint64_t, 8> Words(Vals.size()); 2078d88c1a5aSDimitry Andric transform(Vals, Words.begin(), 20793861d79fSDimitry Andric BitcodeReader::decodeSignRotatedValue); 20807ae0e2c9SDimitry Andric 20817ae0e2c9SDimitry Andric return APInt(TypeBits, Words); 20827ae0e2c9SDimitry Andric } 20837ae0e2c9SDimitry Andric 2084d88c1a5aSDimitry Andric Error BitcodeReader::parseConstants() { 2085f22ef01cSRoman Divacky if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID)) 20868f0fd8f6SDimitry Andric return error("Invalid record"); 2087f22ef01cSRoman Divacky 2088f22ef01cSRoman Divacky SmallVector<uint64_t, 64> Record; 2089f22ef01cSRoman Divacky 2090f22ef01cSRoman Divacky // Read all the records for this value table. 20916122f3e6SDimitry Andric Type *CurTy = Type::getInt32Ty(Context); 2092f22ef01cSRoman Divacky unsigned NextCstNo = ValueList.size(); 2093d88c1a5aSDimitry Andric 2094d88c1a5aSDimitry Andric while (true) { 2095139f7f9bSDimitry Andric BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 2096139f7f9bSDimitry Andric 2097139f7f9bSDimitry Andric switch (Entry.Kind) { 2098139f7f9bSDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already. 2099139f7f9bSDimitry Andric case BitstreamEntry::Error: 21008f0fd8f6SDimitry Andric return error("Malformed block"); 2101139f7f9bSDimitry Andric case BitstreamEntry::EndBlock: 2102139f7f9bSDimitry Andric if (NextCstNo != ValueList.size()) 21033ca95b02SDimitry Andric return error("Invalid constant reference"); 2104139f7f9bSDimitry Andric 2105139f7f9bSDimitry Andric // Once all the constants have been read, go through and resolve forward 2106139f7f9bSDimitry Andric // references. 21078f0fd8f6SDimitry Andric ValueList.resolveConstantForwardRefs(); 2108d88c1a5aSDimitry Andric return Error::success(); 2109139f7f9bSDimitry Andric case BitstreamEntry::Record: 2110139f7f9bSDimitry Andric // The interesting case. 2111f22ef01cSRoman Divacky break; 2112f22ef01cSRoman Divacky } 2113f22ef01cSRoman Divacky 2114f22ef01cSRoman Divacky // Read a record. 2115f22ef01cSRoman Divacky Record.clear(); 21163ca95b02SDimitry Andric Type *VoidType = Type::getVoidTy(Context); 211791bc56edSDimitry Andric Value *V = nullptr; 2118139f7f9bSDimitry Andric unsigned BitCode = Stream.readRecord(Entry.ID, Record); 2119f22ef01cSRoman Divacky switch (BitCode) { 2120f22ef01cSRoman Divacky default: // Default behavior: unknown constant 2121f22ef01cSRoman Divacky case bitc::CST_CODE_UNDEF: // UNDEF 2122f22ef01cSRoman Divacky V = UndefValue::get(CurTy); 2123f22ef01cSRoman Divacky break; 2124f22ef01cSRoman Divacky case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid] 2125f22ef01cSRoman Divacky if (Record.empty()) 21268f0fd8f6SDimitry Andric return error("Invalid record"); 212791bc56edSDimitry Andric if (Record[0] >= TypeList.size() || !TypeList[Record[0]]) 21288f0fd8f6SDimitry Andric return error("Invalid record"); 21293ca95b02SDimitry Andric if (TypeList[Record[0]] == VoidType) 21303ca95b02SDimitry Andric return error("Invalid constant type"); 2131f22ef01cSRoman Divacky CurTy = TypeList[Record[0]]; 2132f22ef01cSRoman Divacky continue; // Skip the ValueList manipulation. 2133f22ef01cSRoman Divacky case bitc::CST_CODE_NULL: // NULL 2134f22ef01cSRoman Divacky V = Constant::getNullValue(CurTy); 2135f22ef01cSRoman Divacky break; 2136f22ef01cSRoman Divacky case bitc::CST_CODE_INTEGER: // INTEGER: [intval] 2137f22ef01cSRoman Divacky if (!CurTy->isIntegerTy() || Record.empty()) 21388f0fd8f6SDimitry Andric return error("Invalid record"); 21393861d79fSDimitry Andric V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0])); 2140f22ef01cSRoman Divacky break; 2141f22ef01cSRoman Divacky case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval] 2142f22ef01cSRoman Divacky if (!CurTy->isIntegerTy() || Record.empty()) 21438f0fd8f6SDimitry Andric return error("Invalid record"); 2144f22ef01cSRoman Divacky 21458f0fd8f6SDimitry Andric APInt VInt = 21468f0fd8f6SDimitry Andric readWideAPInt(Record, cast<IntegerType>(CurTy)->getBitWidth()); 21477ae0e2c9SDimitry Andric V = ConstantInt::get(Context, VInt); 21487ae0e2c9SDimitry Andric 2149f22ef01cSRoman Divacky break; 2150f22ef01cSRoman Divacky } 2151f22ef01cSRoman Divacky case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval] 2152f22ef01cSRoman Divacky if (Record.empty()) 21538f0fd8f6SDimitry Andric return error("Invalid record"); 2154dff0c46cSDimitry Andric if (CurTy->isHalfTy()) 2155d88c1a5aSDimitry Andric V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf(), 2156139f7f9bSDimitry Andric APInt(16, (uint16_t)Record[0]))); 2157dff0c46cSDimitry Andric else if (CurTy->isFloatTy()) 2158d88c1a5aSDimitry Andric V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle(), 2159139f7f9bSDimitry Andric APInt(32, (uint32_t)Record[0]))); 2160f22ef01cSRoman Divacky else if (CurTy->isDoubleTy()) 2161d88c1a5aSDimitry Andric V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble(), 2162139f7f9bSDimitry Andric APInt(64, Record[0]))); 2163f22ef01cSRoman Divacky else if (CurTy->isX86_FP80Ty()) { 2164f22ef01cSRoman Divacky // Bits are not stored the same way as a normal i80 APInt, compensate. 2165f22ef01cSRoman Divacky uint64_t Rearrange[2]; 2166f22ef01cSRoman Divacky Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16); 2167f22ef01cSRoman Divacky Rearrange[1] = Record[0] >> 48; 2168d88c1a5aSDimitry Andric V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended(), 2169139f7f9bSDimitry Andric APInt(80, Rearrange))); 2170f22ef01cSRoman Divacky } else if (CurTy->isFP128Ty()) 2171d88c1a5aSDimitry Andric V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad(), 2172139f7f9bSDimitry Andric APInt(128, Record))); 2173f22ef01cSRoman Divacky else if (CurTy->isPPC_FP128Ty()) 2174d88c1a5aSDimitry Andric V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble(), 2175139f7f9bSDimitry Andric APInt(128, Record))); 2176f22ef01cSRoman Divacky else 2177f22ef01cSRoman Divacky V = UndefValue::get(CurTy); 2178f22ef01cSRoman Divacky break; 2179f22ef01cSRoman Divacky } 2180f22ef01cSRoman Divacky 2181f22ef01cSRoman Divacky case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number] 2182f22ef01cSRoman Divacky if (Record.empty()) 21838f0fd8f6SDimitry Andric return error("Invalid record"); 2184f22ef01cSRoman Divacky 2185f22ef01cSRoman Divacky unsigned Size = Record.size(); 2186dff0c46cSDimitry Andric SmallVector<Constant*, 16> Elts; 2187f22ef01cSRoman Divacky 21886122f3e6SDimitry Andric if (StructType *STy = dyn_cast<StructType>(CurTy)) { 2189f22ef01cSRoman Divacky for (unsigned i = 0; i != Size; ++i) 2190f22ef01cSRoman Divacky Elts.push_back(ValueList.getConstantFwdRef(Record[i], 2191f22ef01cSRoman Divacky STy->getElementType(i))); 2192f22ef01cSRoman Divacky V = ConstantStruct::get(STy, Elts); 21936122f3e6SDimitry Andric } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) { 21946122f3e6SDimitry Andric Type *EltTy = ATy->getElementType(); 2195f22ef01cSRoman Divacky for (unsigned i = 0; i != Size; ++i) 2196f22ef01cSRoman Divacky Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy)); 2197f22ef01cSRoman Divacky V = ConstantArray::get(ATy, Elts); 21986122f3e6SDimitry Andric } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) { 21996122f3e6SDimitry Andric Type *EltTy = VTy->getElementType(); 2200f22ef01cSRoman Divacky for (unsigned i = 0; i != Size; ++i) 2201f22ef01cSRoman Divacky Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy)); 2202f22ef01cSRoman Divacky V = ConstantVector::get(Elts); 2203f22ef01cSRoman Divacky } else { 2204f22ef01cSRoman Divacky V = UndefValue::get(CurTy); 2205f22ef01cSRoman Divacky } 2206f22ef01cSRoman Divacky break; 2207f22ef01cSRoman Divacky } 2208dff0c46cSDimitry Andric case bitc::CST_CODE_STRING: // STRING: [values] 2209f22ef01cSRoman Divacky case bitc::CST_CODE_CSTRING: { // CSTRING: [values] 2210f22ef01cSRoman Divacky if (Record.empty()) 22118f0fd8f6SDimitry Andric return error("Invalid record"); 2212f22ef01cSRoman Divacky 22137ae0e2c9SDimitry Andric SmallString<16> Elts(Record.begin(), Record.end()); 2214dff0c46cSDimitry Andric V = ConstantDataArray::getString(Context, Elts, 2215dff0c46cSDimitry Andric BitCode == bitc::CST_CODE_CSTRING); 2216f22ef01cSRoman Divacky break; 2217f22ef01cSRoman Divacky } 2218dff0c46cSDimitry Andric case bitc::CST_CODE_DATA: {// DATA: [n x value] 2219dff0c46cSDimitry Andric if (Record.empty()) 22208f0fd8f6SDimitry Andric return error("Invalid record"); 2221dff0c46cSDimitry Andric 2222dff0c46cSDimitry Andric Type *EltTy = cast<SequentialType>(CurTy)->getElementType(); 2223dff0c46cSDimitry Andric if (EltTy->isIntegerTy(8)) { 2224dff0c46cSDimitry Andric SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end()); 2225dff0c46cSDimitry Andric if (isa<VectorType>(CurTy)) 2226dff0c46cSDimitry Andric V = ConstantDataVector::get(Context, Elts); 2227dff0c46cSDimitry Andric else 2228dff0c46cSDimitry Andric V = ConstantDataArray::get(Context, Elts); 2229dff0c46cSDimitry Andric } else if (EltTy->isIntegerTy(16)) { 2230dff0c46cSDimitry Andric SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end()); 2231dff0c46cSDimitry Andric if (isa<VectorType>(CurTy)) 2232dff0c46cSDimitry Andric V = ConstantDataVector::get(Context, Elts); 2233dff0c46cSDimitry Andric else 2234dff0c46cSDimitry Andric V = ConstantDataArray::get(Context, Elts); 2235dff0c46cSDimitry Andric } else if (EltTy->isIntegerTy(32)) { 2236dff0c46cSDimitry Andric SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end()); 2237dff0c46cSDimitry Andric if (isa<VectorType>(CurTy)) 2238dff0c46cSDimitry Andric V = ConstantDataVector::get(Context, Elts); 2239dff0c46cSDimitry Andric else 2240dff0c46cSDimitry Andric V = ConstantDataArray::get(Context, Elts); 2241dff0c46cSDimitry Andric } else if (EltTy->isIntegerTy(64)) { 2242dff0c46cSDimitry Andric SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end()); 2243dff0c46cSDimitry Andric if (isa<VectorType>(CurTy)) 2244dff0c46cSDimitry Andric V = ConstantDataVector::get(Context, Elts); 2245dff0c46cSDimitry Andric else 2246dff0c46cSDimitry Andric V = ConstantDataArray::get(Context, Elts); 2247444ed5c5SDimitry Andric } else if (EltTy->isHalfTy()) { 2248444ed5c5SDimitry Andric SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end()); 2249444ed5c5SDimitry Andric if (isa<VectorType>(CurTy)) 2250444ed5c5SDimitry Andric V = ConstantDataVector::getFP(Context, Elts); 2251444ed5c5SDimitry Andric else 2252444ed5c5SDimitry Andric V = ConstantDataArray::getFP(Context, Elts); 2253dff0c46cSDimitry Andric } else if (EltTy->isFloatTy()) { 2254444ed5c5SDimitry Andric SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end()); 2255dff0c46cSDimitry Andric if (isa<VectorType>(CurTy)) 2256444ed5c5SDimitry Andric V = ConstantDataVector::getFP(Context, Elts); 2257dff0c46cSDimitry Andric else 2258444ed5c5SDimitry Andric V = ConstantDataArray::getFP(Context, Elts); 2259dff0c46cSDimitry Andric } else if (EltTy->isDoubleTy()) { 2260444ed5c5SDimitry Andric SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end()); 2261dff0c46cSDimitry Andric if (isa<VectorType>(CurTy)) 2262444ed5c5SDimitry Andric V = ConstantDataVector::getFP(Context, Elts); 2263dff0c46cSDimitry Andric else 2264444ed5c5SDimitry Andric V = ConstantDataArray::getFP(Context, Elts); 2265dff0c46cSDimitry Andric } else { 22668f0fd8f6SDimitry Andric return error("Invalid type for value"); 2267dff0c46cSDimitry Andric } 2268dff0c46cSDimitry Andric break; 2269dff0c46cSDimitry Andric } 2270f22ef01cSRoman Divacky case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval] 2271f785676fSDimitry Andric if (Record.size() < 3) 22728f0fd8f6SDimitry Andric return error("Invalid record"); 22738f0fd8f6SDimitry Andric int Opc = getDecodedBinaryOpcode(Record[0], CurTy); 2274f22ef01cSRoman Divacky if (Opc < 0) { 2275f22ef01cSRoman Divacky V = UndefValue::get(CurTy); // Unknown binop. 2276f22ef01cSRoman Divacky } else { 2277f22ef01cSRoman Divacky Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy); 2278f22ef01cSRoman Divacky Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy); 2279f22ef01cSRoman Divacky unsigned Flags = 0; 2280f22ef01cSRoman Divacky if (Record.size() >= 4) { 2281f22ef01cSRoman Divacky if (Opc == Instruction::Add || 2282f22ef01cSRoman Divacky Opc == Instruction::Sub || 22832754fe60SDimitry Andric Opc == Instruction::Mul || 22842754fe60SDimitry Andric Opc == Instruction::Shl) { 2285f22ef01cSRoman Divacky if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP)) 2286f22ef01cSRoman Divacky Flags |= OverflowingBinaryOperator::NoSignedWrap; 2287f22ef01cSRoman Divacky if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP)) 2288f22ef01cSRoman Divacky Flags |= OverflowingBinaryOperator::NoUnsignedWrap; 22892754fe60SDimitry Andric } else if (Opc == Instruction::SDiv || 22902754fe60SDimitry Andric Opc == Instruction::UDiv || 22912754fe60SDimitry Andric Opc == Instruction::LShr || 22922754fe60SDimitry Andric Opc == Instruction::AShr) { 22932754fe60SDimitry Andric if (Record[3] & (1 << bitc::PEO_EXACT)) 2294f22ef01cSRoman Divacky Flags |= SDivOperator::IsExact; 2295f22ef01cSRoman Divacky } 2296f22ef01cSRoman Divacky } 2297f22ef01cSRoman Divacky V = ConstantExpr::get(Opc, LHS, RHS, Flags); 2298f22ef01cSRoman Divacky } 2299f22ef01cSRoman Divacky break; 2300f22ef01cSRoman Divacky } 2301f22ef01cSRoman Divacky case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval] 2302f785676fSDimitry Andric if (Record.size() < 3) 23038f0fd8f6SDimitry Andric return error("Invalid record"); 23048f0fd8f6SDimitry Andric int Opc = getDecodedCastOpcode(Record[0]); 2305f22ef01cSRoman Divacky if (Opc < 0) { 2306f22ef01cSRoman Divacky V = UndefValue::get(CurTy); // Unknown cast. 2307f22ef01cSRoman Divacky } else { 23086122f3e6SDimitry Andric Type *OpTy = getTypeByID(Record[1]); 2309f785676fSDimitry Andric if (!OpTy) 23108f0fd8f6SDimitry Andric return error("Invalid record"); 2311f22ef01cSRoman Divacky Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy); 2312f785676fSDimitry Andric V = UpgradeBitCastExpr(Opc, Op, CurTy); 2313f785676fSDimitry Andric if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy); 2314f22ef01cSRoman Divacky } 2315f22ef01cSRoman Divacky break; 2316f22ef01cSRoman Divacky } 2317d88c1a5aSDimitry Andric case bitc::CST_CODE_CE_INBOUNDS_GEP: // [ty, n x operands] 2318d88c1a5aSDimitry Andric case bitc::CST_CODE_CE_GEP: // [ty, n x operands] 2319d88c1a5aSDimitry Andric case bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX: { // [ty, flags, n x 2320d88c1a5aSDimitry Andric // operands] 2321ff0cc061SDimitry Andric unsigned OpNum = 0; 2322ff0cc061SDimitry Andric Type *PointeeType = nullptr; 2323d88c1a5aSDimitry Andric if (BitCode == bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX || 2324d88c1a5aSDimitry Andric Record.size() % 2) 2325ff0cc061SDimitry Andric PointeeType = getTypeByID(Record[OpNum++]); 2326d88c1a5aSDimitry Andric 2327d88c1a5aSDimitry Andric bool InBounds = false; 2328d88c1a5aSDimitry Andric Optional<unsigned> InRangeIndex; 2329d88c1a5aSDimitry Andric if (BitCode == bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX) { 2330d88c1a5aSDimitry Andric uint64_t Op = Record[OpNum++]; 2331d88c1a5aSDimitry Andric InBounds = Op & 1; 2332d88c1a5aSDimitry Andric InRangeIndex = Op >> 1; 2333d88c1a5aSDimitry Andric } else if (BitCode == bitc::CST_CODE_CE_INBOUNDS_GEP) 2334d88c1a5aSDimitry Andric InBounds = true; 2335d88c1a5aSDimitry Andric 2336f22ef01cSRoman Divacky SmallVector<Constant*, 16> Elts; 2337ff0cc061SDimitry Andric while (OpNum != Record.size()) { 2338ff0cc061SDimitry Andric Type *ElTy = getTypeByID(Record[OpNum++]); 2339f785676fSDimitry Andric if (!ElTy) 23408f0fd8f6SDimitry Andric return error("Invalid record"); 2341ff0cc061SDimitry Andric Elts.push_back(ValueList.getConstantFwdRef(Record[OpNum++], ElTy)); 2342f22ef01cSRoman Divacky } 2343ff0cc061SDimitry Andric 2344ff0cc061SDimitry Andric if (PointeeType && 2345ff0cc061SDimitry Andric PointeeType != 2346d88c1a5aSDimitry Andric cast<PointerType>(Elts[0]->getType()->getScalarType()) 2347ff0cc061SDimitry Andric ->getElementType()) 23488f0fd8f6SDimitry Andric return error("Explicit gep operator type does not match pointee type " 2349ff0cc061SDimitry Andric "of pointer operand"); 2350ff0cc061SDimitry Andric 23513ca95b02SDimitry Andric if (Elts.size() < 1) 23523ca95b02SDimitry Andric return error("Invalid gep with no operands"); 23533ca95b02SDimitry Andric 23546122f3e6SDimitry Andric ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end()); 2355ff0cc061SDimitry Andric V = ConstantExpr::getGetElementPtr(PointeeType, Elts[0], Indices, 2356d88c1a5aSDimitry Andric InBounds, InRangeIndex); 2357f22ef01cSRoman Divacky break; 2358f22ef01cSRoman Divacky } 2359f785676fSDimitry Andric case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#] 2360f785676fSDimitry Andric if (Record.size() < 3) 23618f0fd8f6SDimitry Andric return error("Invalid record"); 2362f785676fSDimitry Andric 2363f785676fSDimitry Andric Type *SelectorTy = Type::getInt1Ty(Context); 2364f785676fSDimitry Andric 23657d523365SDimitry Andric // The selector might be an i1 or an <n x i1> 23667d523365SDimitry Andric // Get the type from the ValueList before getting a forward ref. 2367f785676fSDimitry Andric if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) 23687d523365SDimitry Andric if (Value *V = ValueList[Record[0]]) 23697d523365SDimitry Andric if (SelectorTy != V->getType()) 23707d523365SDimitry Andric SelectorTy = VectorType::get(SelectorTy, VTy->getNumElements()); 2371f785676fSDimitry Andric 2372f785676fSDimitry Andric V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0], 2373f785676fSDimitry Andric SelectorTy), 2374f22ef01cSRoman Divacky ValueList.getConstantFwdRef(Record[1],CurTy), 2375f22ef01cSRoman Divacky ValueList.getConstantFwdRef(Record[2],CurTy)); 2376f22ef01cSRoman Divacky break; 2377f785676fSDimitry Andric } 237891bc56edSDimitry Andric case bitc::CST_CODE_CE_EXTRACTELT 237991bc56edSDimitry Andric : { // CE_EXTRACTELT: [opty, opval, opty, opval] 2380f785676fSDimitry Andric if (Record.size() < 3) 23818f0fd8f6SDimitry Andric return error("Invalid record"); 23826122f3e6SDimitry Andric VectorType *OpTy = 2383f22ef01cSRoman Divacky dyn_cast_or_null<VectorType>(getTypeByID(Record[0])); 238491bc56edSDimitry Andric if (!OpTy) 23858f0fd8f6SDimitry Andric return error("Invalid record"); 2386f22ef01cSRoman Divacky Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy); 238791bc56edSDimitry Andric Constant *Op1 = nullptr; 238891bc56edSDimitry Andric if (Record.size() == 4) { 238991bc56edSDimitry Andric Type *IdxTy = getTypeByID(Record[2]); 239091bc56edSDimitry Andric if (!IdxTy) 23918f0fd8f6SDimitry Andric return error("Invalid record"); 239291bc56edSDimitry Andric Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy); 239391bc56edSDimitry Andric } else // TODO: Remove with llvm 4.0 239491bc56edSDimitry Andric Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context)); 239591bc56edSDimitry Andric if (!Op1) 23968f0fd8f6SDimitry Andric return error("Invalid record"); 2397f22ef01cSRoman Divacky V = ConstantExpr::getExtractElement(Op0, Op1); 2398f22ef01cSRoman Divacky break; 2399f22ef01cSRoman Divacky } 240091bc56edSDimitry Andric case bitc::CST_CODE_CE_INSERTELT 240191bc56edSDimitry Andric : { // CE_INSERTELT: [opval, opval, opty, opval] 24026122f3e6SDimitry Andric VectorType *OpTy = dyn_cast<VectorType>(CurTy); 240391bc56edSDimitry Andric if (Record.size() < 3 || !OpTy) 24048f0fd8f6SDimitry Andric return error("Invalid record"); 2405f22ef01cSRoman Divacky Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy); 2406f22ef01cSRoman Divacky Constant *Op1 = ValueList.getConstantFwdRef(Record[1], 2407f22ef01cSRoman Divacky OpTy->getElementType()); 240891bc56edSDimitry Andric Constant *Op2 = nullptr; 240991bc56edSDimitry Andric if (Record.size() == 4) { 241091bc56edSDimitry Andric Type *IdxTy = getTypeByID(Record[2]); 241191bc56edSDimitry Andric if (!IdxTy) 24128f0fd8f6SDimitry Andric return error("Invalid record"); 241391bc56edSDimitry Andric Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy); 241491bc56edSDimitry Andric } else // TODO: Remove with llvm 4.0 241591bc56edSDimitry Andric Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context)); 241691bc56edSDimitry Andric if (!Op2) 24178f0fd8f6SDimitry Andric return error("Invalid record"); 2418f22ef01cSRoman Divacky V = ConstantExpr::getInsertElement(Op0, Op1, Op2); 2419f22ef01cSRoman Divacky break; 2420f22ef01cSRoman Divacky } 2421f22ef01cSRoman Divacky case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval] 24226122f3e6SDimitry Andric VectorType *OpTy = dyn_cast<VectorType>(CurTy); 242391bc56edSDimitry Andric if (Record.size() < 3 || !OpTy) 24248f0fd8f6SDimitry Andric return error("Invalid record"); 2425f22ef01cSRoman Divacky Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy); 2426f22ef01cSRoman Divacky Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy); 24276122f3e6SDimitry Andric Type *ShufTy = VectorType::get(Type::getInt32Ty(Context), 2428f22ef01cSRoman Divacky OpTy->getNumElements()); 2429f22ef01cSRoman Divacky Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy); 2430f22ef01cSRoman Divacky V = ConstantExpr::getShuffleVector(Op0, Op1, Op2); 2431f22ef01cSRoman Divacky break; 2432f22ef01cSRoman Divacky } 2433f22ef01cSRoman Divacky case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval] 24346122f3e6SDimitry Andric VectorType *RTy = dyn_cast<VectorType>(CurTy); 24356122f3e6SDimitry Andric VectorType *OpTy = 24362754fe60SDimitry Andric dyn_cast_or_null<VectorType>(getTypeByID(Record[0])); 243791bc56edSDimitry Andric if (Record.size() < 4 || !RTy || !OpTy) 24388f0fd8f6SDimitry Andric return error("Invalid record"); 2439f22ef01cSRoman Divacky Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy); 2440f22ef01cSRoman Divacky Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy); 24416122f3e6SDimitry Andric Type *ShufTy = VectorType::get(Type::getInt32Ty(Context), 2442f22ef01cSRoman Divacky RTy->getNumElements()); 2443f22ef01cSRoman Divacky Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy); 2444f22ef01cSRoman Divacky V = ConstantExpr::getShuffleVector(Op0, Op1, Op2); 2445f22ef01cSRoman Divacky break; 2446f22ef01cSRoman Divacky } 2447f22ef01cSRoman Divacky case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred] 2448f785676fSDimitry Andric if (Record.size() < 4) 24498f0fd8f6SDimitry Andric return error("Invalid record"); 24506122f3e6SDimitry Andric Type *OpTy = getTypeByID(Record[0]); 245191bc56edSDimitry Andric if (!OpTy) 24528f0fd8f6SDimitry Andric return error("Invalid record"); 2453f22ef01cSRoman Divacky Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy); 2454f22ef01cSRoman Divacky Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy); 2455f22ef01cSRoman Divacky 2456f22ef01cSRoman Divacky if (OpTy->isFPOrFPVectorTy()) 2457f22ef01cSRoman Divacky V = ConstantExpr::getFCmp(Record[3], Op0, Op1); 2458f22ef01cSRoman Divacky else 2459f22ef01cSRoman Divacky V = ConstantExpr::getICmp(Record[3], Op0, Op1); 2460f22ef01cSRoman Divacky break; 2461f22ef01cSRoman Divacky } 24623861d79fSDimitry Andric // This maintains backward compatibility, pre-asm dialect keywords. 24633861d79fSDimitry Andric // FIXME: Remove with the 4.0 release. 24643861d79fSDimitry Andric case bitc::CST_CODE_INLINEASM_OLD: { 2465f785676fSDimitry Andric if (Record.size() < 2) 24668f0fd8f6SDimitry Andric return error("Invalid record"); 2467f22ef01cSRoman Divacky std::string AsmStr, ConstrStr; 2468f22ef01cSRoman Divacky bool HasSideEffects = Record[0] & 1; 2469f22ef01cSRoman Divacky bool IsAlignStack = Record[0] >> 1; 2470f22ef01cSRoman Divacky unsigned AsmStrSize = Record[1]; 2471f22ef01cSRoman Divacky if (2+AsmStrSize >= Record.size()) 24728f0fd8f6SDimitry Andric return error("Invalid record"); 2473f22ef01cSRoman Divacky unsigned ConstStrSize = Record[2+AsmStrSize]; 2474f22ef01cSRoman Divacky if (3+AsmStrSize+ConstStrSize > Record.size()) 24758f0fd8f6SDimitry Andric return error("Invalid record"); 2476f22ef01cSRoman Divacky 2477f22ef01cSRoman Divacky for (unsigned i = 0; i != AsmStrSize; ++i) 2478f22ef01cSRoman Divacky AsmStr += (char)Record[2+i]; 2479f22ef01cSRoman Divacky for (unsigned i = 0; i != ConstStrSize; ++i) 2480f22ef01cSRoman Divacky ConstrStr += (char)Record[3+AsmStrSize+i]; 24816122f3e6SDimitry Andric PointerType *PTy = cast<PointerType>(CurTy); 2482f22ef01cSRoman Divacky V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()), 2483f22ef01cSRoman Divacky AsmStr, ConstrStr, HasSideEffects, IsAlignStack); 2484f22ef01cSRoman Divacky break; 2485f22ef01cSRoman Divacky } 24863861d79fSDimitry Andric // This version adds support for the asm dialect keywords (e.g., 24873861d79fSDimitry Andric // inteldialect). 24883861d79fSDimitry Andric case bitc::CST_CODE_INLINEASM: { 2489f785676fSDimitry Andric if (Record.size() < 2) 24908f0fd8f6SDimitry Andric return error("Invalid record"); 24913861d79fSDimitry Andric std::string AsmStr, ConstrStr; 24923861d79fSDimitry Andric bool HasSideEffects = Record[0] & 1; 24933861d79fSDimitry Andric bool IsAlignStack = (Record[0] >> 1) & 1; 24943861d79fSDimitry Andric unsigned AsmDialect = Record[0] >> 2; 24953861d79fSDimitry Andric unsigned AsmStrSize = Record[1]; 24963861d79fSDimitry Andric if (2+AsmStrSize >= Record.size()) 24978f0fd8f6SDimitry Andric return error("Invalid record"); 24983861d79fSDimitry Andric unsigned ConstStrSize = Record[2+AsmStrSize]; 24993861d79fSDimitry Andric if (3+AsmStrSize+ConstStrSize > Record.size()) 25008f0fd8f6SDimitry Andric return error("Invalid record"); 25013861d79fSDimitry Andric 25023861d79fSDimitry Andric for (unsigned i = 0; i != AsmStrSize; ++i) 25033861d79fSDimitry Andric AsmStr += (char)Record[2+i]; 25043861d79fSDimitry Andric for (unsigned i = 0; i != ConstStrSize; ++i) 25053861d79fSDimitry Andric ConstrStr += (char)Record[3+AsmStrSize+i]; 25063861d79fSDimitry Andric PointerType *PTy = cast<PointerType>(CurTy); 25073861d79fSDimitry Andric V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()), 25083861d79fSDimitry Andric AsmStr, ConstrStr, HasSideEffects, IsAlignStack, 25093861d79fSDimitry Andric InlineAsm::AsmDialect(AsmDialect)); 25103861d79fSDimitry Andric break; 25113861d79fSDimitry Andric } 2512f22ef01cSRoman Divacky case bitc::CST_CODE_BLOCKADDRESS:{ 2513f785676fSDimitry Andric if (Record.size() < 3) 25148f0fd8f6SDimitry Andric return error("Invalid record"); 25156122f3e6SDimitry Andric Type *FnTy = getTypeByID(Record[0]); 251691bc56edSDimitry Andric if (!FnTy) 25178f0fd8f6SDimitry Andric return error("Invalid record"); 2518f22ef01cSRoman Divacky Function *Fn = 2519f22ef01cSRoman Divacky dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy)); 252091bc56edSDimitry Andric if (!Fn) 25218f0fd8f6SDimitry Andric return error("Invalid record"); 252239d628a0SDimitry Andric 25233861d79fSDimitry Andric // If the function is already parsed we can insert the block address right 25243861d79fSDimitry Andric // away. 252539d628a0SDimitry Andric BasicBlock *BB; 252639d628a0SDimitry Andric unsigned BBID = Record[2]; 252739d628a0SDimitry Andric if (!BBID) 252839d628a0SDimitry Andric // Invalid reference to entry block. 25298f0fd8f6SDimitry Andric return error("Invalid ID"); 25303861d79fSDimitry Andric if (!Fn->empty()) { 25313861d79fSDimitry Andric Function::iterator BBI = Fn->begin(), BBE = Fn->end(); 253239d628a0SDimitry Andric for (size_t I = 0, E = BBID; I != E; ++I) { 25333861d79fSDimitry Andric if (BBI == BBE) 25348f0fd8f6SDimitry Andric return error("Invalid ID"); 25353861d79fSDimitry Andric ++BBI; 25363861d79fSDimitry Andric } 25377d523365SDimitry Andric BB = &*BBI; 25383861d79fSDimitry Andric } else { 25393861d79fSDimitry Andric // Otherwise insert a placeholder and remember it so it can be inserted 25403861d79fSDimitry Andric // when the function is parsed. 254139d628a0SDimitry Andric auto &FwdBBs = BasicBlockFwdRefs[Fn]; 254239d628a0SDimitry Andric if (FwdBBs.empty()) 254339d628a0SDimitry Andric BasicBlockFwdRefQueue.push_back(Fn); 254439d628a0SDimitry Andric if (FwdBBs.size() < BBID + 1) 254539d628a0SDimitry Andric FwdBBs.resize(BBID + 1); 254639d628a0SDimitry Andric if (!FwdBBs[BBID]) 254739d628a0SDimitry Andric FwdBBs[BBID] = BasicBlock::Create(Context); 254839d628a0SDimitry Andric BB = FwdBBs[BBID]; 25493861d79fSDimitry Andric } 255039d628a0SDimitry Andric V = BlockAddress::get(Fn, BB); 2551f22ef01cSRoman Divacky break; 2552f22ef01cSRoman Divacky } 2553f22ef01cSRoman Divacky } 2554f22ef01cSRoman Divacky 25558f0fd8f6SDimitry Andric ValueList.assignValue(V, NextCstNo); 2556f22ef01cSRoman Divacky ++NextCstNo; 2557f22ef01cSRoman Divacky } 2558f22ef01cSRoman Divacky } 2559f22ef01cSRoman Divacky 2560d88c1a5aSDimitry Andric Error BitcodeReader::parseUseLists() { 2561dff0c46cSDimitry Andric if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID)) 25628f0fd8f6SDimitry Andric return error("Invalid record"); 2563dff0c46cSDimitry Andric 2564dff0c46cSDimitry Andric // Read all the records. 256539d628a0SDimitry Andric SmallVector<uint64_t, 64> Record; 2566d88c1a5aSDimitry Andric 2567d88c1a5aSDimitry Andric while (true) { 2568139f7f9bSDimitry Andric BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 2569139f7f9bSDimitry Andric 2570139f7f9bSDimitry Andric switch (Entry.Kind) { 2571139f7f9bSDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already. 2572139f7f9bSDimitry Andric case BitstreamEntry::Error: 25738f0fd8f6SDimitry Andric return error("Malformed block"); 2574139f7f9bSDimitry Andric case BitstreamEntry::EndBlock: 2575d88c1a5aSDimitry Andric return Error::success(); 2576139f7f9bSDimitry Andric case BitstreamEntry::Record: 2577139f7f9bSDimitry Andric // The interesting case. 2578139f7f9bSDimitry Andric break; 2579dff0c46cSDimitry Andric } 2580dff0c46cSDimitry Andric 2581dff0c46cSDimitry Andric // Read a use list record. 2582dff0c46cSDimitry Andric Record.clear(); 258339d628a0SDimitry Andric bool IsBB = false; 2584139f7f9bSDimitry Andric switch (Stream.readRecord(Entry.ID, Record)) { 2585dff0c46cSDimitry Andric default: // Default behavior: unknown type. 2586dff0c46cSDimitry Andric break; 258739d628a0SDimitry Andric case bitc::USELIST_CODE_BB: 258839d628a0SDimitry Andric IsBB = true; 2589d88c1a5aSDimitry Andric LLVM_FALLTHROUGH; 259039d628a0SDimitry Andric case bitc::USELIST_CODE_DEFAULT: { 2591dff0c46cSDimitry Andric unsigned RecordLength = Record.size(); 259239d628a0SDimitry Andric if (RecordLength < 3) 259339d628a0SDimitry Andric // Records should have at least an ID and two indexes. 25948f0fd8f6SDimitry Andric return error("Invalid record"); 259539d628a0SDimitry Andric unsigned ID = Record.back(); 259639d628a0SDimitry Andric Record.pop_back(); 259739d628a0SDimitry Andric 259839d628a0SDimitry Andric Value *V; 259939d628a0SDimitry Andric if (IsBB) { 260039d628a0SDimitry Andric assert(ID < FunctionBBs.size() && "Basic block not found"); 260139d628a0SDimitry Andric V = FunctionBBs[ID]; 260239d628a0SDimitry Andric } else 260339d628a0SDimitry Andric V = ValueList[ID]; 260439d628a0SDimitry Andric unsigned NumUses = 0; 260539d628a0SDimitry Andric SmallDenseMap<const Use *, unsigned, 16> Order; 26067d523365SDimitry Andric for (const Use &U : V->materialized_uses()) { 260739d628a0SDimitry Andric if (++NumUses > Record.size()) 260839d628a0SDimitry Andric break; 260939d628a0SDimitry Andric Order[&U] = Record[NumUses - 1]; 261039d628a0SDimitry Andric } 261139d628a0SDimitry Andric if (Order.size() != Record.size() || NumUses > Record.size()) 261239d628a0SDimitry Andric // Mismatches can happen if the functions are being materialized lazily 261339d628a0SDimitry Andric // (out-of-order), or a value has been upgraded. 261439d628a0SDimitry Andric break; 261539d628a0SDimitry Andric 261639d628a0SDimitry Andric V->sortUseList([&](const Use &L, const Use &R) { 261739d628a0SDimitry Andric return Order.lookup(&L) < Order.lookup(&R); 261839d628a0SDimitry Andric }); 2619dff0c46cSDimitry Andric break; 2620dff0c46cSDimitry Andric } 2621dff0c46cSDimitry Andric } 2622dff0c46cSDimitry Andric } 2623dff0c46cSDimitry Andric } 2624dff0c46cSDimitry Andric 2625ff0cc061SDimitry Andric /// When we see the block for metadata, remember where it is and then skip it. 2626ff0cc061SDimitry Andric /// This lets us lazily deserialize the metadata. 2627d88c1a5aSDimitry Andric Error BitcodeReader::rememberAndSkipMetadata() { 2628ff0cc061SDimitry Andric // Save the current stream state. 2629ff0cc061SDimitry Andric uint64_t CurBit = Stream.GetCurrentBitNo(); 2630ff0cc061SDimitry Andric DeferredMetadataInfo.push_back(CurBit); 2631ff0cc061SDimitry Andric 2632ff0cc061SDimitry Andric // Skip over the block for now. 2633ff0cc061SDimitry Andric if (Stream.SkipBlock()) 26348f0fd8f6SDimitry Andric return error("Invalid record"); 2635d88c1a5aSDimitry Andric return Error::success(); 2636ff0cc061SDimitry Andric } 2637ff0cc061SDimitry Andric 2638d88c1a5aSDimitry Andric Error BitcodeReader::materializeMetadata() { 2639ff0cc061SDimitry Andric for (uint64_t BitPos : DeferredMetadataInfo) { 2640ff0cc061SDimitry Andric // Move the bit stream to the saved position. 2641ff0cc061SDimitry Andric Stream.JumpToBit(BitPos); 2642d88c1a5aSDimitry Andric if (Error Err = MDLoader->parseModuleMetadata()) 2643d88c1a5aSDimitry Andric return Err; 2644ff0cc061SDimitry Andric } 264524d58133SDimitry Andric 264624d58133SDimitry Andric // Upgrade "Linker Options" module flag to "llvm.linker.options" module-level 264724d58133SDimitry Andric // metadata. 264824d58133SDimitry Andric if (Metadata *Val = TheModule->getModuleFlag("Linker Options")) { 264924d58133SDimitry Andric NamedMDNode *LinkerOpts = 265024d58133SDimitry Andric TheModule->getOrInsertNamedMetadata("llvm.linker.options"); 265124d58133SDimitry Andric for (const MDOperand &MDOptions : cast<MDNode>(Val)->operands()) 265224d58133SDimitry Andric LinkerOpts->addOperand(cast<MDNode>(MDOptions)); 265324d58133SDimitry Andric } 265424d58133SDimitry Andric 2655ff0cc061SDimitry Andric DeferredMetadataInfo.clear(); 2656d88c1a5aSDimitry Andric return Error::success(); 2657ff0cc061SDimitry Andric } 2658ff0cc061SDimitry Andric 2659ff0cc061SDimitry Andric void BitcodeReader::setStripDebugInfo() { StripDebugInfo = true; } 2660ff0cc061SDimitry Andric 26618f0fd8f6SDimitry Andric /// When we see the block for a function body, remember where it is and then 26628f0fd8f6SDimitry Andric /// skip it. This lets us lazily deserialize the functions. 2663d88c1a5aSDimitry Andric Error BitcodeReader::rememberAndSkipFunctionBody() { 2664f22ef01cSRoman Divacky // Get the function we are talking about. 2665f22ef01cSRoman Divacky if (FunctionsWithBodies.empty()) 26668f0fd8f6SDimitry Andric return error("Insufficient function protos"); 2667f22ef01cSRoman Divacky 2668f22ef01cSRoman Divacky Function *Fn = FunctionsWithBodies.back(); 2669f22ef01cSRoman Divacky FunctionsWithBodies.pop_back(); 2670f22ef01cSRoman Divacky 2671f22ef01cSRoman Divacky // Save the current stream state. 2672f22ef01cSRoman Divacky uint64_t CurBit = Stream.GetCurrentBitNo(); 26737d523365SDimitry Andric assert( 26747d523365SDimitry Andric (DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo[Fn] == CurBit) && 26757d523365SDimitry Andric "Mismatch between VST and scanned function offsets"); 2676f22ef01cSRoman Divacky DeferredFunctionInfo[Fn] = CurBit; 2677f22ef01cSRoman Divacky 2678f22ef01cSRoman Divacky // Skip over the function block for now. 2679f22ef01cSRoman Divacky if (Stream.SkipBlock()) 26808f0fd8f6SDimitry Andric return error("Invalid record"); 2681d88c1a5aSDimitry Andric return Error::success(); 2682f22ef01cSRoman Divacky } 2683f22ef01cSRoman Divacky 2684d88c1a5aSDimitry Andric Error BitcodeReader::globalCleanup() { 2685f22ef01cSRoman Divacky // Patch the initializers for globals and aliases up. 2686d88c1a5aSDimitry Andric if (Error Err = resolveGlobalAndIndirectSymbolInits()) 2687d88c1a5aSDimitry Andric return Err; 26883ca95b02SDimitry Andric if (!GlobalInits.empty() || !IndirectSymbolInits.empty()) 26898f0fd8f6SDimitry Andric return error("Malformed global initializer set"); 2690f22ef01cSRoman Divacky 2691f22ef01cSRoman Divacky // Look for intrinsic functions which need to be upgraded at some point 26928f0fd8f6SDimitry Andric for (Function &F : *TheModule) { 26936bc11b14SDimitry Andric MDLoader->upgradeDebugIntrinsics(F); 2694f22ef01cSRoman Divacky Function *NewFn; 26958f0fd8f6SDimitry Andric if (UpgradeIntrinsicFunction(&F, NewFn)) 26963dac3a9bSDimitry Andric UpgradedIntrinsics[&F] = NewFn; 26973ca95b02SDimitry Andric else if (auto Remangled = Intrinsic::remangleIntrinsicFunction(&F)) 26983ca95b02SDimitry Andric // Some types could be renamed during loading if several modules are 26993ca95b02SDimitry Andric // loaded in the same LLVMContext (LTO scenario). In this case we should 27003ca95b02SDimitry Andric // remangle intrinsics names as well. 27013ca95b02SDimitry Andric RemangledIntrinsics[&F] = Remangled.getValue(); 2702f22ef01cSRoman Divacky } 2703f22ef01cSRoman Divacky 2704e580952dSDimitry Andric // Look for global variables which need to be renamed. 27058f0fd8f6SDimitry Andric for (GlobalVariable &GV : TheModule->globals()) 27068f0fd8f6SDimitry Andric UpgradeGlobalVariable(&GV); 270791bc56edSDimitry Andric 2708f22ef01cSRoman Divacky // Force deallocation of memory for these vectors to favor the client that 2709f22ef01cSRoman Divacky // want lazy deserialization. 2710f22ef01cSRoman Divacky std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits); 27113ca95b02SDimitry Andric std::vector<std::pair<GlobalIndirectSymbol*, unsigned> >().swap( 27123ca95b02SDimitry Andric IndirectSymbolInits); 2713d88c1a5aSDimitry Andric return Error::success(); 2714f22ef01cSRoman Divacky } 2715f22ef01cSRoman Divacky 27167d523365SDimitry Andric /// Support for lazy parsing of function bodies. This is required if we 27177d523365SDimitry Andric /// either have an old bitcode file without a VST forward declaration record, 27187d523365SDimitry Andric /// or if we have an anonymous function being materialized, since anonymous 27197d523365SDimitry Andric /// functions do not have a name and are therefore not in the VST. 2720d88c1a5aSDimitry Andric Error BitcodeReader::rememberAndSkipFunctionBodies() { 2721dff0c46cSDimitry Andric Stream.JumpToBit(NextUnreadBit); 27227d523365SDimitry Andric 27237d523365SDimitry Andric if (Stream.AtEndOfStream()) 27247d523365SDimitry Andric return error("Could not find function in stream"); 27257d523365SDimitry Andric 27267d523365SDimitry Andric if (!SeenFirstFunctionBody) 27277d523365SDimitry Andric return error("Trying to materialize functions before seeing function blocks"); 27287d523365SDimitry Andric 27297d523365SDimitry Andric // An old bitcode file with the symbol table at the end would have 27307d523365SDimitry Andric // finished the parse greedily. 27317d523365SDimitry Andric assert(SeenValueSymbolTable); 27327d523365SDimitry Andric 27337d523365SDimitry Andric SmallVector<uint64_t, 64> Record; 27347d523365SDimitry Andric 2735d88c1a5aSDimitry Andric while (true) { 27367d523365SDimitry Andric BitstreamEntry Entry = Stream.advance(); 27377d523365SDimitry Andric switch (Entry.Kind) { 27387d523365SDimitry Andric default: 27397d523365SDimitry Andric return error("Expect SubBlock"); 27407d523365SDimitry Andric case BitstreamEntry::SubBlock: 27417d523365SDimitry Andric switch (Entry.ID) { 27427d523365SDimitry Andric default: 27437d523365SDimitry Andric return error("Expect function block"); 27447d523365SDimitry Andric case bitc::FUNCTION_BLOCK_ID: 2745d88c1a5aSDimitry Andric if (Error Err = rememberAndSkipFunctionBody()) 2746d88c1a5aSDimitry Andric return Err; 27477d523365SDimitry Andric NextUnreadBit = Stream.GetCurrentBitNo(); 2748d88c1a5aSDimitry Andric return Error::success(); 27497d523365SDimitry Andric } 27507d523365SDimitry Andric } 27517d523365SDimitry Andric } 27527d523365SDimitry Andric } 27537d523365SDimitry Andric 2754d88c1a5aSDimitry Andric bool BitcodeReaderBase::readBlockInfo() { 2755d88c1a5aSDimitry Andric Optional<BitstreamBlockInfo> NewBlockInfo = Stream.ReadBlockInfoBlock(); 2756d88c1a5aSDimitry Andric if (!NewBlockInfo) 2757d88c1a5aSDimitry Andric return true; 2758d88c1a5aSDimitry Andric BlockInfo = std::move(*NewBlockInfo); 2759d88c1a5aSDimitry Andric return false; 27607d523365SDimitry Andric } 27617d523365SDimitry Andric 27627a7e6055SDimitry Andric Error BitcodeReader::parseComdatRecord(ArrayRef<uint64_t> Record) { 27636bc11b14SDimitry Andric // v1: [selection_kind, name] 27646bc11b14SDimitry Andric // v2: [strtab_offset, strtab_size, selection_kind] 27656bc11b14SDimitry Andric StringRef Name; 27666bc11b14SDimitry Andric std::tie(Name, Record) = readNameFromStrtab(Record); 27676bc11b14SDimitry Andric 27686bc11b14SDimitry Andric if (Record.size() < 1) 27697a7e6055SDimitry Andric return error("Invalid record"); 27707a7e6055SDimitry Andric Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]); 27716bc11b14SDimitry Andric std::string OldFormatName; 27726bc11b14SDimitry Andric if (!UseStrtab) { 27736bc11b14SDimitry Andric if (Record.size() < 2) 27746bc11b14SDimitry Andric return error("Invalid record"); 27757a7e6055SDimitry Andric unsigned ComdatNameSize = Record[1]; 27766bc11b14SDimitry Andric OldFormatName.reserve(ComdatNameSize); 27777a7e6055SDimitry Andric for (unsigned i = 0; i != ComdatNameSize; ++i) 27786bc11b14SDimitry Andric OldFormatName += (char)Record[2 + i]; 27796bc11b14SDimitry Andric Name = OldFormatName; 27806bc11b14SDimitry Andric } 27817a7e6055SDimitry Andric Comdat *C = TheModule->getOrInsertComdat(Name); 27827a7e6055SDimitry Andric C->setSelectionKind(SK); 27837a7e6055SDimitry Andric ComdatList.push_back(C); 27847a7e6055SDimitry Andric return Error::success(); 27857a7e6055SDimitry Andric } 27867a7e6055SDimitry Andric 27877a7e6055SDimitry Andric Error BitcodeReader::parseGlobalVarRecord(ArrayRef<uint64_t> Record) { 27886bc11b14SDimitry Andric // v1: [pointer type, isconst, initid, linkage, alignment, section, 27897a7e6055SDimitry Andric // visibility, threadlocal, unnamed_addr, externally_initialized, 27905517e702SDimitry Andric // dllstorageclass, comdat, attributes] (name in VST) 27916bc11b14SDimitry Andric // v2: [strtab_offset, strtab_size, v1] 27926bc11b14SDimitry Andric StringRef Name; 27936bc11b14SDimitry Andric std::tie(Name, Record) = readNameFromStrtab(Record); 27946bc11b14SDimitry Andric 27957a7e6055SDimitry Andric if (Record.size() < 6) 27967a7e6055SDimitry Andric return error("Invalid record"); 27977a7e6055SDimitry Andric Type *Ty = getTypeByID(Record[0]); 27987a7e6055SDimitry Andric if (!Ty) 27997a7e6055SDimitry Andric return error("Invalid record"); 28007a7e6055SDimitry Andric bool isConstant = Record[1] & 1; 28017a7e6055SDimitry Andric bool explicitType = Record[1] & 2; 28027a7e6055SDimitry Andric unsigned AddressSpace; 28037a7e6055SDimitry Andric if (explicitType) { 28047a7e6055SDimitry Andric AddressSpace = Record[1] >> 2; 28057a7e6055SDimitry Andric } else { 28067a7e6055SDimitry Andric if (!Ty->isPointerTy()) 28077a7e6055SDimitry Andric return error("Invalid type for value"); 28087a7e6055SDimitry Andric AddressSpace = cast<PointerType>(Ty)->getAddressSpace(); 28097a7e6055SDimitry Andric Ty = cast<PointerType>(Ty)->getElementType(); 28107a7e6055SDimitry Andric } 28117a7e6055SDimitry Andric 28127a7e6055SDimitry Andric uint64_t RawLinkage = Record[3]; 28137a7e6055SDimitry Andric GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage); 28147a7e6055SDimitry Andric unsigned Alignment; 28157a7e6055SDimitry Andric if (Error Err = parseAlignmentValue(Record[4], Alignment)) 28167a7e6055SDimitry Andric return Err; 28177a7e6055SDimitry Andric std::string Section; 28187a7e6055SDimitry Andric if (Record[5]) { 28197a7e6055SDimitry Andric if (Record[5] - 1 >= SectionTable.size()) 28207a7e6055SDimitry Andric return error("Invalid ID"); 28217a7e6055SDimitry Andric Section = SectionTable[Record[5] - 1]; 28227a7e6055SDimitry Andric } 28237a7e6055SDimitry Andric GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility; 28247a7e6055SDimitry Andric // Local linkage must have default visibility. 28257a7e6055SDimitry Andric if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage)) 28267a7e6055SDimitry Andric // FIXME: Change to an error if non-default in 4.0. 28277a7e6055SDimitry Andric Visibility = getDecodedVisibility(Record[6]); 28287a7e6055SDimitry Andric 28297a7e6055SDimitry Andric GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal; 28307a7e6055SDimitry Andric if (Record.size() > 7) 28317a7e6055SDimitry Andric TLM = getDecodedThreadLocalMode(Record[7]); 28327a7e6055SDimitry Andric 28337a7e6055SDimitry Andric GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None; 28347a7e6055SDimitry Andric if (Record.size() > 8) 28357a7e6055SDimitry Andric UnnamedAddr = getDecodedUnnamedAddrType(Record[8]); 28367a7e6055SDimitry Andric 28377a7e6055SDimitry Andric bool ExternallyInitialized = false; 28387a7e6055SDimitry Andric if (Record.size() > 9) 28397a7e6055SDimitry Andric ExternallyInitialized = Record[9]; 28407a7e6055SDimitry Andric 28417a7e6055SDimitry Andric GlobalVariable *NewGV = 28426bc11b14SDimitry Andric new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, Name, 28437a7e6055SDimitry Andric nullptr, TLM, AddressSpace, ExternallyInitialized); 28447a7e6055SDimitry Andric NewGV->setAlignment(Alignment); 28457a7e6055SDimitry Andric if (!Section.empty()) 28467a7e6055SDimitry Andric NewGV->setSection(Section); 28477a7e6055SDimitry Andric NewGV->setVisibility(Visibility); 28487a7e6055SDimitry Andric NewGV->setUnnamedAddr(UnnamedAddr); 28497a7e6055SDimitry Andric 28507a7e6055SDimitry Andric if (Record.size() > 10) 28517a7e6055SDimitry Andric NewGV->setDLLStorageClass(getDecodedDLLStorageClass(Record[10])); 28527a7e6055SDimitry Andric else 28537a7e6055SDimitry Andric upgradeDLLImportExportLinkage(NewGV, RawLinkage); 28547a7e6055SDimitry Andric 28557a7e6055SDimitry Andric ValueList.push_back(NewGV); 28567a7e6055SDimitry Andric 28577a7e6055SDimitry Andric // Remember which value to use for the global initializer. 28587a7e6055SDimitry Andric if (unsigned InitID = Record[2]) 28597a7e6055SDimitry Andric GlobalInits.push_back(std::make_pair(NewGV, InitID - 1)); 28607a7e6055SDimitry Andric 28617a7e6055SDimitry Andric if (Record.size() > 11) { 28627a7e6055SDimitry Andric if (unsigned ComdatID = Record[11]) { 28637a7e6055SDimitry Andric if (ComdatID > ComdatList.size()) 28647a7e6055SDimitry Andric return error("Invalid global variable comdat ID"); 28657a7e6055SDimitry Andric NewGV->setComdat(ComdatList[ComdatID - 1]); 28667a7e6055SDimitry Andric } 28677a7e6055SDimitry Andric } else if (hasImplicitComdat(RawLinkage)) { 28687a7e6055SDimitry Andric NewGV->setComdat(reinterpret_cast<Comdat *>(1)); 28697a7e6055SDimitry Andric } 28705517e702SDimitry Andric 28715517e702SDimitry Andric if (Record.size() > 12) { 28725517e702SDimitry Andric auto AS = getAttributes(Record[12]).getFnAttributes(); 28735517e702SDimitry Andric NewGV->setAttributes(AS); 28745517e702SDimitry Andric } 28757a7e6055SDimitry Andric return Error::success(); 28767a7e6055SDimitry Andric } 28777a7e6055SDimitry Andric 28787a7e6055SDimitry Andric Error BitcodeReader::parseFunctionRecord(ArrayRef<uint64_t> Record) { 28796bc11b14SDimitry Andric // v1: [type, callingconv, isproto, linkage, paramattr, alignment, section, 28807a7e6055SDimitry Andric // visibility, gc, unnamed_addr, prologuedata, dllstorageclass, comdat, 28816bc11b14SDimitry Andric // prefixdata] (name in VST) 28826bc11b14SDimitry Andric // v2: [strtab_offset, strtab_size, v1] 28836bc11b14SDimitry Andric StringRef Name; 28846bc11b14SDimitry Andric std::tie(Name, Record) = readNameFromStrtab(Record); 28856bc11b14SDimitry Andric 28867a7e6055SDimitry Andric if (Record.size() < 8) 28877a7e6055SDimitry Andric return error("Invalid record"); 28887a7e6055SDimitry Andric Type *Ty = getTypeByID(Record[0]); 28897a7e6055SDimitry Andric if (!Ty) 28907a7e6055SDimitry Andric return error("Invalid record"); 28917a7e6055SDimitry Andric if (auto *PTy = dyn_cast<PointerType>(Ty)) 28927a7e6055SDimitry Andric Ty = PTy->getElementType(); 28937a7e6055SDimitry Andric auto *FTy = dyn_cast<FunctionType>(Ty); 28947a7e6055SDimitry Andric if (!FTy) 28957a7e6055SDimitry Andric return error("Invalid type for value"); 28967a7e6055SDimitry Andric auto CC = static_cast<CallingConv::ID>(Record[1]); 28977a7e6055SDimitry Andric if (CC & ~CallingConv::MaxID) 28987a7e6055SDimitry Andric return error("Invalid calling convention ID"); 28997a7e6055SDimitry Andric 29007a7e6055SDimitry Andric Function *Func = 29016bc11b14SDimitry Andric Function::Create(FTy, GlobalValue::ExternalLinkage, Name, TheModule); 29027a7e6055SDimitry Andric 29037a7e6055SDimitry Andric Func->setCallingConv(CC); 29047a7e6055SDimitry Andric bool isProto = Record[2]; 29057a7e6055SDimitry Andric uint64_t RawLinkage = Record[3]; 29067a7e6055SDimitry Andric Func->setLinkage(getDecodedLinkage(RawLinkage)); 29077a7e6055SDimitry Andric Func->setAttributes(getAttributes(Record[4])); 29087a7e6055SDimitry Andric 29097a7e6055SDimitry Andric unsigned Alignment; 29107a7e6055SDimitry Andric if (Error Err = parseAlignmentValue(Record[5], Alignment)) 29117a7e6055SDimitry Andric return Err; 29127a7e6055SDimitry Andric Func->setAlignment(Alignment); 29137a7e6055SDimitry Andric if (Record[6]) { 29147a7e6055SDimitry Andric if (Record[6] - 1 >= SectionTable.size()) 29157a7e6055SDimitry Andric return error("Invalid ID"); 29167a7e6055SDimitry Andric Func->setSection(SectionTable[Record[6] - 1]); 29177a7e6055SDimitry Andric } 29187a7e6055SDimitry Andric // Local linkage must have default visibility. 29197a7e6055SDimitry Andric if (!Func->hasLocalLinkage()) 29207a7e6055SDimitry Andric // FIXME: Change to an error if non-default in 4.0. 29217a7e6055SDimitry Andric Func->setVisibility(getDecodedVisibility(Record[7])); 29227a7e6055SDimitry Andric if (Record.size() > 8 && Record[8]) { 29237a7e6055SDimitry Andric if (Record[8] - 1 >= GCTable.size()) 29247a7e6055SDimitry Andric return error("Invalid ID"); 29257a7e6055SDimitry Andric Func->setGC(GCTable[Record[8] - 1]); 29267a7e6055SDimitry Andric } 29277a7e6055SDimitry Andric GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None; 29287a7e6055SDimitry Andric if (Record.size() > 9) 29297a7e6055SDimitry Andric UnnamedAddr = getDecodedUnnamedAddrType(Record[9]); 29307a7e6055SDimitry Andric Func->setUnnamedAddr(UnnamedAddr); 29317a7e6055SDimitry Andric if (Record.size() > 10 && Record[10] != 0) 29327a7e6055SDimitry Andric FunctionPrologues.push_back(std::make_pair(Func, Record[10] - 1)); 29337a7e6055SDimitry Andric 29347a7e6055SDimitry Andric if (Record.size() > 11) 29357a7e6055SDimitry Andric Func->setDLLStorageClass(getDecodedDLLStorageClass(Record[11])); 29367a7e6055SDimitry Andric else 29377a7e6055SDimitry Andric upgradeDLLImportExportLinkage(Func, RawLinkage); 29387a7e6055SDimitry Andric 29397a7e6055SDimitry Andric if (Record.size() > 12) { 29407a7e6055SDimitry Andric if (unsigned ComdatID = Record[12]) { 29417a7e6055SDimitry Andric if (ComdatID > ComdatList.size()) 29427a7e6055SDimitry Andric return error("Invalid function comdat ID"); 29437a7e6055SDimitry Andric Func->setComdat(ComdatList[ComdatID - 1]); 29447a7e6055SDimitry Andric } 29457a7e6055SDimitry Andric } else if (hasImplicitComdat(RawLinkage)) { 29467a7e6055SDimitry Andric Func->setComdat(reinterpret_cast<Comdat *>(1)); 29477a7e6055SDimitry Andric } 29487a7e6055SDimitry Andric 29497a7e6055SDimitry Andric if (Record.size() > 13 && Record[13] != 0) 29507a7e6055SDimitry Andric FunctionPrefixes.push_back(std::make_pair(Func, Record[13] - 1)); 29517a7e6055SDimitry Andric 29527a7e6055SDimitry Andric if (Record.size() > 14 && Record[14] != 0) 29537a7e6055SDimitry Andric FunctionPersonalityFns.push_back(std::make_pair(Func, Record[14] - 1)); 29547a7e6055SDimitry Andric 29557a7e6055SDimitry Andric ValueList.push_back(Func); 29567a7e6055SDimitry Andric 29577a7e6055SDimitry Andric // If this is a function with a body, remember the prototype we are 29587a7e6055SDimitry Andric // creating now, so that we can match up the body with them later. 29597a7e6055SDimitry Andric if (!isProto) { 29607a7e6055SDimitry Andric Func->setIsMaterializable(true); 29617a7e6055SDimitry Andric FunctionsWithBodies.push_back(Func); 29627a7e6055SDimitry Andric DeferredFunctionInfo[Func] = 0; 29637a7e6055SDimitry Andric } 29647a7e6055SDimitry Andric return Error::success(); 29657a7e6055SDimitry Andric } 29667a7e6055SDimitry Andric 29677a7e6055SDimitry Andric Error BitcodeReader::parseGlobalIndirectSymbolRecord( 29687a7e6055SDimitry Andric unsigned BitCode, ArrayRef<uint64_t> Record) { 29696bc11b14SDimitry Andric // v1 ALIAS_OLD: [alias type, aliasee val#, linkage] (name in VST) 29706bc11b14SDimitry Andric // v1 ALIAS: [alias type, addrspace, aliasee val#, linkage, visibility, 29716bc11b14SDimitry Andric // dllstorageclass] (name in VST) 29726bc11b14SDimitry Andric // v1 IFUNC: [alias type, addrspace, aliasee val#, linkage, 29736bc11b14SDimitry Andric // visibility, dllstorageclass] (name in VST) 29746bc11b14SDimitry Andric // v2: [strtab_offset, strtab_size, v1] 29756bc11b14SDimitry Andric StringRef Name; 29766bc11b14SDimitry Andric std::tie(Name, Record) = readNameFromStrtab(Record); 29776bc11b14SDimitry Andric 29787a7e6055SDimitry Andric bool NewRecord = BitCode != bitc::MODULE_CODE_ALIAS_OLD; 29797a7e6055SDimitry Andric if (Record.size() < (3 + (unsigned)NewRecord)) 29807a7e6055SDimitry Andric return error("Invalid record"); 29817a7e6055SDimitry Andric unsigned OpNum = 0; 29827a7e6055SDimitry Andric Type *Ty = getTypeByID(Record[OpNum++]); 29837a7e6055SDimitry Andric if (!Ty) 29847a7e6055SDimitry Andric return error("Invalid record"); 29857a7e6055SDimitry Andric 29867a7e6055SDimitry Andric unsigned AddrSpace; 29877a7e6055SDimitry Andric if (!NewRecord) { 29887a7e6055SDimitry Andric auto *PTy = dyn_cast<PointerType>(Ty); 29897a7e6055SDimitry Andric if (!PTy) 29907a7e6055SDimitry Andric return error("Invalid type for value"); 29917a7e6055SDimitry Andric Ty = PTy->getElementType(); 29927a7e6055SDimitry Andric AddrSpace = PTy->getAddressSpace(); 29937a7e6055SDimitry Andric } else { 29947a7e6055SDimitry Andric AddrSpace = Record[OpNum++]; 29957a7e6055SDimitry Andric } 29967a7e6055SDimitry Andric 29977a7e6055SDimitry Andric auto Val = Record[OpNum++]; 29987a7e6055SDimitry Andric auto Linkage = Record[OpNum++]; 29997a7e6055SDimitry Andric GlobalIndirectSymbol *NewGA; 30007a7e6055SDimitry Andric if (BitCode == bitc::MODULE_CODE_ALIAS || 30017a7e6055SDimitry Andric BitCode == bitc::MODULE_CODE_ALIAS_OLD) 30026bc11b14SDimitry Andric NewGA = GlobalAlias::create(Ty, AddrSpace, getDecodedLinkage(Linkage), Name, 30037a7e6055SDimitry Andric TheModule); 30047a7e6055SDimitry Andric else 30056bc11b14SDimitry Andric NewGA = GlobalIFunc::create(Ty, AddrSpace, getDecodedLinkage(Linkage), Name, 30067a7e6055SDimitry Andric nullptr, TheModule); 30077a7e6055SDimitry Andric // Old bitcode files didn't have visibility field. 30087a7e6055SDimitry Andric // Local linkage must have default visibility. 30097a7e6055SDimitry Andric if (OpNum != Record.size()) { 30107a7e6055SDimitry Andric auto VisInd = OpNum++; 30117a7e6055SDimitry Andric if (!NewGA->hasLocalLinkage()) 30127a7e6055SDimitry Andric // FIXME: Change to an error if non-default in 4.0. 30137a7e6055SDimitry Andric NewGA->setVisibility(getDecodedVisibility(Record[VisInd])); 30147a7e6055SDimitry Andric } 30157a7e6055SDimitry Andric if (OpNum != Record.size()) 30167a7e6055SDimitry Andric NewGA->setDLLStorageClass(getDecodedDLLStorageClass(Record[OpNum++])); 30177a7e6055SDimitry Andric else 30187a7e6055SDimitry Andric upgradeDLLImportExportLinkage(NewGA, Linkage); 30197a7e6055SDimitry Andric if (OpNum != Record.size()) 30207a7e6055SDimitry Andric NewGA->setThreadLocalMode(getDecodedThreadLocalMode(Record[OpNum++])); 30217a7e6055SDimitry Andric if (OpNum != Record.size()) 30227a7e6055SDimitry Andric NewGA->setUnnamedAddr(getDecodedUnnamedAddrType(Record[OpNum++])); 30237a7e6055SDimitry Andric ValueList.push_back(NewGA); 30247a7e6055SDimitry Andric IndirectSymbolInits.push_back(std::make_pair(NewGA, Val)); 30257a7e6055SDimitry Andric return Error::success(); 30267a7e6055SDimitry Andric } 30277a7e6055SDimitry Andric 3028d88c1a5aSDimitry Andric Error BitcodeReader::parseModule(uint64_t ResumeBit, 30297d523365SDimitry Andric bool ShouldLazyLoadMetadata) { 30307d523365SDimitry Andric if (ResumeBit) 30317d523365SDimitry Andric Stream.JumpToBit(ResumeBit); 3032dff0c46cSDimitry Andric else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID)) 30338f0fd8f6SDimitry Andric return error("Invalid record"); 3034dff0c46cSDimitry Andric 3035dff0c46cSDimitry Andric SmallVector<uint64_t, 64> Record; 3036dff0c46cSDimitry Andric 3037dff0c46cSDimitry Andric // Read all the records for this module. 3038d88c1a5aSDimitry Andric while (true) { 3039139f7f9bSDimitry Andric BitstreamEntry Entry = Stream.advance(); 3040dff0c46cSDimitry Andric 3041139f7f9bSDimitry Andric switch (Entry.Kind) { 3042139f7f9bSDimitry Andric case BitstreamEntry::Error: 30438f0fd8f6SDimitry Andric return error("Malformed block"); 3044139f7f9bSDimitry Andric case BitstreamEntry::EndBlock: 30458f0fd8f6SDimitry Andric return globalCleanup(); 3046dff0c46cSDimitry Andric 3047139f7f9bSDimitry Andric case BitstreamEntry::SubBlock: 3048139f7f9bSDimitry Andric switch (Entry.ID) { 3049f22ef01cSRoman Divacky default: // Skip unknown content. 3050f22ef01cSRoman Divacky if (Stream.SkipBlock()) 30518f0fd8f6SDimitry Andric return error("Invalid record"); 3052f22ef01cSRoman Divacky break; 3053f22ef01cSRoman Divacky case bitc::BLOCKINFO_BLOCK_ID: 3054d88c1a5aSDimitry Andric if (readBlockInfo()) 30558f0fd8f6SDimitry Andric return error("Malformed block"); 3056f22ef01cSRoman Divacky break; 3057f22ef01cSRoman Divacky case bitc::PARAMATTR_BLOCK_ID: 3058d88c1a5aSDimitry Andric if (Error Err = parseAttributeBlock()) 3059d88c1a5aSDimitry Andric return Err; 3060f22ef01cSRoman Divacky break; 3061139f7f9bSDimitry Andric case bitc::PARAMATTR_GROUP_BLOCK_ID: 3062d88c1a5aSDimitry Andric if (Error Err = parseAttributeGroupBlock()) 3063d88c1a5aSDimitry Andric return Err; 3064139f7f9bSDimitry Andric break; 306517a519f9SDimitry Andric case bitc::TYPE_BLOCK_ID_NEW: 3066d88c1a5aSDimitry Andric if (Error Err = parseTypeTable()) 3067d88c1a5aSDimitry Andric return Err; 3068f22ef01cSRoman Divacky break; 3069f22ef01cSRoman Divacky case bitc::VALUE_SYMTAB_BLOCK_ID: 30707d523365SDimitry Andric if (!SeenValueSymbolTable) { 30717d523365SDimitry Andric // Either this is an old form VST without function index and an 30727d523365SDimitry Andric // associated VST forward declaration record (which would have caused 30737d523365SDimitry Andric // the VST to be jumped to and parsed before it was encountered 30747d523365SDimitry Andric // normally in the stream), or there were no function blocks to 30757d523365SDimitry Andric // trigger an earlier parsing of the VST. 30767d523365SDimitry Andric assert(VSTOffset == 0 || FunctionsWithBodies.empty()); 3077d88c1a5aSDimitry Andric if (Error Err = parseValueSymbolTable()) 3078d88c1a5aSDimitry Andric return Err; 3079dff0c46cSDimitry Andric SeenValueSymbolTable = true; 30807d523365SDimitry Andric } else { 30817d523365SDimitry Andric // We must have had a VST forward declaration record, which caused 30827d523365SDimitry Andric // the parser to jump to and parse the VST earlier. 30837d523365SDimitry Andric assert(VSTOffset > 0); 30847d523365SDimitry Andric if (Stream.SkipBlock()) 30857d523365SDimitry Andric return error("Invalid record"); 30867d523365SDimitry Andric } 3087f22ef01cSRoman Divacky break; 3088f22ef01cSRoman Divacky case bitc::CONSTANTS_BLOCK_ID: 3089d88c1a5aSDimitry Andric if (Error Err = parseConstants()) 3090d88c1a5aSDimitry Andric return Err; 3091d88c1a5aSDimitry Andric if (Error Err = resolveGlobalAndIndirectSymbolInits()) 3092d88c1a5aSDimitry Andric return Err; 3093f22ef01cSRoman Divacky break; 3094f22ef01cSRoman Divacky case bitc::METADATA_BLOCK_ID: 3095d88c1a5aSDimitry Andric if (ShouldLazyLoadMetadata) { 3096d88c1a5aSDimitry Andric if (Error Err = rememberAndSkipMetadata()) 3097d88c1a5aSDimitry Andric return Err; 3098ff0cc061SDimitry Andric break; 3099ff0cc061SDimitry Andric } 3100ff0cc061SDimitry Andric assert(DeferredMetadataInfo.empty() && "Unexpected deferred metadata"); 3101d88c1a5aSDimitry Andric if (Error Err = MDLoader->parseModuleMetadata()) 3102d88c1a5aSDimitry Andric return Err; 31037d523365SDimitry Andric break; 31047d523365SDimitry Andric case bitc::METADATA_KIND_BLOCK_ID: 3105d88c1a5aSDimitry Andric if (Error Err = MDLoader->parseMetadataKinds()) 3106d88c1a5aSDimitry Andric return Err; 3107f22ef01cSRoman Divacky break; 3108f22ef01cSRoman Divacky case bitc::FUNCTION_BLOCK_ID: 3109f22ef01cSRoman Divacky // If this is the first function body we've seen, reverse the 3110f22ef01cSRoman Divacky // FunctionsWithBodies list. 3111dff0c46cSDimitry Andric if (!SeenFirstFunctionBody) { 3112f22ef01cSRoman Divacky std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end()); 3113d88c1a5aSDimitry Andric if (Error Err = globalCleanup()) 3114d88c1a5aSDimitry Andric return Err; 3115dff0c46cSDimitry Andric SeenFirstFunctionBody = true; 3116f22ef01cSRoman Divacky } 3117f22ef01cSRoman Divacky 31187d523365SDimitry Andric if (VSTOffset > 0) { 31197d523365SDimitry Andric // If we have a VST forward declaration record, make sure we 31207d523365SDimitry Andric // parse the VST now if we haven't already. It is needed to 31217d523365SDimitry Andric // set up the DeferredFunctionInfo vector for lazy reading. 31227d523365SDimitry Andric if (!SeenValueSymbolTable) { 3123d88c1a5aSDimitry Andric if (Error Err = BitcodeReader::parseValueSymbolTable(VSTOffset)) 3124d88c1a5aSDimitry Andric return Err; 31257d523365SDimitry Andric SeenValueSymbolTable = true; 31267d523365SDimitry Andric // Fall through so that we record the NextUnreadBit below. 31277d523365SDimitry Andric // This is necessary in case we have an anonymous function that 31287d523365SDimitry Andric // is later materialized. Since it will not have a VST entry we 31297d523365SDimitry Andric // need to fall back to the lazy parse to find its offset. 31307d523365SDimitry Andric } else { 31317d523365SDimitry Andric // If we have a VST forward declaration record, but have already 31327d523365SDimitry Andric // parsed the VST (just above, when the first function body was 31337d523365SDimitry Andric // encountered here), then we are resuming the parse after 31347d523365SDimitry Andric // materializing functions. The ResumeBit points to the 31357d523365SDimitry Andric // start of the last function block recorded in the 31367d523365SDimitry Andric // DeferredFunctionInfo map. Skip it. 31377d523365SDimitry Andric if (Stream.SkipBlock()) 31387d523365SDimitry Andric return error("Invalid record"); 31397d523365SDimitry Andric continue; 31407d523365SDimitry Andric } 31417d523365SDimitry Andric } 31427d523365SDimitry Andric 31437d523365SDimitry Andric // Support older bitcode files that did not have the function 31447d523365SDimitry Andric // index in the VST, nor a VST forward declaration record, as 31457d523365SDimitry Andric // well as anonymous functions that do not have VST entries. 31467d523365SDimitry Andric // Build the DeferredFunctionInfo vector on the fly. 3147d88c1a5aSDimitry Andric if (Error Err = rememberAndSkipFunctionBody()) 3148d88c1a5aSDimitry Andric return Err; 31497d523365SDimitry Andric 31503dac3a9bSDimitry Andric // Suspend parsing when we reach the function bodies. Subsequent 31513dac3a9bSDimitry Andric // materialization calls will resume it when necessary. If the bitcode 31523dac3a9bSDimitry Andric // file is old, the symbol table will be at the end instead and will not 31533dac3a9bSDimitry Andric // have been seen yet. In this case, just finish the parse now. 31543dac3a9bSDimitry Andric if (SeenValueSymbolTable) { 3155dff0c46cSDimitry Andric NextUnreadBit = Stream.GetCurrentBitNo(); 3156d88c1a5aSDimitry Andric // After the VST has been parsed, we need to make sure intrinsic name 3157d88c1a5aSDimitry Andric // are auto-upgraded. 3158d88c1a5aSDimitry Andric return globalCleanup(); 3159dff0c46cSDimitry Andric } 3160dff0c46cSDimitry Andric break; 3161dff0c46cSDimitry Andric case bitc::USELIST_BLOCK_ID: 3162d88c1a5aSDimitry Andric if (Error Err = parseUseLists()) 3163d88c1a5aSDimitry Andric return Err; 3164f22ef01cSRoman Divacky break; 31657d523365SDimitry Andric case bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID: 3166d88c1a5aSDimitry Andric if (Error Err = parseOperandBundleTags()) 3167d88c1a5aSDimitry Andric return Err; 31687d523365SDimitry Andric break; 3169c4394386SDimitry Andric case bitc::SYNC_SCOPE_NAMES_BLOCK_ID: 3170c4394386SDimitry Andric if (Error Err = parseSyncScopeNames()) 3171c4394386SDimitry Andric return Err; 3172c4394386SDimitry Andric break; 3173f22ef01cSRoman Divacky } 3174f22ef01cSRoman Divacky continue; 3175139f7f9bSDimitry Andric 3176139f7f9bSDimitry Andric case BitstreamEntry::Record: 3177139f7f9bSDimitry Andric // The interesting case. 3178139f7f9bSDimitry Andric break; 3179f22ef01cSRoman Divacky } 3180f22ef01cSRoman Divacky 3181f22ef01cSRoman Divacky // Read a record. 31827d523365SDimitry Andric auto BitCode = Stream.readRecord(Entry.ID, Record); 31837d523365SDimitry Andric switch (BitCode) { 3184f22ef01cSRoman Divacky default: break; // Default behavior, ignore unknown content. 31857a7e6055SDimitry Andric case bitc::MODULE_CODE_VERSION: { 31867a7e6055SDimitry Andric Expected<unsigned> VersionOrErr = parseVersionRecord(Record); 31877a7e6055SDimitry Andric if (!VersionOrErr) 31887a7e6055SDimitry Andric return VersionOrErr.takeError(); 31897a7e6055SDimitry Andric UseRelativeIDs = *VersionOrErr >= 1; 31903861d79fSDimitry Andric break; 31913861d79fSDimitry Andric } 3192f22ef01cSRoman Divacky case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N] 3193f22ef01cSRoman Divacky std::string S; 31948f0fd8f6SDimitry Andric if (convertToString(Record, 0, S)) 31958f0fd8f6SDimitry Andric return error("Invalid record"); 3196f22ef01cSRoman Divacky TheModule->setTargetTriple(S); 3197f22ef01cSRoman Divacky break; 3198f22ef01cSRoman Divacky } 3199f22ef01cSRoman Divacky case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N] 3200f22ef01cSRoman Divacky std::string S; 32018f0fd8f6SDimitry Andric if (convertToString(Record, 0, S)) 32028f0fd8f6SDimitry Andric return error("Invalid record"); 3203f22ef01cSRoman Divacky TheModule->setDataLayout(S); 3204f22ef01cSRoman Divacky break; 3205f22ef01cSRoman Divacky } 3206f22ef01cSRoman Divacky case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N] 3207f22ef01cSRoman Divacky std::string S; 32088f0fd8f6SDimitry Andric if (convertToString(Record, 0, S)) 32098f0fd8f6SDimitry Andric return error("Invalid record"); 3210f22ef01cSRoman Divacky TheModule->setModuleInlineAsm(S); 3211f22ef01cSRoman Divacky break; 3212f22ef01cSRoman Divacky } 3213f22ef01cSRoman Divacky case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N] 3214139f7f9bSDimitry Andric // FIXME: Remove in 4.0. 3215f22ef01cSRoman Divacky std::string S; 32168f0fd8f6SDimitry Andric if (convertToString(Record, 0, S)) 32178f0fd8f6SDimitry Andric return error("Invalid record"); 3218139f7f9bSDimitry Andric // Ignore value. 3219f22ef01cSRoman Divacky break; 3220f22ef01cSRoman Divacky } 3221f22ef01cSRoman Divacky case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N] 3222f22ef01cSRoman Divacky std::string S; 32238f0fd8f6SDimitry Andric if (convertToString(Record, 0, S)) 32248f0fd8f6SDimitry Andric return error("Invalid record"); 3225f22ef01cSRoman Divacky SectionTable.push_back(S); 3226f22ef01cSRoman Divacky break; 3227f22ef01cSRoman Divacky } 3228f22ef01cSRoman Divacky case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N] 3229f22ef01cSRoman Divacky std::string S; 32308f0fd8f6SDimitry Andric if (convertToString(Record, 0, S)) 32318f0fd8f6SDimitry Andric return error("Invalid record"); 3232f22ef01cSRoman Divacky GCTable.push_back(S); 3233f22ef01cSRoman Divacky break; 3234f22ef01cSRoman Divacky } 32357a7e6055SDimitry Andric case bitc::MODULE_CODE_COMDAT: { 32367a7e6055SDimitry Andric if (Error Err = parseComdatRecord(Record)) 32377a7e6055SDimitry Andric return Err; 323891bc56edSDimitry Andric break; 323991bc56edSDimitry Andric } 3240f22ef01cSRoman Divacky case bitc::MODULE_CODE_GLOBALVAR: { 32417a7e6055SDimitry Andric if (Error Err = parseGlobalVarRecord(Record)) 3242d88c1a5aSDimitry Andric return Err; 3243f22ef01cSRoman Divacky break; 3244f22ef01cSRoman Divacky } 3245f22ef01cSRoman Divacky case bitc::MODULE_CODE_FUNCTION: { 32467a7e6055SDimitry Andric if (Error Err = parseFunctionRecord(Record)) 3247d88c1a5aSDimitry Andric return Err; 3248f22ef01cSRoman Divacky break; 3249f22ef01cSRoman Divacky } 32503ca95b02SDimitry Andric case bitc::MODULE_CODE_IFUNC: 32517d523365SDimitry Andric case bitc::MODULE_CODE_ALIAS: 32527d523365SDimitry Andric case bitc::MODULE_CODE_ALIAS_OLD: { 32537a7e6055SDimitry Andric if (Error Err = parseGlobalIndirectSymbolRecord(BitCode, Record)) 32547a7e6055SDimitry Andric return Err; 3255f22ef01cSRoman Divacky break; 3256f22ef01cSRoman Divacky } 32577d523365SDimitry Andric /// MODULE_CODE_VSTOFFSET: [offset] 32587d523365SDimitry Andric case bitc::MODULE_CODE_VSTOFFSET: 32597d523365SDimitry Andric if (Record.size() < 1) 32607d523365SDimitry Andric return error("Invalid record"); 3261d88c1a5aSDimitry Andric // Note that we subtract 1 here because the offset is relative to one word 3262d88c1a5aSDimitry Andric // before the start of the identification or module block, which was 3263d88c1a5aSDimitry Andric // historically always the start of the regular bitcode header. 3264d88c1a5aSDimitry Andric VSTOffset = Record[0] - 1; 32657d523365SDimitry Andric break; 32663ca95b02SDimitry Andric /// MODULE_CODE_SOURCE_FILENAME: [namechar x N] 32673ca95b02SDimitry Andric case bitc::MODULE_CODE_SOURCE_FILENAME: 32683ca95b02SDimitry Andric SmallString<128> ValueName; 32693ca95b02SDimitry Andric if (convertToString(Record, 0, ValueName)) 32707d523365SDimitry Andric return error("Invalid record"); 32713ca95b02SDimitry Andric TheModule->setSourceFileName(ValueName); 32727d523365SDimitry Andric break; 3273f22ef01cSRoman Divacky } 3274f22ef01cSRoman Divacky Record.clear(); 3275f22ef01cSRoman Divacky } 3276f22ef01cSRoman Divacky } 3277f22ef01cSRoman Divacky 3278d88c1a5aSDimitry Andric Error BitcodeReader::parseBitcodeInto(Module *M, bool ShouldLazyLoadMetadata, 3279d88c1a5aSDimitry Andric bool IsImporting) { 32808f0fd8f6SDimitry Andric TheModule = M; 3281d88c1a5aSDimitry Andric MDLoader = MetadataLoader(Stream, *M, ValueList, IsImporting, 3282d88c1a5aSDimitry Andric [&](unsigned ID) { return getTypeByID(ID); }); 32837d523365SDimitry Andric return parseModule(0, ShouldLazyLoadMetadata); 3284f22ef01cSRoman Divacky } 3285f22ef01cSRoman Divacky 32862754fe60SDimitry Andric 3287d88c1a5aSDimitry Andric Error BitcodeReader::typeCheckLoadStoreInst(Type *ValType, Type *PtrType) { 3288ff0cc061SDimitry Andric if (!isa<PointerType>(PtrType)) 3289d88c1a5aSDimitry Andric return error("Load/Store operand is not a pointer type"); 3290ff0cc061SDimitry Andric Type *ElemType = cast<PointerType>(PtrType)->getElementType(); 3291ff0cc061SDimitry Andric 3292ff0cc061SDimitry Andric if (ValType && ValType != ElemType) 3293d88c1a5aSDimitry Andric return error("Explicit load/store type does not match pointee " 32947d523365SDimitry Andric "type of pointer operand"); 3295ff0cc061SDimitry Andric if (!PointerType::isLoadableOrStorableType(ElemType)) 3296d88c1a5aSDimitry Andric return error("Cannot load/store from pointer"); 3297d88c1a5aSDimitry Andric return Error::success(); 3298ff0cc061SDimitry Andric } 3299ff0cc061SDimitry Andric 33008f0fd8f6SDimitry Andric /// Lazily parse the specified function body block. 3301d88c1a5aSDimitry Andric Error BitcodeReader::parseFunctionBody(Function *F) { 3302f22ef01cSRoman Divacky if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID)) 33038f0fd8f6SDimitry Andric return error("Invalid record"); 3304f22ef01cSRoman Divacky 33053ca95b02SDimitry Andric // Unexpected unresolved metadata when parsing function. 3306d88c1a5aSDimitry Andric if (MDLoader->hasFwdRefs()) 33073ca95b02SDimitry Andric return error("Invalid function metadata: incoming forward references"); 33083ca95b02SDimitry Andric 3309f22ef01cSRoman Divacky InstructionList.clear(); 3310f22ef01cSRoman Divacky unsigned ModuleValueListSize = ValueList.size(); 3311d88c1a5aSDimitry Andric unsigned ModuleMDLoaderSize = MDLoader->size(); 3312f22ef01cSRoman Divacky 3313f22ef01cSRoman Divacky // Add all the function arguments to the value table. 33147d523365SDimitry Andric for (Argument &I : F->args()) 33157d523365SDimitry Andric ValueList.push_back(&I); 3316f22ef01cSRoman Divacky 3317f22ef01cSRoman Divacky unsigned NextValueNo = ValueList.size(); 331891bc56edSDimitry Andric BasicBlock *CurBB = nullptr; 3319f22ef01cSRoman Divacky unsigned CurBBNo = 0; 3320f22ef01cSRoman Divacky 3321f22ef01cSRoman Divacky DebugLoc LastLoc; 332239d628a0SDimitry Andric auto getLastInstruction = [&]() -> Instruction * { 332339d628a0SDimitry Andric if (CurBB && !CurBB->empty()) 332439d628a0SDimitry Andric return &CurBB->back(); 332539d628a0SDimitry Andric else if (CurBBNo && FunctionBBs[CurBBNo - 1] && 332639d628a0SDimitry Andric !FunctionBBs[CurBBNo - 1]->empty()) 332739d628a0SDimitry Andric return &FunctionBBs[CurBBNo - 1]->back(); 332839d628a0SDimitry Andric return nullptr; 332939d628a0SDimitry Andric }; 3330f22ef01cSRoman Divacky 33317d523365SDimitry Andric std::vector<OperandBundleDef> OperandBundles; 33327d523365SDimitry Andric 3333f22ef01cSRoman Divacky // Read all the records. 3334f22ef01cSRoman Divacky SmallVector<uint64_t, 64> Record; 3335d88c1a5aSDimitry Andric 3336d88c1a5aSDimitry Andric while (true) { 3337139f7f9bSDimitry Andric BitstreamEntry Entry = Stream.advance(); 3338f22ef01cSRoman Divacky 3339139f7f9bSDimitry Andric switch (Entry.Kind) { 3340139f7f9bSDimitry Andric case BitstreamEntry::Error: 33418f0fd8f6SDimitry Andric return error("Malformed block"); 3342139f7f9bSDimitry Andric case BitstreamEntry::EndBlock: 3343139f7f9bSDimitry Andric goto OutOfRecordLoop; 3344139f7f9bSDimitry Andric 3345139f7f9bSDimitry Andric case BitstreamEntry::SubBlock: 3346139f7f9bSDimitry Andric switch (Entry.ID) { 3347f22ef01cSRoman Divacky default: // Skip unknown content. 3348f22ef01cSRoman Divacky if (Stream.SkipBlock()) 33498f0fd8f6SDimitry Andric return error("Invalid record"); 3350f22ef01cSRoman Divacky break; 3351f22ef01cSRoman Divacky case bitc::CONSTANTS_BLOCK_ID: 3352d88c1a5aSDimitry Andric if (Error Err = parseConstants()) 3353d88c1a5aSDimitry Andric return Err; 3354f22ef01cSRoman Divacky NextValueNo = ValueList.size(); 3355f22ef01cSRoman Divacky break; 3356f22ef01cSRoman Divacky case bitc::VALUE_SYMTAB_BLOCK_ID: 3357d88c1a5aSDimitry Andric if (Error Err = parseValueSymbolTable()) 3358d88c1a5aSDimitry Andric return Err; 3359f22ef01cSRoman Divacky break; 3360f22ef01cSRoman Divacky case bitc::METADATA_ATTACHMENT_ID: 3361d88c1a5aSDimitry Andric if (Error Err = MDLoader->parseMetadataAttachment(*F, InstructionList)) 3362d88c1a5aSDimitry Andric return Err; 3363f22ef01cSRoman Divacky break; 3364f22ef01cSRoman Divacky case bitc::METADATA_BLOCK_ID: 3365d88c1a5aSDimitry Andric assert(DeferredMetadataInfo.empty() && 3366d88c1a5aSDimitry Andric "Must read all module-level metadata before function-level"); 3367d88c1a5aSDimitry Andric if (Error Err = MDLoader->parseFunctionMetadata()) 3368d88c1a5aSDimitry Andric return Err; 3369f22ef01cSRoman Divacky break; 337039d628a0SDimitry Andric case bitc::USELIST_BLOCK_ID: 3371d88c1a5aSDimitry Andric if (Error Err = parseUseLists()) 3372d88c1a5aSDimitry Andric return Err; 337339d628a0SDimitry Andric break; 3374f22ef01cSRoman Divacky } 3375f22ef01cSRoman Divacky continue; 3376f22ef01cSRoman Divacky 3377139f7f9bSDimitry Andric case BitstreamEntry::Record: 3378139f7f9bSDimitry Andric // The interesting case. 3379139f7f9bSDimitry Andric break; 3380f22ef01cSRoman Divacky } 3381f22ef01cSRoman Divacky 3382f22ef01cSRoman Divacky // Read a record. 3383f22ef01cSRoman Divacky Record.clear(); 338491bc56edSDimitry Andric Instruction *I = nullptr; 3385139f7f9bSDimitry Andric unsigned BitCode = Stream.readRecord(Entry.ID, Record); 3386f22ef01cSRoman Divacky switch (BitCode) { 3387f22ef01cSRoman Divacky default: // Default behavior: reject 33888f0fd8f6SDimitry Andric return error("Invalid value"); 338939d628a0SDimitry Andric case bitc::FUNC_CODE_DECLAREBLOCKS: { // DECLAREBLOCKS: [nblocks] 3390f22ef01cSRoman Divacky if (Record.size() < 1 || Record[0] == 0) 33918f0fd8f6SDimitry Andric return error("Invalid record"); 3392f22ef01cSRoman Divacky // Create all the basic blocks for the function. 3393f22ef01cSRoman Divacky FunctionBBs.resize(Record[0]); 339439d628a0SDimitry Andric 339539d628a0SDimitry Andric // See if anything took the address of blocks in this function. 339639d628a0SDimitry Andric auto BBFRI = BasicBlockFwdRefs.find(F); 339739d628a0SDimitry Andric if (BBFRI == BasicBlockFwdRefs.end()) { 3398f22ef01cSRoman Divacky for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i) 3399f22ef01cSRoman Divacky FunctionBBs[i] = BasicBlock::Create(Context, "", F); 340039d628a0SDimitry Andric } else { 340139d628a0SDimitry Andric auto &BBRefs = BBFRI->second; 340239d628a0SDimitry Andric // Check for invalid basic block references. 340339d628a0SDimitry Andric if (BBRefs.size() > FunctionBBs.size()) 34048f0fd8f6SDimitry Andric return error("Invalid ID"); 340539d628a0SDimitry Andric assert(!BBRefs.empty() && "Unexpected empty array"); 340639d628a0SDimitry Andric assert(!BBRefs.front() && "Invalid reference to entry block"); 340739d628a0SDimitry Andric for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E; 340839d628a0SDimitry Andric ++I) 340939d628a0SDimitry Andric if (I < RE && BBRefs[I]) { 341039d628a0SDimitry Andric BBRefs[I]->insertInto(F); 341139d628a0SDimitry Andric FunctionBBs[I] = BBRefs[I]; 341239d628a0SDimitry Andric } else { 341339d628a0SDimitry Andric FunctionBBs[I] = BasicBlock::Create(Context, "", F); 341439d628a0SDimitry Andric } 341539d628a0SDimitry Andric 341639d628a0SDimitry Andric // Erase from the table. 341739d628a0SDimitry Andric BasicBlockFwdRefs.erase(BBFRI); 341839d628a0SDimitry Andric } 341939d628a0SDimitry Andric 3420f22ef01cSRoman Divacky CurBB = FunctionBBs[0]; 3421f22ef01cSRoman Divacky continue; 342239d628a0SDimitry Andric } 3423f22ef01cSRoman Divacky 3424f22ef01cSRoman Divacky case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN 3425f22ef01cSRoman Divacky // This record indicates that the last instruction is at the same 3426f22ef01cSRoman Divacky // location as the previous instruction with a location. 342739d628a0SDimitry Andric I = getLastInstruction(); 3428f22ef01cSRoman Divacky 342991bc56edSDimitry Andric if (!I) 34308f0fd8f6SDimitry Andric return error("Invalid record"); 3431f22ef01cSRoman Divacky I->setDebugLoc(LastLoc); 343291bc56edSDimitry Andric I = nullptr; 3433f22ef01cSRoman Divacky continue; 3434f22ef01cSRoman Divacky 343517a519f9SDimitry Andric case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia] 343639d628a0SDimitry Andric I = getLastInstruction(); 343791bc56edSDimitry Andric if (!I || Record.size() < 4) 34388f0fd8f6SDimitry Andric return error("Invalid record"); 3439f22ef01cSRoman Divacky 3440f22ef01cSRoman Divacky unsigned Line = Record[0], Col = Record[1]; 3441f22ef01cSRoman Divacky unsigned ScopeID = Record[2], IAID = Record[3]; 3442f22ef01cSRoman Divacky 344391bc56edSDimitry Andric MDNode *Scope = nullptr, *IA = nullptr; 34443ca95b02SDimitry Andric if (ScopeID) { 3445d88c1a5aSDimitry Andric Scope = MDLoader->getMDNodeFwdRefOrNull(ScopeID - 1); 34463ca95b02SDimitry Andric if (!Scope) 34473ca95b02SDimitry Andric return error("Invalid record"); 34483ca95b02SDimitry Andric } 34493ca95b02SDimitry Andric if (IAID) { 3450d88c1a5aSDimitry Andric IA = MDLoader->getMDNodeFwdRefOrNull(IAID - 1); 34513ca95b02SDimitry Andric if (!IA) 34523ca95b02SDimitry Andric return error("Invalid record"); 34533ca95b02SDimitry Andric } 3454f22ef01cSRoman Divacky LastLoc = DebugLoc::get(Line, Col, Scope, IA); 3455f22ef01cSRoman Divacky I->setDebugLoc(LastLoc); 345691bc56edSDimitry Andric I = nullptr; 3457f22ef01cSRoman Divacky continue; 3458f22ef01cSRoman Divacky } 3459f22ef01cSRoman Divacky 3460f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode] 3461f22ef01cSRoman Divacky unsigned OpNum = 0; 3462f22ef01cSRoman Divacky Value *LHS, *RHS; 3463f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, LHS) || 34643861d79fSDimitry Andric popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) || 3465f22ef01cSRoman Divacky OpNum+1 > Record.size()) 34668f0fd8f6SDimitry Andric return error("Invalid record"); 3467f22ef01cSRoman Divacky 34688f0fd8f6SDimitry Andric int Opc = getDecodedBinaryOpcode(Record[OpNum++], LHS->getType()); 3469f785676fSDimitry Andric if (Opc == -1) 34708f0fd8f6SDimitry Andric return error("Invalid record"); 3471f22ef01cSRoman Divacky I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS); 3472f22ef01cSRoman Divacky InstructionList.push_back(I); 3473f22ef01cSRoman Divacky if (OpNum < Record.size()) { 3474f22ef01cSRoman Divacky if (Opc == Instruction::Add || 3475f22ef01cSRoman Divacky Opc == Instruction::Sub || 34762754fe60SDimitry Andric Opc == Instruction::Mul || 34772754fe60SDimitry Andric Opc == Instruction::Shl) { 3478f22ef01cSRoman Divacky if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP)) 3479f22ef01cSRoman Divacky cast<BinaryOperator>(I)->setHasNoSignedWrap(true); 3480f22ef01cSRoman Divacky if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP)) 3481f22ef01cSRoman Divacky cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true); 34822754fe60SDimitry Andric } else if (Opc == Instruction::SDiv || 34832754fe60SDimitry Andric Opc == Instruction::UDiv || 34842754fe60SDimitry Andric Opc == Instruction::LShr || 34852754fe60SDimitry Andric Opc == Instruction::AShr) { 34862754fe60SDimitry Andric if (Record[OpNum] & (1 << bitc::PEO_EXACT)) 3487f22ef01cSRoman Divacky cast<BinaryOperator>(I)->setIsExact(true); 3488139f7f9bSDimitry Andric } else if (isa<FPMathOperator>(I)) { 3489875ed548SDimitry Andric FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]); 3490139f7f9bSDimitry Andric if (FMF.any()) 3491139f7f9bSDimitry Andric I->setFastMathFlags(FMF); 3492f22ef01cSRoman Divacky } 3493139f7f9bSDimitry Andric 3494f22ef01cSRoman Divacky } 3495f22ef01cSRoman Divacky break; 3496f22ef01cSRoman Divacky } 3497f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc] 3498f22ef01cSRoman Divacky unsigned OpNum = 0; 3499f22ef01cSRoman Divacky Value *Op; 3500f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, Op) || 3501f22ef01cSRoman Divacky OpNum+2 != Record.size()) 35028f0fd8f6SDimitry Andric return error("Invalid record"); 3503f22ef01cSRoman Divacky 35046122f3e6SDimitry Andric Type *ResTy = getTypeByID(Record[OpNum]); 35058f0fd8f6SDimitry Andric int Opc = getDecodedCastOpcode(Record[OpNum + 1]); 350691bc56edSDimitry Andric if (Opc == -1 || !ResTy) 35078f0fd8f6SDimitry Andric return error("Invalid record"); 350891bc56edSDimitry Andric Instruction *Temp = nullptr; 3509f785676fSDimitry Andric if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) { 3510f785676fSDimitry Andric if (Temp) { 3511f785676fSDimitry Andric InstructionList.push_back(Temp); 3512f785676fSDimitry Andric CurBB->getInstList().push_back(Temp); 3513f785676fSDimitry Andric } 3514f785676fSDimitry Andric } else { 35157d523365SDimitry Andric auto CastOp = (Instruction::CastOps)Opc; 35167d523365SDimitry Andric if (!CastInst::castIsValid(CastOp, Op, ResTy)) 35177d523365SDimitry Andric return error("Invalid cast"); 35187d523365SDimitry Andric I = CastInst::Create(CastOp, Op, ResTy); 3519f785676fSDimitry Andric } 3520f22ef01cSRoman Divacky InstructionList.push_back(I); 3521f22ef01cSRoman Divacky break; 3522f22ef01cSRoman Divacky } 3523ff0cc061SDimitry Andric case bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD: 3524ff0cc061SDimitry Andric case bitc::FUNC_CODE_INST_GEP_OLD: 3525ff0cc061SDimitry Andric case bitc::FUNC_CODE_INST_GEP: { // GEP: type, [n x operands] 3526f22ef01cSRoman Divacky unsigned OpNum = 0; 3527ff0cc061SDimitry Andric 3528ff0cc061SDimitry Andric Type *Ty; 3529ff0cc061SDimitry Andric bool InBounds; 3530ff0cc061SDimitry Andric 3531ff0cc061SDimitry Andric if (BitCode == bitc::FUNC_CODE_INST_GEP) { 3532ff0cc061SDimitry Andric InBounds = Record[OpNum++]; 3533ff0cc061SDimitry Andric Ty = getTypeByID(Record[OpNum++]); 3534ff0cc061SDimitry Andric } else { 3535ff0cc061SDimitry Andric InBounds = BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD; 3536ff0cc061SDimitry Andric Ty = nullptr; 3537ff0cc061SDimitry Andric } 3538ff0cc061SDimitry Andric 3539f22ef01cSRoman Divacky Value *BasePtr; 3540f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr)) 35418f0fd8f6SDimitry Andric return error("Invalid record"); 3542f22ef01cSRoman Divacky 3543ff0cc061SDimitry Andric if (!Ty) 3544d88c1a5aSDimitry Andric Ty = cast<PointerType>(BasePtr->getType()->getScalarType()) 3545ff0cc061SDimitry Andric ->getElementType(); 3546ff0cc061SDimitry Andric else if (Ty != 3547d88c1a5aSDimitry Andric cast<PointerType>(BasePtr->getType()->getScalarType()) 3548ff0cc061SDimitry Andric ->getElementType()) 35498f0fd8f6SDimitry Andric return error( 3550ff0cc061SDimitry Andric "Explicit gep type does not match pointee type of pointer operand"); 3551ff0cc061SDimitry Andric 3552f22ef01cSRoman Divacky SmallVector<Value*, 16> GEPIdx; 3553f22ef01cSRoman Divacky while (OpNum != Record.size()) { 3554f22ef01cSRoman Divacky Value *Op; 3555f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 35568f0fd8f6SDimitry Andric return error("Invalid record"); 3557f22ef01cSRoman Divacky GEPIdx.push_back(Op); 3558f22ef01cSRoman Divacky } 3559f22ef01cSRoman Divacky 3560ff0cc061SDimitry Andric I = GetElementPtrInst::Create(Ty, BasePtr, GEPIdx); 3561ff0cc061SDimitry Andric 3562f22ef01cSRoman Divacky InstructionList.push_back(I); 3563ff0cc061SDimitry Andric if (InBounds) 3564f22ef01cSRoman Divacky cast<GetElementPtrInst>(I)->setIsInBounds(true); 3565f22ef01cSRoman Divacky break; 3566f22ef01cSRoman Divacky } 3567f22ef01cSRoman Divacky 3568f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_EXTRACTVAL: { 3569f22ef01cSRoman Divacky // EXTRACTVAL: [opty, opval, n x indices] 3570f22ef01cSRoman Divacky unsigned OpNum = 0; 3571f22ef01cSRoman Divacky Value *Agg; 3572f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, Agg)) 35738f0fd8f6SDimitry Andric return error("Invalid record"); 3574f22ef01cSRoman Divacky 3575ff0cc061SDimitry Andric unsigned RecSize = Record.size(); 3576ff0cc061SDimitry Andric if (OpNum == RecSize) 35778f0fd8f6SDimitry Andric return error("EXTRACTVAL: Invalid instruction with 0 indices"); 3578ff0cc061SDimitry Andric 3579f22ef01cSRoman Divacky SmallVector<unsigned, 4> EXTRACTVALIdx; 3580ff0cc061SDimitry Andric Type *CurTy = Agg->getType(); 3581ff0cc061SDimitry Andric for (; OpNum != RecSize; ++OpNum) { 3582ff0cc061SDimitry Andric bool IsArray = CurTy->isArrayTy(); 3583ff0cc061SDimitry Andric bool IsStruct = CurTy->isStructTy(); 3584f22ef01cSRoman Divacky uint64_t Index = Record[OpNum]; 3585ff0cc061SDimitry Andric 3586ff0cc061SDimitry Andric if (!IsStruct && !IsArray) 35878f0fd8f6SDimitry Andric return error("EXTRACTVAL: Invalid type"); 3588f22ef01cSRoman Divacky if ((unsigned)Index != Index) 35898f0fd8f6SDimitry Andric return error("Invalid value"); 3590ff0cc061SDimitry Andric if (IsStruct && Index >= CurTy->subtypes().size()) 35918f0fd8f6SDimitry Andric return error("EXTRACTVAL: Invalid struct index"); 3592ff0cc061SDimitry Andric if (IsArray && Index >= CurTy->getArrayNumElements()) 35938f0fd8f6SDimitry Andric return error("EXTRACTVAL: Invalid array index"); 3594f22ef01cSRoman Divacky EXTRACTVALIdx.push_back((unsigned)Index); 3595ff0cc061SDimitry Andric 3596ff0cc061SDimitry Andric if (IsStruct) 3597ff0cc061SDimitry Andric CurTy = CurTy->subtypes()[Index]; 3598ff0cc061SDimitry Andric else 3599ff0cc061SDimitry Andric CurTy = CurTy->subtypes()[0]; 3600f22ef01cSRoman Divacky } 3601f22ef01cSRoman Divacky 360217a519f9SDimitry Andric I = ExtractValueInst::Create(Agg, EXTRACTVALIdx); 3603f22ef01cSRoman Divacky InstructionList.push_back(I); 3604f22ef01cSRoman Divacky break; 3605f22ef01cSRoman Divacky } 3606f22ef01cSRoman Divacky 3607f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_INSERTVAL: { 3608f22ef01cSRoman Divacky // INSERTVAL: [opty, opval, opty, opval, n x indices] 3609f22ef01cSRoman Divacky unsigned OpNum = 0; 3610f22ef01cSRoman Divacky Value *Agg; 3611f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, Agg)) 36128f0fd8f6SDimitry Andric return error("Invalid record"); 3613f22ef01cSRoman Divacky Value *Val; 3614f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, Val)) 36158f0fd8f6SDimitry Andric return error("Invalid record"); 3616f22ef01cSRoman Divacky 3617ff0cc061SDimitry Andric unsigned RecSize = Record.size(); 3618ff0cc061SDimitry Andric if (OpNum == RecSize) 36198f0fd8f6SDimitry Andric return error("INSERTVAL: Invalid instruction with 0 indices"); 3620ff0cc061SDimitry Andric 3621f22ef01cSRoman Divacky SmallVector<unsigned, 4> INSERTVALIdx; 3622ff0cc061SDimitry Andric Type *CurTy = Agg->getType(); 3623ff0cc061SDimitry Andric for (; OpNum != RecSize; ++OpNum) { 3624ff0cc061SDimitry Andric bool IsArray = CurTy->isArrayTy(); 3625ff0cc061SDimitry Andric bool IsStruct = CurTy->isStructTy(); 3626f22ef01cSRoman Divacky uint64_t Index = Record[OpNum]; 3627ff0cc061SDimitry Andric 3628ff0cc061SDimitry Andric if (!IsStruct && !IsArray) 36298f0fd8f6SDimitry Andric return error("INSERTVAL: Invalid type"); 3630f22ef01cSRoman Divacky if ((unsigned)Index != Index) 36318f0fd8f6SDimitry Andric return error("Invalid value"); 3632ff0cc061SDimitry Andric if (IsStruct && Index >= CurTy->subtypes().size()) 36338f0fd8f6SDimitry Andric return error("INSERTVAL: Invalid struct index"); 3634ff0cc061SDimitry Andric if (IsArray && Index >= CurTy->getArrayNumElements()) 36358f0fd8f6SDimitry Andric return error("INSERTVAL: Invalid array index"); 3636ff0cc061SDimitry Andric 3637f22ef01cSRoman Divacky INSERTVALIdx.push_back((unsigned)Index); 3638ff0cc061SDimitry Andric if (IsStruct) 3639ff0cc061SDimitry Andric CurTy = CurTy->subtypes()[Index]; 3640ff0cc061SDimitry Andric else 3641ff0cc061SDimitry Andric CurTy = CurTy->subtypes()[0]; 3642f22ef01cSRoman Divacky } 3643f22ef01cSRoman Divacky 3644ff0cc061SDimitry Andric if (CurTy != Val->getType()) 36458f0fd8f6SDimitry Andric return error("Inserted value type doesn't match aggregate type"); 3646ff0cc061SDimitry Andric 364717a519f9SDimitry Andric I = InsertValueInst::Create(Agg, Val, INSERTVALIdx); 3648f22ef01cSRoman Divacky InstructionList.push_back(I); 3649f22ef01cSRoman Divacky break; 3650f22ef01cSRoman Divacky } 3651f22ef01cSRoman Divacky 3652f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval] 3653f22ef01cSRoman Divacky // obsolete form of select 3654f22ef01cSRoman Divacky // handles select i1 ... in old bitcode 3655f22ef01cSRoman Divacky unsigned OpNum = 0; 3656f22ef01cSRoman Divacky Value *TrueVal, *FalseVal, *Cond; 3657f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) || 36583861d79fSDimitry Andric popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) || 36593861d79fSDimitry Andric popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond)) 36608f0fd8f6SDimitry Andric return error("Invalid record"); 3661f22ef01cSRoman Divacky 3662f22ef01cSRoman Divacky I = SelectInst::Create(Cond, TrueVal, FalseVal); 3663f22ef01cSRoman Divacky InstructionList.push_back(I); 3664f22ef01cSRoman Divacky break; 3665f22ef01cSRoman Divacky } 3666f22ef01cSRoman Divacky 3667f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred] 3668f22ef01cSRoman Divacky // new form of select 3669f22ef01cSRoman Divacky // handles select i1 or select [N x i1] 3670f22ef01cSRoman Divacky unsigned OpNum = 0; 3671f22ef01cSRoman Divacky Value *TrueVal, *FalseVal, *Cond; 3672f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) || 36733861d79fSDimitry Andric popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) || 3674f22ef01cSRoman Divacky getValueTypePair(Record, OpNum, NextValueNo, Cond)) 36758f0fd8f6SDimitry Andric return error("Invalid record"); 3676f22ef01cSRoman Divacky 3677f22ef01cSRoman Divacky // select condition can be either i1 or [N x i1] 36786122f3e6SDimitry Andric if (VectorType* vector_type = 36796122f3e6SDimitry Andric dyn_cast<VectorType>(Cond->getType())) { 3680f22ef01cSRoman Divacky // expect <n x i1> 3681f22ef01cSRoman Divacky if (vector_type->getElementType() != Type::getInt1Ty(Context)) 36828f0fd8f6SDimitry Andric return error("Invalid type for value"); 3683f22ef01cSRoman Divacky } else { 3684f22ef01cSRoman Divacky // expect i1 3685f22ef01cSRoman Divacky if (Cond->getType() != Type::getInt1Ty(Context)) 36868f0fd8f6SDimitry Andric return error("Invalid type for value"); 3687f22ef01cSRoman Divacky } 3688f22ef01cSRoman Divacky 3689f22ef01cSRoman Divacky I = SelectInst::Create(Cond, TrueVal, FalseVal); 3690f22ef01cSRoman Divacky InstructionList.push_back(I); 3691f22ef01cSRoman Divacky break; 3692f22ef01cSRoman Divacky } 3693f22ef01cSRoman Divacky 3694f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval] 3695f22ef01cSRoman Divacky unsigned OpNum = 0; 3696f22ef01cSRoman Divacky Value *Vec, *Idx; 3697f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, Vec) || 369891bc56edSDimitry Andric getValueTypePair(Record, OpNum, NextValueNo, Idx)) 36998f0fd8f6SDimitry Andric return error("Invalid record"); 3700ff0cc061SDimitry Andric if (!Vec->getType()->isVectorTy()) 37018f0fd8f6SDimitry Andric return error("Invalid type for value"); 3702f22ef01cSRoman Divacky I = ExtractElementInst::Create(Vec, Idx); 3703f22ef01cSRoman Divacky InstructionList.push_back(I); 3704f22ef01cSRoman Divacky break; 3705f22ef01cSRoman Divacky } 3706f22ef01cSRoman Divacky 3707f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval] 3708f22ef01cSRoman Divacky unsigned OpNum = 0; 3709f22ef01cSRoman Divacky Value *Vec, *Elt, *Idx; 3710ff0cc061SDimitry Andric if (getValueTypePair(Record, OpNum, NextValueNo, Vec)) 37118f0fd8f6SDimitry Andric return error("Invalid record"); 3712ff0cc061SDimitry Andric if (!Vec->getType()->isVectorTy()) 37138f0fd8f6SDimitry Andric return error("Invalid type for value"); 3714ff0cc061SDimitry Andric if (popValue(Record, OpNum, NextValueNo, 3715f22ef01cSRoman Divacky cast<VectorType>(Vec->getType())->getElementType(), Elt) || 371691bc56edSDimitry Andric getValueTypePair(Record, OpNum, NextValueNo, Idx)) 37178f0fd8f6SDimitry Andric return error("Invalid record"); 3718f22ef01cSRoman Divacky I = InsertElementInst::Create(Vec, Elt, Idx); 3719f22ef01cSRoman Divacky InstructionList.push_back(I); 3720f22ef01cSRoman Divacky break; 3721f22ef01cSRoman Divacky } 3722f22ef01cSRoman Divacky 3723f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval] 3724f22ef01cSRoman Divacky unsigned OpNum = 0; 3725f22ef01cSRoman Divacky Value *Vec1, *Vec2, *Mask; 3726f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) || 37273861d79fSDimitry Andric popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2)) 37288f0fd8f6SDimitry Andric return error("Invalid record"); 3729f22ef01cSRoman Divacky 3730f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, Mask)) 37318f0fd8f6SDimitry Andric return error("Invalid record"); 3732ff0cc061SDimitry Andric if (!Vec1->getType()->isVectorTy() || !Vec2->getType()->isVectorTy()) 37338f0fd8f6SDimitry Andric return error("Invalid type for value"); 3734f22ef01cSRoman Divacky I = new ShuffleVectorInst(Vec1, Vec2, Mask); 3735f22ef01cSRoman Divacky InstructionList.push_back(I); 3736f22ef01cSRoman Divacky break; 3737f22ef01cSRoman Divacky } 3738f22ef01cSRoman Divacky 3739f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred] 3740f22ef01cSRoman Divacky // Old form of ICmp/FCmp returning bool 3741f22ef01cSRoman Divacky // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were 3742f22ef01cSRoman Divacky // both legal on vectors but had different behaviour. 3743f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred] 3744f22ef01cSRoman Divacky // FCmp/ICmp returning bool or vector of bool 3745f22ef01cSRoman Divacky 3746f22ef01cSRoman Divacky unsigned OpNum = 0; 3747f22ef01cSRoman Divacky Value *LHS, *RHS; 3748f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, LHS) || 3749875ed548SDimitry Andric popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS)) 3750875ed548SDimitry Andric return error("Invalid record"); 3751875ed548SDimitry Andric 3752875ed548SDimitry Andric unsigned PredVal = Record[OpNum]; 3753875ed548SDimitry Andric bool IsFP = LHS->getType()->isFPOrFPVectorTy(); 3754875ed548SDimitry Andric FastMathFlags FMF; 3755875ed548SDimitry Andric if (IsFP && Record.size() > OpNum+1) 3756875ed548SDimitry Andric FMF = getDecodedFastMathFlags(Record[++OpNum]); 3757875ed548SDimitry Andric 3758875ed548SDimitry Andric if (OpNum+1 != Record.size()) 37598f0fd8f6SDimitry Andric return error("Invalid record"); 3760f22ef01cSRoman Divacky 3761f22ef01cSRoman Divacky if (LHS->getType()->isFPOrFPVectorTy()) 3762875ed548SDimitry Andric I = new FCmpInst((FCmpInst::Predicate)PredVal, LHS, RHS); 3763f22ef01cSRoman Divacky else 3764875ed548SDimitry Andric I = new ICmpInst((ICmpInst::Predicate)PredVal, LHS, RHS); 3765875ed548SDimitry Andric 3766875ed548SDimitry Andric if (FMF.any()) 3767875ed548SDimitry Andric I->setFastMathFlags(FMF); 3768f22ef01cSRoman Divacky InstructionList.push_back(I); 3769f22ef01cSRoman Divacky break; 3770f22ef01cSRoman Divacky } 3771f22ef01cSRoman Divacky 3772f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>] 3773f22ef01cSRoman Divacky { 3774f22ef01cSRoman Divacky unsigned Size = Record.size(); 3775f22ef01cSRoman Divacky if (Size == 0) { 3776f22ef01cSRoman Divacky I = ReturnInst::Create(Context); 3777f22ef01cSRoman Divacky InstructionList.push_back(I); 3778f22ef01cSRoman Divacky break; 3779f22ef01cSRoman Divacky } 3780f22ef01cSRoman Divacky 3781f22ef01cSRoman Divacky unsigned OpNum = 0; 378291bc56edSDimitry Andric Value *Op = nullptr; 3783f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 37848f0fd8f6SDimitry Andric return error("Invalid record"); 378517a519f9SDimitry Andric if (OpNum != Record.size()) 37868f0fd8f6SDimitry Andric return error("Invalid record"); 3787f22ef01cSRoman Divacky 378817a519f9SDimitry Andric I = ReturnInst::Create(Context, Op); 3789f22ef01cSRoman Divacky InstructionList.push_back(I); 3790f22ef01cSRoman Divacky break; 3791f22ef01cSRoman Divacky } 3792f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#] 3793f22ef01cSRoman Divacky if (Record.size() != 1 && Record.size() != 3) 37948f0fd8f6SDimitry Andric return error("Invalid record"); 3795f22ef01cSRoman Divacky BasicBlock *TrueDest = getBasicBlock(Record[0]); 379691bc56edSDimitry Andric if (!TrueDest) 37978f0fd8f6SDimitry Andric return error("Invalid record"); 3798f22ef01cSRoman Divacky 3799f22ef01cSRoman Divacky if (Record.size() == 1) { 3800f22ef01cSRoman Divacky I = BranchInst::Create(TrueDest); 3801f22ef01cSRoman Divacky InstructionList.push_back(I); 3802f22ef01cSRoman Divacky } 3803f22ef01cSRoman Divacky else { 3804f22ef01cSRoman Divacky BasicBlock *FalseDest = getBasicBlock(Record[1]); 38053861d79fSDimitry Andric Value *Cond = getValue(Record, 2, NextValueNo, 38063861d79fSDimitry Andric Type::getInt1Ty(Context)); 380791bc56edSDimitry Andric if (!FalseDest || !Cond) 38088f0fd8f6SDimitry Andric return error("Invalid record"); 3809f22ef01cSRoman Divacky I = BranchInst::Create(TrueDest, FalseDest, Cond); 3810f22ef01cSRoman Divacky InstructionList.push_back(I); 3811f22ef01cSRoman Divacky } 3812f22ef01cSRoman Divacky break; 3813f22ef01cSRoman Divacky } 38147d523365SDimitry Andric case bitc::FUNC_CODE_INST_CLEANUPRET: { // CLEANUPRET: [val] or [val,bb#] 38157d523365SDimitry Andric if (Record.size() != 1 && Record.size() != 2) 38167d523365SDimitry Andric return error("Invalid record"); 38177d523365SDimitry Andric unsigned Idx = 0; 38187d523365SDimitry Andric Value *CleanupPad = 38197d523365SDimitry Andric getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context)); 38207d523365SDimitry Andric if (!CleanupPad) 38217d523365SDimitry Andric return error("Invalid record"); 38227d523365SDimitry Andric BasicBlock *UnwindDest = nullptr; 38237d523365SDimitry Andric if (Record.size() == 2) { 38247d523365SDimitry Andric UnwindDest = getBasicBlock(Record[Idx++]); 38257d523365SDimitry Andric if (!UnwindDest) 38267d523365SDimitry Andric return error("Invalid record"); 38277d523365SDimitry Andric } 38287d523365SDimitry Andric 38297d523365SDimitry Andric I = CleanupReturnInst::Create(CleanupPad, UnwindDest); 38307d523365SDimitry Andric InstructionList.push_back(I); 38317d523365SDimitry Andric break; 38327d523365SDimitry Andric } 38337d523365SDimitry Andric case bitc::FUNC_CODE_INST_CATCHRET: { // CATCHRET: [val,bb#] 38347d523365SDimitry Andric if (Record.size() != 2) 38357d523365SDimitry Andric return error("Invalid record"); 38367d523365SDimitry Andric unsigned Idx = 0; 38377d523365SDimitry Andric Value *CatchPad = 38387d523365SDimitry Andric getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context)); 38397d523365SDimitry Andric if (!CatchPad) 38407d523365SDimitry Andric return error("Invalid record"); 38417d523365SDimitry Andric BasicBlock *BB = getBasicBlock(Record[Idx++]); 38427d523365SDimitry Andric if (!BB) 38437d523365SDimitry Andric return error("Invalid record"); 38447d523365SDimitry Andric 38457d523365SDimitry Andric I = CatchReturnInst::Create(CatchPad, BB); 38467d523365SDimitry Andric InstructionList.push_back(I); 38477d523365SDimitry Andric break; 38487d523365SDimitry Andric } 38497d523365SDimitry Andric case bitc::FUNC_CODE_INST_CATCHSWITCH: { // CATCHSWITCH: [tok,num,(bb)*,bb?] 38507d523365SDimitry Andric // We must have, at minimum, the outer scope and the number of arguments. 38517d523365SDimitry Andric if (Record.size() < 2) 38527d523365SDimitry Andric return error("Invalid record"); 38537d523365SDimitry Andric 38547d523365SDimitry Andric unsigned Idx = 0; 38557d523365SDimitry Andric 38567d523365SDimitry Andric Value *ParentPad = 38577d523365SDimitry Andric getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context)); 38587d523365SDimitry Andric 38597d523365SDimitry Andric unsigned NumHandlers = Record[Idx++]; 38607d523365SDimitry Andric 38617d523365SDimitry Andric SmallVector<BasicBlock *, 2> Handlers; 38627d523365SDimitry Andric for (unsigned Op = 0; Op != NumHandlers; ++Op) { 38637d523365SDimitry Andric BasicBlock *BB = getBasicBlock(Record[Idx++]); 38647d523365SDimitry Andric if (!BB) 38657d523365SDimitry Andric return error("Invalid record"); 38667d523365SDimitry Andric Handlers.push_back(BB); 38677d523365SDimitry Andric } 38687d523365SDimitry Andric 38697d523365SDimitry Andric BasicBlock *UnwindDest = nullptr; 38707d523365SDimitry Andric if (Idx + 1 == Record.size()) { 38717d523365SDimitry Andric UnwindDest = getBasicBlock(Record[Idx++]); 38727d523365SDimitry Andric if (!UnwindDest) 38737d523365SDimitry Andric return error("Invalid record"); 38747d523365SDimitry Andric } 38757d523365SDimitry Andric 38767d523365SDimitry Andric if (Record.size() != Idx) 38777d523365SDimitry Andric return error("Invalid record"); 38787d523365SDimitry Andric 38797d523365SDimitry Andric auto *CatchSwitch = 38807d523365SDimitry Andric CatchSwitchInst::Create(ParentPad, UnwindDest, NumHandlers); 38817d523365SDimitry Andric for (BasicBlock *Handler : Handlers) 38827d523365SDimitry Andric CatchSwitch->addHandler(Handler); 38837d523365SDimitry Andric I = CatchSwitch; 38847d523365SDimitry Andric InstructionList.push_back(I); 38857d523365SDimitry Andric break; 38867d523365SDimitry Andric } 38877d523365SDimitry Andric case bitc::FUNC_CODE_INST_CATCHPAD: 38887d523365SDimitry Andric case bitc::FUNC_CODE_INST_CLEANUPPAD: { // [tok,num,(ty,val)*] 38897d523365SDimitry Andric // We must have, at minimum, the outer scope and the number of arguments. 38907d523365SDimitry Andric if (Record.size() < 2) 38917d523365SDimitry Andric return error("Invalid record"); 38927d523365SDimitry Andric 38937d523365SDimitry Andric unsigned Idx = 0; 38947d523365SDimitry Andric 38957d523365SDimitry Andric Value *ParentPad = 38967d523365SDimitry Andric getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context)); 38977d523365SDimitry Andric 38987d523365SDimitry Andric unsigned NumArgOperands = Record[Idx++]; 38997d523365SDimitry Andric 39007d523365SDimitry Andric SmallVector<Value *, 2> Args; 39017d523365SDimitry Andric for (unsigned Op = 0; Op != NumArgOperands; ++Op) { 39027d523365SDimitry Andric Value *Val; 39037d523365SDimitry Andric if (getValueTypePair(Record, Idx, NextValueNo, Val)) 39047d523365SDimitry Andric return error("Invalid record"); 39057d523365SDimitry Andric Args.push_back(Val); 39067d523365SDimitry Andric } 39077d523365SDimitry Andric 39087d523365SDimitry Andric if (Record.size() != Idx) 39097d523365SDimitry Andric return error("Invalid record"); 39107d523365SDimitry Andric 39117d523365SDimitry Andric if (BitCode == bitc::FUNC_CODE_INST_CLEANUPPAD) 39127d523365SDimitry Andric I = CleanupPadInst::Create(ParentPad, Args); 39137d523365SDimitry Andric else 39147d523365SDimitry Andric I = CatchPadInst::Create(ParentPad, Args); 39157d523365SDimitry Andric InstructionList.push_back(I); 39167d523365SDimitry Andric break; 39177d523365SDimitry Andric } 3918f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...] 39197ae0e2c9SDimitry Andric // Check magic 39207ae0e2c9SDimitry Andric if ((Record[0] >> 16) == SWITCH_INST_MAGIC) { 3921f785676fSDimitry Andric // "New" SwitchInst format with case ranges. The changes to write this 3922f785676fSDimitry Andric // format were reverted but we still recognize bitcode that uses it. 3923f785676fSDimitry Andric // Hopefully someday we will have support for case ranges and can use 3924f785676fSDimitry Andric // this format again. 39257ae0e2c9SDimitry Andric 39267ae0e2c9SDimitry Andric Type *OpTy = getTypeByID(Record[1]); 39277ae0e2c9SDimitry Andric unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth(); 39287ae0e2c9SDimitry Andric 39293861d79fSDimitry Andric Value *Cond = getValue(Record, 2, NextValueNo, OpTy); 39307ae0e2c9SDimitry Andric BasicBlock *Default = getBasicBlock(Record[3]); 393191bc56edSDimitry Andric if (!OpTy || !Cond || !Default) 39328f0fd8f6SDimitry Andric return error("Invalid record"); 39337ae0e2c9SDimitry Andric 39347ae0e2c9SDimitry Andric unsigned NumCases = Record[4]; 39357ae0e2c9SDimitry Andric 39367ae0e2c9SDimitry Andric SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases); 39377ae0e2c9SDimitry Andric InstructionList.push_back(SI); 39387ae0e2c9SDimitry Andric 39397ae0e2c9SDimitry Andric unsigned CurIdx = 5; 39407ae0e2c9SDimitry Andric for (unsigned i = 0; i != NumCases; ++i) { 3941f785676fSDimitry Andric SmallVector<ConstantInt*, 1> CaseVals; 39427ae0e2c9SDimitry Andric unsigned NumItems = Record[CurIdx++]; 39437ae0e2c9SDimitry Andric for (unsigned ci = 0; ci != NumItems; ++ci) { 39447ae0e2c9SDimitry Andric bool isSingleNumber = Record[CurIdx++]; 39457ae0e2c9SDimitry Andric 39467ae0e2c9SDimitry Andric APInt Low; 39477ae0e2c9SDimitry Andric unsigned ActiveWords = 1; 39487ae0e2c9SDimitry Andric if (ValueBitWidth > 64) 39497ae0e2c9SDimitry Andric ActiveWords = Record[CurIdx++]; 39508f0fd8f6SDimitry Andric Low = readWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords), 39517ae0e2c9SDimitry Andric ValueBitWidth); 39527ae0e2c9SDimitry Andric CurIdx += ActiveWords; 39537ae0e2c9SDimitry Andric 39547ae0e2c9SDimitry Andric if (!isSingleNumber) { 39557ae0e2c9SDimitry Andric ActiveWords = 1; 39567ae0e2c9SDimitry Andric if (ValueBitWidth > 64) 39577ae0e2c9SDimitry Andric ActiveWords = Record[CurIdx++]; 39588f0fd8f6SDimitry Andric APInt High = readWideAPInt( 39598f0fd8f6SDimitry Andric makeArrayRef(&Record[CurIdx], ActiveWords), ValueBitWidth); 39607ae0e2c9SDimitry Andric CurIdx += ActiveWords; 3961f785676fSDimitry Andric 3962f785676fSDimitry Andric // FIXME: It is not clear whether values in the range should be 3963f785676fSDimitry Andric // compared as signed or unsigned values. The partially 3964f785676fSDimitry Andric // implemented changes that used this format in the past used 3965f785676fSDimitry Andric // unsigned comparisons. 3966f785676fSDimitry Andric for ( ; Low.ule(High); ++Low) 3967f785676fSDimitry Andric CaseVals.push_back(ConstantInt::get(Context, Low)); 39687ae0e2c9SDimitry Andric } else 3969f785676fSDimitry Andric CaseVals.push_back(ConstantInt::get(Context, Low)); 39707ae0e2c9SDimitry Andric } 39717ae0e2c9SDimitry Andric BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]); 3972f785676fSDimitry Andric for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(), 3973f785676fSDimitry Andric cve = CaseVals.end(); cvi != cve; ++cvi) 3974f785676fSDimitry Andric SI->addCase(*cvi, DestBB); 39757ae0e2c9SDimitry Andric } 39767ae0e2c9SDimitry Andric I = SI; 39777ae0e2c9SDimitry Andric break; 39787ae0e2c9SDimitry Andric } 39797ae0e2c9SDimitry Andric 39807ae0e2c9SDimitry Andric // Old SwitchInst format without case ranges. 39817ae0e2c9SDimitry Andric 3982f22ef01cSRoman Divacky if (Record.size() < 3 || (Record.size() & 1) == 0) 39838f0fd8f6SDimitry Andric return error("Invalid record"); 39846122f3e6SDimitry Andric Type *OpTy = getTypeByID(Record[0]); 39853861d79fSDimitry Andric Value *Cond = getValue(Record, 1, NextValueNo, OpTy); 3986f22ef01cSRoman Divacky BasicBlock *Default = getBasicBlock(Record[2]); 398791bc56edSDimitry Andric if (!OpTy || !Cond || !Default) 39888f0fd8f6SDimitry Andric return error("Invalid record"); 3989f22ef01cSRoman Divacky unsigned NumCases = (Record.size()-3)/2; 3990f22ef01cSRoman Divacky SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases); 3991f22ef01cSRoman Divacky InstructionList.push_back(SI); 3992f22ef01cSRoman Divacky for (unsigned i = 0, e = NumCases; i != e; ++i) { 3993f22ef01cSRoman Divacky ConstantInt *CaseVal = 3994f22ef01cSRoman Divacky dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy)); 3995f22ef01cSRoman Divacky BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]); 399691bc56edSDimitry Andric if (!CaseVal || !DestBB) { 3997f22ef01cSRoman Divacky delete SI; 39988f0fd8f6SDimitry Andric return error("Invalid record"); 3999f22ef01cSRoman Divacky } 4000f22ef01cSRoman Divacky SI->addCase(CaseVal, DestBB); 4001f22ef01cSRoman Divacky } 4002f22ef01cSRoman Divacky I = SI; 4003f22ef01cSRoman Divacky break; 4004f22ef01cSRoman Divacky } 4005f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...] 4006f22ef01cSRoman Divacky if (Record.size() < 2) 40078f0fd8f6SDimitry Andric return error("Invalid record"); 40086122f3e6SDimitry Andric Type *OpTy = getTypeByID(Record[0]); 40093861d79fSDimitry Andric Value *Address = getValue(Record, 1, NextValueNo, OpTy); 401091bc56edSDimitry Andric if (!OpTy || !Address) 40118f0fd8f6SDimitry Andric return error("Invalid record"); 4012f22ef01cSRoman Divacky unsigned NumDests = Record.size()-2; 4013f22ef01cSRoman Divacky IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests); 4014f22ef01cSRoman Divacky InstructionList.push_back(IBI); 4015f22ef01cSRoman Divacky for (unsigned i = 0, e = NumDests; i != e; ++i) { 4016f22ef01cSRoman Divacky if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) { 4017f22ef01cSRoman Divacky IBI->addDestination(DestBB); 4018f22ef01cSRoman Divacky } else { 4019f22ef01cSRoman Divacky delete IBI; 40208f0fd8f6SDimitry Andric return error("Invalid record"); 4021f22ef01cSRoman Divacky } 4022f22ef01cSRoman Divacky } 4023f22ef01cSRoman Divacky I = IBI; 4024f22ef01cSRoman Divacky break; 4025f22ef01cSRoman Divacky } 4026f22ef01cSRoman Divacky 4027f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_INVOKE: { 4028f22ef01cSRoman Divacky // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...] 4029f785676fSDimitry Andric if (Record.size() < 4) 40308f0fd8f6SDimitry Andric return error("Invalid record"); 4031ff0cc061SDimitry Andric unsigned OpNum = 0; 40327a7e6055SDimitry Andric AttributeList PAL = getAttributes(Record[OpNum++]); 4033ff0cc061SDimitry Andric unsigned CCInfo = Record[OpNum++]; 4034ff0cc061SDimitry Andric BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]); 4035ff0cc061SDimitry Andric BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]); 4036f22ef01cSRoman Divacky 4037ff0cc061SDimitry Andric FunctionType *FTy = nullptr; 4038ff0cc061SDimitry Andric if (CCInfo >> 13 & 1 && 4039ff0cc061SDimitry Andric !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++])))) 40408f0fd8f6SDimitry Andric return error("Explicit invoke type is not a function type"); 4041ff0cc061SDimitry Andric 4042f22ef01cSRoman Divacky Value *Callee; 4043f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, Callee)) 40448f0fd8f6SDimitry Andric return error("Invalid record"); 4045f22ef01cSRoman Divacky 40466122f3e6SDimitry Andric PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType()); 4047ff0cc061SDimitry Andric if (!CalleeTy) 40488f0fd8f6SDimitry Andric return error("Callee is not a pointer"); 4049ff0cc061SDimitry Andric if (!FTy) { 4050ff0cc061SDimitry Andric FTy = dyn_cast<FunctionType>(CalleeTy->getElementType()); 4051ff0cc061SDimitry Andric if (!FTy) 40528f0fd8f6SDimitry Andric return error("Callee is not of pointer to function type"); 4053ff0cc061SDimitry Andric } else if (CalleeTy->getElementType() != FTy) 40548f0fd8f6SDimitry Andric return error("Explicit invoke type does not match pointee type of " 4055ff0cc061SDimitry Andric "callee operand"); 4056ff0cc061SDimitry Andric if (Record.size() < FTy->getNumParams() + OpNum) 40578f0fd8f6SDimitry Andric return error("Insufficient operands to call"); 4058f22ef01cSRoman Divacky 4059f22ef01cSRoman Divacky SmallVector<Value*, 16> Ops; 4060f22ef01cSRoman Divacky for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) { 40613861d79fSDimitry Andric Ops.push_back(getValue(Record, OpNum, NextValueNo, 40623861d79fSDimitry Andric FTy->getParamType(i))); 406391bc56edSDimitry Andric if (!Ops.back()) 40648f0fd8f6SDimitry Andric return error("Invalid record"); 4065f22ef01cSRoman Divacky } 4066f22ef01cSRoman Divacky 4067f22ef01cSRoman Divacky if (!FTy->isVarArg()) { 4068f22ef01cSRoman Divacky if (Record.size() != OpNum) 40698f0fd8f6SDimitry Andric return error("Invalid record"); 4070f22ef01cSRoman Divacky } else { 4071f22ef01cSRoman Divacky // Read type/value pairs for varargs params. 4072f22ef01cSRoman Divacky while (OpNum != Record.size()) { 4073f22ef01cSRoman Divacky Value *Op; 4074f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 40758f0fd8f6SDimitry Andric return error("Invalid record"); 4076f22ef01cSRoman Divacky Ops.push_back(Op); 4077f22ef01cSRoman Divacky } 4078f22ef01cSRoman Divacky } 4079f22ef01cSRoman Divacky 40807d523365SDimitry Andric I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops, OperandBundles); 40817d523365SDimitry Andric OperandBundles.clear(); 4082f22ef01cSRoman Divacky InstructionList.push_back(I); 40837d523365SDimitry Andric cast<InvokeInst>(I)->setCallingConv( 40847d523365SDimitry Andric static_cast<CallingConv::ID>(CallingConv::MaxID & CCInfo)); 4085f22ef01cSRoman Divacky cast<InvokeInst>(I)->setAttributes(PAL); 4086f22ef01cSRoman Divacky break; 4087f22ef01cSRoman Divacky } 40886122f3e6SDimitry Andric case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval] 40896122f3e6SDimitry Andric unsigned Idx = 0; 409091bc56edSDimitry Andric Value *Val = nullptr; 40916122f3e6SDimitry Andric if (getValueTypePair(Record, Idx, NextValueNo, Val)) 40928f0fd8f6SDimitry Andric return error("Invalid record"); 40936122f3e6SDimitry Andric I = ResumeInst::Create(Val); 40946122f3e6SDimitry Andric InstructionList.push_back(I); 40956122f3e6SDimitry Andric break; 40966122f3e6SDimitry Andric } 4097f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE 4098f22ef01cSRoman Divacky I = new UnreachableInst(Context); 4099f22ef01cSRoman Divacky InstructionList.push_back(I); 4100f22ef01cSRoman Divacky break; 4101f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...] 4102f22ef01cSRoman Divacky if (Record.size() < 1 || ((Record.size()-1)&1)) 41038f0fd8f6SDimitry Andric return error("Invalid record"); 41046122f3e6SDimitry Andric Type *Ty = getTypeByID(Record[0]); 4105f785676fSDimitry Andric if (!Ty) 41068f0fd8f6SDimitry Andric return error("Invalid record"); 4107f22ef01cSRoman Divacky 41083b0f4066SDimitry Andric PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2); 4109f22ef01cSRoman Divacky InstructionList.push_back(PN); 4110f22ef01cSRoman Divacky 4111f22ef01cSRoman Divacky for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) { 41123861d79fSDimitry Andric Value *V; 41133861d79fSDimitry Andric // With the new function encoding, it is possible that operands have 41143861d79fSDimitry Andric // negative IDs (for forward references). Use a signed VBR 41153861d79fSDimitry Andric // representation to keep the encoding small. 41163861d79fSDimitry Andric if (UseRelativeIDs) 41173861d79fSDimitry Andric V = getValueSigned(Record, 1+i, NextValueNo, Ty); 41183861d79fSDimitry Andric else 41193861d79fSDimitry Andric V = getValue(Record, 1+i, NextValueNo, Ty); 4120f22ef01cSRoman Divacky BasicBlock *BB = getBasicBlock(Record[2+i]); 4121f785676fSDimitry Andric if (!V || !BB) 41228f0fd8f6SDimitry Andric return error("Invalid record"); 4123f22ef01cSRoman Divacky PN->addIncoming(V, BB); 4124f22ef01cSRoman Divacky } 4125f22ef01cSRoman Divacky I = PN; 4126f22ef01cSRoman Divacky break; 4127f22ef01cSRoman Divacky } 4128f22ef01cSRoman Divacky 41298f0fd8f6SDimitry Andric case bitc::FUNC_CODE_INST_LANDINGPAD: 41308f0fd8f6SDimitry Andric case bitc::FUNC_CODE_INST_LANDINGPAD_OLD: { 41316122f3e6SDimitry Andric // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?] 41326122f3e6SDimitry Andric unsigned Idx = 0; 41338f0fd8f6SDimitry Andric if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD) { 41348f0fd8f6SDimitry Andric if (Record.size() < 3) 41358f0fd8f6SDimitry Andric return error("Invalid record"); 41368f0fd8f6SDimitry Andric } else { 41378f0fd8f6SDimitry Andric assert(BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD); 41386122f3e6SDimitry Andric if (Record.size() < 4) 41398f0fd8f6SDimitry Andric return error("Invalid record"); 41408f0fd8f6SDimitry Andric } 41416122f3e6SDimitry Andric Type *Ty = getTypeByID(Record[Idx++]); 4142f785676fSDimitry Andric if (!Ty) 41438f0fd8f6SDimitry Andric return error("Invalid record"); 41448f0fd8f6SDimitry Andric if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD) { 414591bc56edSDimitry Andric Value *PersFn = nullptr; 41466122f3e6SDimitry Andric if (getValueTypePair(Record, Idx, NextValueNo, PersFn)) 41478f0fd8f6SDimitry Andric return error("Invalid record"); 41488f0fd8f6SDimitry Andric 41498f0fd8f6SDimitry Andric if (!F->hasPersonalityFn()) 41508f0fd8f6SDimitry Andric F->setPersonalityFn(cast<Constant>(PersFn)); 41518f0fd8f6SDimitry Andric else if (F->getPersonalityFn() != cast<Constant>(PersFn)) 41528f0fd8f6SDimitry Andric return error("Personality function mismatch"); 41538f0fd8f6SDimitry Andric } 41546122f3e6SDimitry Andric 41556122f3e6SDimitry Andric bool IsCleanup = !!Record[Idx++]; 41566122f3e6SDimitry Andric unsigned NumClauses = Record[Idx++]; 41578f0fd8f6SDimitry Andric LandingPadInst *LP = LandingPadInst::Create(Ty, NumClauses); 41586122f3e6SDimitry Andric LP->setCleanup(IsCleanup); 41596122f3e6SDimitry Andric for (unsigned J = 0; J != NumClauses; ++J) { 41606122f3e6SDimitry Andric LandingPadInst::ClauseType CT = 41616122f3e6SDimitry Andric LandingPadInst::ClauseType(Record[Idx++]); (void)CT; 41626122f3e6SDimitry Andric Value *Val; 41636122f3e6SDimitry Andric 41646122f3e6SDimitry Andric if (getValueTypePair(Record, Idx, NextValueNo, Val)) { 41656122f3e6SDimitry Andric delete LP; 41668f0fd8f6SDimitry Andric return error("Invalid record"); 41676122f3e6SDimitry Andric } 41686122f3e6SDimitry Andric 41696122f3e6SDimitry Andric assert((CT != LandingPadInst::Catch || 41706122f3e6SDimitry Andric !isa<ArrayType>(Val->getType())) && 41716122f3e6SDimitry Andric "Catch clause has a invalid type!"); 41726122f3e6SDimitry Andric assert((CT != LandingPadInst::Filter || 41736122f3e6SDimitry Andric isa<ArrayType>(Val->getType())) && 41746122f3e6SDimitry Andric "Filter clause has invalid type!"); 417591bc56edSDimitry Andric LP->addClause(cast<Constant>(Val)); 41766122f3e6SDimitry Andric } 41776122f3e6SDimitry Andric 41786122f3e6SDimitry Andric I = LP; 41796122f3e6SDimitry Andric InstructionList.push_back(I); 41806122f3e6SDimitry Andric break; 41816122f3e6SDimitry Andric } 41826122f3e6SDimitry Andric 418317a519f9SDimitry Andric case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align] 418417a519f9SDimitry Andric if (Record.size() != 4) 41858f0fd8f6SDimitry Andric return error("Invalid record"); 4186ff0cc061SDimitry Andric uint64_t AlignRecord = Record[3]; 4187ff0cc061SDimitry Andric const uint64_t InAllocaMask = uint64_t(1) << 5; 4188ff0cc061SDimitry Andric const uint64_t ExplicitTypeMask = uint64_t(1) << 6; 41893ca95b02SDimitry Andric const uint64_t SwiftErrorMask = uint64_t(1) << 7; 41903ca95b02SDimitry Andric const uint64_t FlagMask = InAllocaMask | ExplicitTypeMask | 41913ca95b02SDimitry Andric SwiftErrorMask; 4192ff0cc061SDimitry Andric bool InAlloca = AlignRecord & InAllocaMask; 41933ca95b02SDimitry Andric bool SwiftError = AlignRecord & SwiftErrorMask; 4194ff0cc061SDimitry Andric Type *Ty = getTypeByID(Record[0]); 4195ff0cc061SDimitry Andric if ((AlignRecord & ExplicitTypeMask) == 0) { 4196ff0cc061SDimitry Andric auto *PTy = dyn_cast_or_null<PointerType>(Ty); 4197ff0cc061SDimitry Andric if (!PTy) 41988f0fd8f6SDimitry Andric return error("Old-style alloca with a non-pointer type"); 4199ff0cc061SDimitry Andric Ty = PTy->getElementType(); 4200ff0cc061SDimitry Andric } 42016122f3e6SDimitry Andric Type *OpTy = getTypeByID(Record[1]); 420217a519f9SDimitry Andric Value *Size = getFnValueByID(Record[2], OpTy); 4203ff0cc061SDimitry Andric unsigned Align; 4204d88c1a5aSDimitry Andric if (Error Err = parseAlignmentValue(AlignRecord & ~FlagMask, Align)) { 4205d88c1a5aSDimitry Andric return Err; 4206ff0cc061SDimitry Andric } 4207f785676fSDimitry Andric if (!Ty || !Size) 42088f0fd8f6SDimitry Andric return error("Invalid record"); 42097a7e6055SDimitry Andric 42107a7e6055SDimitry Andric // FIXME: Make this an optional field. 42117a7e6055SDimitry Andric const DataLayout &DL = TheModule->getDataLayout(); 42127a7e6055SDimitry Andric unsigned AS = DL.getAllocaAddrSpace(); 42137a7e6055SDimitry Andric 42147a7e6055SDimitry Andric AllocaInst *AI = new AllocaInst(Ty, AS, Size, Align); 421591bc56edSDimitry Andric AI->setUsedWithInAlloca(InAlloca); 42163ca95b02SDimitry Andric AI->setSwiftError(SwiftError); 421791bc56edSDimitry Andric I = AI; 4218f22ef01cSRoman Divacky InstructionList.push_back(I); 4219f22ef01cSRoman Divacky break; 4220f22ef01cSRoman Divacky } 4221f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol] 4222f22ef01cSRoman Divacky unsigned OpNum = 0; 4223f22ef01cSRoman Divacky Value *Op; 4224f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, Op) || 4225ff0cc061SDimitry Andric (OpNum + 2 != Record.size() && OpNum + 3 != Record.size())) 42268f0fd8f6SDimitry Andric return error("Invalid record"); 4227f22ef01cSRoman Divacky 4228ff0cc061SDimitry Andric Type *Ty = nullptr; 4229ff0cc061SDimitry Andric if (OpNum + 3 == Record.size()) 4230ff0cc061SDimitry Andric Ty = getTypeByID(Record[OpNum++]); 4231d88c1a5aSDimitry Andric if (Error Err = typeCheckLoadStoreInst(Ty, Op->getType())) 4232d88c1a5aSDimitry Andric return Err; 4233ff0cc061SDimitry Andric if (!Ty) 4234ff0cc061SDimitry Andric Ty = cast<PointerType>(Op->getType())->getElementType(); 4235ff0cc061SDimitry Andric 4236ff0cc061SDimitry Andric unsigned Align; 4237d88c1a5aSDimitry Andric if (Error Err = parseAlignmentValue(Record[OpNum], Align)) 4238d88c1a5aSDimitry Andric return Err; 4239ff0cc061SDimitry Andric I = new LoadInst(Ty, Op, "", Record[OpNum + 1], Align); 4240ff0cc061SDimitry Andric 4241f22ef01cSRoman Divacky InstructionList.push_back(I); 4242f22ef01cSRoman Divacky break; 4243f22ef01cSRoman Divacky } 42446122f3e6SDimitry Andric case bitc::FUNC_CODE_INST_LOADATOMIC: { 4245c4394386SDimitry Andric // LOADATOMIC: [opty, op, align, vol, ordering, ssid] 42466122f3e6SDimitry Andric unsigned OpNum = 0; 42476122f3e6SDimitry Andric Value *Op; 42486122f3e6SDimitry Andric if (getValueTypePair(Record, OpNum, NextValueNo, Op) || 4249ff0cc061SDimitry Andric (OpNum + 4 != Record.size() && OpNum + 5 != Record.size())) 42508f0fd8f6SDimitry Andric return error("Invalid record"); 42516122f3e6SDimitry Andric 4252ff0cc061SDimitry Andric Type *Ty = nullptr; 4253ff0cc061SDimitry Andric if (OpNum + 5 == Record.size()) 4254ff0cc061SDimitry Andric Ty = getTypeByID(Record[OpNum++]); 4255d88c1a5aSDimitry Andric if (Error Err = typeCheckLoadStoreInst(Ty, Op->getType())) 4256d88c1a5aSDimitry Andric return Err; 4257ff0cc061SDimitry Andric if (!Ty) 4258ff0cc061SDimitry Andric Ty = cast<PointerType>(Op->getType())->getElementType(); 4259ff0cc061SDimitry Andric 42608f0fd8f6SDimitry Andric AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]); 42613ca95b02SDimitry Andric if (Ordering == AtomicOrdering::NotAtomic || 42623ca95b02SDimitry Andric Ordering == AtomicOrdering::Release || 42633ca95b02SDimitry Andric Ordering == AtomicOrdering::AcquireRelease) 42648f0fd8f6SDimitry Andric return error("Invalid record"); 42653ca95b02SDimitry Andric if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0) 42668f0fd8f6SDimitry Andric return error("Invalid record"); 4267c4394386SDimitry Andric SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]); 42686122f3e6SDimitry Andric 4269ff0cc061SDimitry Andric unsigned Align; 4270d88c1a5aSDimitry Andric if (Error Err = parseAlignmentValue(Record[OpNum], Align)) 4271d88c1a5aSDimitry Andric return Err; 4272c4394386SDimitry Andric I = new LoadInst(Op, "", Record[OpNum+1], Align, Ordering, SSID); 4273ff0cc061SDimitry Andric 42746122f3e6SDimitry Andric InstructionList.push_back(I); 42756122f3e6SDimitry Andric break; 42766122f3e6SDimitry Andric } 4277ff0cc061SDimitry Andric case bitc::FUNC_CODE_INST_STORE: 4278ff0cc061SDimitry Andric case bitc::FUNC_CODE_INST_STORE_OLD: { // STORE2:[ptrty, ptr, val, align, vol] 4279f22ef01cSRoman Divacky unsigned OpNum = 0; 4280f22ef01cSRoman Divacky Value *Val, *Ptr; 4281f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) || 4282ff0cc061SDimitry Andric (BitCode == bitc::FUNC_CODE_INST_STORE 4283ff0cc061SDimitry Andric ? getValueTypePair(Record, OpNum, NextValueNo, Val) 4284ff0cc061SDimitry Andric : popValue(Record, OpNum, NextValueNo, 4285ff0cc061SDimitry Andric cast<PointerType>(Ptr->getType())->getElementType(), 4286ff0cc061SDimitry Andric Val)) || 4287f22ef01cSRoman Divacky OpNum + 2 != Record.size()) 42888f0fd8f6SDimitry Andric return error("Invalid record"); 4289f22ef01cSRoman Divacky 4290d88c1a5aSDimitry Andric if (Error Err = typeCheckLoadStoreInst(Val->getType(), Ptr->getType())) 4291d88c1a5aSDimitry Andric return Err; 4292ff0cc061SDimitry Andric unsigned Align; 4293d88c1a5aSDimitry Andric if (Error Err = parseAlignmentValue(Record[OpNum], Align)) 4294d88c1a5aSDimitry Andric return Err; 4295ff0cc061SDimitry Andric I = new StoreInst(Val, Ptr, Record[OpNum+1], Align); 4296f22ef01cSRoman Divacky InstructionList.push_back(I); 4297f22ef01cSRoman Divacky break; 4298f22ef01cSRoman Divacky } 4299ff0cc061SDimitry Andric case bitc::FUNC_CODE_INST_STOREATOMIC: 4300ff0cc061SDimitry Andric case bitc::FUNC_CODE_INST_STOREATOMIC_OLD: { 4301c4394386SDimitry Andric // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, ssid] 43026122f3e6SDimitry Andric unsigned OpNum = 0; 43036122f3e6SDimitry Andric Value *Val, *Ptr; 43046122f3e6SDimitry Andric if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) || 43053ca95b02SDimitry Andric !isa<PointerType>(Ptr->getType()) || 4306ff0cc061SDimitry Andric (BitCode == bitc::FUNC_CODE_INST_STOREATOMIC 4307ff0cc061SDimitry Andric ? getValueTypePair(Record, OpNum, NextValueNo, Val) 4308ff0cc061SDimitry Andric : popValue(Record, OpNum, NextValueNo, 4309ff0cc061SDimitry Andric cast<PointerType>(Ptr->getType())->getElementType(), 4310ff0cc061SDimitry Andric Val)) || 43116122f3e6SDimitry Andric OpNum + 4 != Record.size()) 43128f0fd8f6SDimitry Andric return error("Invalid record"); 43136122f3e6SDimitry Andric 4314d88c1a5aSDimitry Andric if (Error Err = typeCheckLoadStoreInst(Val->getType(), Ptr->getType())) 4315d88c1a5aSDimitry Andric return Err; 43168f0fd8f6SDimitry Andric AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]); 43173ca95b02SDimitry Andric if (Ordering == AtomicOrdering::NotAtomic || 43183ca95b02SDimitry Andric Ordering == AtomicOrdering::Acquire || 43193ca95b02SDimitry Andric Ordering == AtomicOrdering::AcquireRelease) 43208f0fd8f6SDimitry Andric return error("Invalid record"); 4321c4394386SDimitry Andric SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]); 43223ca95b02SDimitry Andric if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0) 43238f0fd8f6SDimitry Andric return error("Invalid record"); 43246122f3e6SDimitry Andric 4325ff0cc061SDimitry Andric unsigned Align; 4326d88c1a5aSDimitry Andric if (Error Err = parseAlignmentValue(Record[OpNum], Align)) 4327d88c1a5aSDimitry Andric return Err; 4328c4394386SDimitry Andric I = new StoreInst(Val, Ptr, Record[OpNum+1], Align, Ordering, SSID); 43296122f3e6SDimitry Andric InstructionList.push_back(I); 43306122f3e6SDimitry Andric break; 43316122f3e6SDimitry Andric } 4332ff0cc061SDimitry Andric case bitc::FUNC_CODE_INST_CMPXCHG_OLD: 43336122f3e6SDimitry Andric case bitc::FUNC_CODE_INST_CMPXCHG: { 4334c4394386SDimitry Andric // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, ssid, 433591bc56edSDimitry Andric // failureordering?, isweak?] 43366122f3e6SDimitry Andric unsigned OpNum = 0; 43376122f3e6SDimitry Andric Value *Ptr, *Cmp, *New; 43386122f3e6SDimitry Andric if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) || 4339ff0cc061SDimitry Andric (BitCode == bitc::FUNC_CODE_INST_CMPXCHG 4340ff0cc061SDimitry Andric ? getValueTypePair(Record, OpNum, NextValueNo, Cmp) 4341ff0cc061SDimitry Andric : popValue(Record, OpNum, NextValueNo, 4342ff0cc061SDimitry Andric cast<PointerType>(Ptr->getType())->getElementType(), 4343ff0cc061SDimitry Andric Cmp)) || 4344ff0cc061SDimitry Andric popValue(Record, OpNum, NextValueNo, Cmp->getType(), New) || 4345ff0cc061SDimitry Andric Record.size() < OpNum + 3 || Record.size() > OpNum + 5) 43468f0fd8f6SDimitry Andric return error("Invalid record"); 43478f0fd8f6SDimitry Andric AtomicOrdering SuccessOrdering = getDecodedOrdering(Record[OpNum + 1]); 43483ca95b02SDimitry Andric if (SuccessOrdering == AtomicOrdering::NotAtomic || 43493ca95b02SDimitry Andric SuccessOrdering == AtomicOrdering::Unordered) 43508f0fd8f6SDimitry Andric return error("Invalid record"); 4351c4394386SDimitry Andric SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 2]); 435291bc56edSDimitry Andric 4353d88c1a5aSDimitry Andric if (Error Err = typeCheckLoadStoreInst(Cmp->getType(), Ptr->getType())) 4354d88c1a5aSDimitry Andric return Err; 435591bc56edSDimitry Andric AtomicOrdering FailureOrdering; 435691bc56edSDimitry Andric if (Record.size() < 7) 435791bc56edSDimitry Andric FailureOrdering = 435891bc56edSDimitry Andric AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering); 435991bc56edSDimitry Andric else 43608f0fd8f6SDimitry Andric FailureOrdering = getDecodedOrdering(Record[OpNum + 3]); 436191bc56edSDimitry Andric 436291bc56edSDimitry Andric I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering, 4363c4394386SDimitry Andric SSID); 43646122f3e6SDimitry Andric cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]); 436591bc56edSDimitry Andric 436691bc56edSDimitry Andric if (Record.size() < 8) { 436791bc56edSDimitry Andric // Before weak cmpxchgs existed, the instruction simply returned the 436891bc56edSDimitry Andric // value loaded from memory, so bitcode files from that era will be 436991bc56edSDimitry Andric // expecting the first component of a modern cmpxchg. 437091bc56edSDimitry Andric CurBB->getInstList().push_back(I); 437191bc56edSDimitry Andric I = ExtractValueInst::Create(I, 0); 437291bc56edSDimitry Andric } else { 437391bc56edSDimitry Andric cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]); 437491bc56edSDimitry Andric } 437591bc56edSDimitry Andric 43766122f3e6SDimitry Andric InstructionList.push_back(I); 43776122f3e6SDimitry Andric break; 43786122f3e6SDimitry Andric } 43796122f3e6SDimitry Andric case bitc::FUNC_CODE_INST_ATOMICRMW: { 4380c4394386SDimitry Andric // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, ssid] 43816122f3e6SDimitry Andric unsigned OpNum = 0; 43826122f3e6SDimitry Andric Value *Ptr, *Val; 43836122f3e6SDimitry Andric if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) || 43843ca95b02SDimitry Andric !isa<PointerType>(Ptr->getType()) || 43853861d79fSDimitry Andric popValue(Record, OpNum, NextValueNo, 43866122f3e6SDimitry Andric cast<PointerType>(Ptr->getType())->getElementType(), Val) || 43876122f3e6SDimitry Andric OpNum+4 != Record.size()) 43888f0fd8f6SDimitry Andric return error("Invalid record"); 43898f0fd8f6SDimitry Andric AtomicRMWInst::BinOp Operation = getDecodedRMWOperation(Record[OpNum]); 43906122f3e6SDimitry Andric if (Operation < AtomicRMWInst::FIRST_BINOP || 43916122f3e6SDimitry Andric Operation > AtomicRMWInst::LAST_BINOP) 43928f0fd8f6SDimitry Andric return error("Invalid record"); 43938f0fd8f6SDimitry Andric AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]); 43943ca95b02SDimitry Andric if (Ordering == AtomicOrdering::NotAtomic || 43953ca95b02SDimitry Andric Ordering == AtomicOrdering::Unordered) 43968f0fd8f6SDimitry Andric return error("Invalid record"); 4397c4394386SDimitry Andric SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]); 4398c4394386SDimitry Andric I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SSID); 43996122f3e6SDimitry Andric cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]); 44006122f3e6SDimitry Andric InstructionList.push_back(I); 44016122f3e6SDimitry Andric break; 44026122f3e6SDimitry Andric } 4403c4394386SDimitry Andric case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, ssid] 44046122f3e6SDimitry Andric if (2 != Record.size()) 44058f0fd8f6SDimitry Andric return error("Invalid record"); 44068f0fd8f6SDimitry Andric AtomicOrdering Ordering = getDecodedOrdering(Record[0]); 44073ca95b02SDimitry Andric if (Ordering == AtomicOrdering::NotAtomic || 44083ca95b02SDimitry Andric Ordering == AtomicOrdering::Unordered || 44093ca95b02SDimitry Andric Ordering == AtomicOrdering::Monotonic) 44108f0fd8f6SDimitry Andric return error("Invalid record"); 4411c4394386SDimitry Andric SyncScope::ID SSID = getDecodedSyncScopeID(Record[1]); 4412c4394386SDimitry Andric I = new FenceInst(Context, Ordering, SSID); 44136122f3e6SDimitry Andric InstructionList.push_back(I); 44146122f3e6SDimitry Andric break; 44156122f3e6SDimitry Andric } 441617a519f9SDimitry Andric case bitc::FUNC_CODE_INST_CALL: { 44177d523365SDimitry Andric // CALL: [paramattrs, cc, fmf, fnty, fnid, arg0, arg1...] 4418f22ef01cSRoman Divacky if (Record.size() < 3) 44198f0fd8f6SDimitry Andric return error("Invalid record"); 4420f22ef01cSRoman Divacky 4421ff0cc061SDimitry Andric unsigned OpNum = 0; 44227a7e6055SDimitry Andric AttributeList PAL = getAttributes(Record[OpNum++]); 4423ff0cc061SDimitry Andric unsigned CCInfo = Record[OpNum++]; 4424f22ef01cSRoman Divacky 44257d523365SDimitry Andric FastMathFlags FMF; 44267d523365SDimitry Andric if ((CCInfo >> bitc::CALL_FMF) & 1) { 44277d523365SDimitry Andric FMF = getDecodedFastMathFlags(Record[OpNum++]); 44287d523365SDimitry Andric if (!FMF.any()) 44297d523365SDimitry Andric return error("Fast math flags indicator set for call with no FMF"); 44307d523365SDimitry Andric } 44317d523365SDimitry Andric 4432ff0cc061SDimitry Andric FunctionType *FTy = nullptr; 44337d523365SDimitry Andric if (CCInfo >> bitc::CALL_EXPLICIT_TYPE & 1 && 4434ff0cc061SDimitry Andric !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++])))) 44358f0fd8f6SDimitry Andric return error("Explicit call type is not a function type"); 4436ff0cc061SDimitry Andric 4437f22ef01cSRoman Divacky Value *Callee; 4438f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, Callee)) 44398f0fd8f6SDimitry Andric return error("Invalid record"); 4440f22ef01cSRoman Divacky 44416122f3e6SDimitry Andric PointerType *OpTy = dyn_cast<PointerType>(Callee->getType()); 4442ff0cc061SDimitry Andric if (!OpTy) 44438f0fd8f6SDimitry Andric return error("Callee is not a pointer type"); 4444ff0cc061SDimitry Andric if (!FTy) { 4445ff0cc061SDimitry Andric FTy = dyn_cast<FunctionType>(OpTy->getElementType()); 4446ff0cc061SDimitry Andric if (!FTy) 44478f0fd8f6SDimitry Andric return error("Callee is not of pointer to function type"); 4448ff0cc061SDimitry Andric } else if (OpTy->getElementType() != FTy) 44498f0fd8f6SDimitry Andric return error("Explicit call type does not match pointee type of " 4450ff0cc061SDimitry Andric "callee operand"); 4451ff0cc061SDimitry Andric if (Record.size() < FTy->getNumParams() + OpNum) 44528f0fd8f6SDimitry Andric return error("Insufficient operands to call"); 4453f22ef01cSRoman Divacky 4454f22ef01cSRoman Divacky SmallVector<Value*, 16> Args; 4455f22ef01cSRoman Divacky // Read the fixed params. 4456f22ef01cSRoman Divacky for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) { 445717a519f9SDimitry Andric if (FTy->getParamType(i)->isLabelTy()) 4458f22ef01cSRoman Divacky Args.push_back(getBasicBlock(Record[OpNum])); 4459f22ef01cSRoman Divacky else 44603861d79fSDimitry Andric Args.push_back(getValue(Record, OpNum, NextValueNo, 44613861d79fSDimitry Andric FTy->getParamType(i))); 446291bc56edSDimitry Andric if (!Args.back()) 44638f0fd8f6SDimitry Andric return error("Invalid record"); 4464f22ef01cSRoman Divacky } 4465f22ef01cSRoman Divacky 4466f22ef01cSRoman Divacky // Read type/value pairs for varargs params. 4467f22ef01cSRoman Divacky if (!FTy->isVarArg()) { 4468f22ef01cSRoman Divacky if (OpNum != Record.size()) 44698f0fd8f6SDimitry Andric return error("Invalid record"); 4470f22ef01cSRoman Divacky } else { 4471f22ef01cSRoman Divacky while (OpNum != Record.size()) { 4472f22ef01cSRoman Divacky Value *Op; 4473f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 44748f0fd8f6SDimitry Andric return error("Invalid record"); 4475f22ef01cSRoman Divacky Args.push_back(Op); 4476f22ef01cSRoman Divacky } 4477f22ef01cSRoman Divacky } 4478f22ef01cSRoman Divacky 44797d523365SDimitry Andric I = CallInst::Create(FTy, Callee, Args, OperandBundles); 44807d523365SDimitry Andric OperandBundles.clear(); 4481f22ef01cSRoman Divacky InstructionList.push_back(I); 4482f22ef01cSRoman Divacky cast<CallInst>(I)->setCallingConv( 44837d523365SDimitry Andric static_cast<CallingConv::ID>((0x7ff & CCInfo) >> bitc::CALL_CCONV)); 448491bc56edSDimitry Andric CallInst::TailCallKind TCK = CallInst::TCK_None; 44857d523365SDimitry Andric if (CCInfo & 1 << bitc::CALL_TAIL) 448691bc56edSDimitry Andric TCK = CallInst::TCK_Tail; 44877d523365SDimitry Andric if (CCInfo & (1 << bitc::CALL_MUSTTAIL)) 448891bc56edSDimitry Andric TCK = CallInst::TCK_MustTail; 44897d523365SDimitry Andric if (CCInfo & (1 << bitc::CALL_NOTAIL)) 44907d523365SDimitry Andric TCK = CallInst::TCK_NoTail; 449191bc56edSDimitry Andric cast<CallInst>(I)->setTailCallKind(TCK); 4492f22ef01cSRoman Divacky cast<CallInst>(I)->setAttributes(PAL); 44937d523365SDimitry Andric if (FMF.any()) { 44947d523365SDimitry Andric if (!isa<FPMathOperator>(I)) 44957d523365SDimitry Andric return error("Fast-math-flags specified for call without " 44967d523365SDimitry Andric "floating-point scalar or vector return type"); 44977d523365SDimitry Andric I->setFastMathFlags(FMF); 44987d523365SDimitry Andric } 4499f22ef01cSRoman Divacky break; 4500f22ef01cSRoman Divacky } 4501f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty] 4502f22ef01cSRoman Divacky if (Record.size() < 3) 45038f0fd8f6SDimitry Andric return error("Invalid record"); 45046122f3e6SDimitry Andric Type *OpTy = getTypeByID(Record[0]); 45053861d79fSDimitry Andric Value *Op = getValue(Record, 1, NextValueNo, OpTy); 45066122f3e6SDimitry Andric Type *ResTy = getTypeByID(Record[2]); 4507f22ef01cSRoman Divacky if (!OpTy || !Op || !ResTy) 45088f0fd8f6SDimitry Andric return error("Invalid record"); 4509f22ef01cSRoman Divacky I = new VAArgInst(Op, ResTy); 4510f22ef01cSRoman Divacky InstructionList.push_back(I); 4511f22ef01cSRoman Divacky break; 4512f22ef01cSRoman Divacky } 45137d523365SDimitry Andric 45147d523365SDimitry Andric case bitc::FUNC_CODE_OPERAND_BUNDLE: { 45157d523365SDimitry Andric // A call or an invoke can be optionally prefixed with some variable 45167d523365SDimitry Andric // number of operand bundle blocks. These blocks are read into 45177d523365SDimitry Andric // OperandBundles and consumed at the next call or invoke instruction. 45187d523365SDimitry Andric 45197d523365SDimitry Andric if (Record.size() < 1 || Record[0] >= BundleTags.size()) 45207d523365SDimitry Andric return error("Invalid record"); 45217d523365SDimitry Andric 45227d523365SDimitry Andric std::vector<Value *> Inputs; 45237d523365SDimitry Andric 45247d523365SDimitry Andric unsigned OpNum = 1; 45257d523365SDimitry Andric while (OpNum != Record.size()) { 45267d523365SDimitry Andric Value *Op; 45277d523365SDimitry Andric if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 45287d523365SDimitry Andric return error("Invalid record"); 45297d523365SDimitry Andric Inputs.push_back(Op); 45307d523365SDimitry Andric } 45317d523365SDimitry Andric 45327d523365SDimitry Andric OperandBundles.emplace_back(BundleTags[Record[0]], std::move(Inputs)); 45337d523365SDimitry Andric continue; 45347d523365SDimitry Andric } 4535f22ef01cSRoman Divacky } 4536f22ef01cSRoman Divacky 4537f22ef01cSRoman Divacky // Add instruction to end of current BB. If there is no current BB, reject 4538f22ef01cSRoman Divacky // this file. 453991bc56edSDimitry Andric if (!CurBB) { 4540d8866befSDimitry Andric I->deleteValue(); 45418f0fd8f6SDimitry Andric return error("Invalid instruction with no BB"); 4542f22ef01cSRoman Divacky } 45437d523365SDimitry Andric if (!OperandBundles.empty()) { 4544d8866befSDimitry Andric I->deleteValue(); 45457d523365SDimitry Andric return error("Operand bundles found with no consumer"); 45467d523365SDimitry Andric } 4547f22ef01cSRoman Divacky CurBB->getInstList().push_back(I); 4548f22ef01cSRoman Divacky 4549f22ef01cSRoman Divacky // If this was a terminator instruction, move to the next block. 4550f22ef01cSRoman Divacky if (isa<TerminatorInst>(I)) { 4551f22ef01cSRoman Divacky ++CurBBNo; 455291bc56edSDimitry Andric CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr; 4553f22ef01cSRoman Divacky } 4554f22ef01cSRoman Divacky 4555f22ef01cSRoman Divacky // Non-void values get registered in the value table for future use. 4556f22ef01cSRoman Divacky if (I && !I->getType()->isVoidTy()) 45578f0fd8f6SDimitry Andric ValueList.assignValue(I, NextValueNo++); 4558f22ef01cSRoman Divacky } 4559f22ef01cSRoman Divacky 4560139f7f9bSDimitry Andric OutOfRecordLoop: 4561139f7f9bSDimitry Andric 45627d523365SDimitry Andric if (!OperandBundles.empty()) 45637d523365SDimitry Andric return error("Operand bundles found with no consumer"); 45647d523365SDimitry Andric 4565f22ef01cSRoman Divacky // Check the function list for unresolved values. 4566f22ef01cSRoman Divacky if (Argument *A = dyn_cast<Argument>(ValueList.back())) { 456791bc56edSDimitry Andric if (!A->getParent()) { 4568f22ef01cSRoman Divacky // We found at least one unresolved value. Nuke them all to avoid leaks. 4569f22ef01cSRoman Divacky for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){ 457091bc56edSDimitry Andric if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) { 4571f22ef01cSRoman Divacky A->replaceAllUsesWith(UndefValue::get(A->getType())); 4572f22ef01cSRoman Divacky delete A; 4573f22ef01cSRoman Divacky } 4574f22ef01cSRoman Divacky } 45758f0fd8f6SDimitry Andric return error("Never resolved value found in function"); 4576f22ef01cSRoman Divacky } 4577f22ef01cSRoman Divacky } 4578f22ef01cSRoman Divacky 45793ca95b02SDimitry Andric // Unexpected unresolved metadata about to be dropped. 4580d88c1a5aSDimitry Andric if (MDLoader->hasFwdRefs()) 45813ca95b02SDimitry Andric return error("Invalid function metadata: outgoing forward refs"); 4582e580952dSDimitry Andric 4583f22ef01cSRoman Divacky // Trim the value list down to the size it was before we parsed this function. 4584f22ef01cSRoman Divacky ValueList.shrinkTo(ModuleValueListSize); 4585d88c1a5aSDimitry Andric MDLoader->shrinkTo(ModuleMDLoaderSize); 4586f22ef01cSRoman Divacky std::vector<BasicBlock*>().swap(FunctionBBs); 4587d88c1a5aSDimitry Andric return Error::success(); 4588f22ef01cSRoman Divacky } 4589f22ef01cSRoman Divacky 4590f785676fSDimitry Andric /// Find the function body in the bitcode stream 4591d88c1a5aSDimitry Andric Error BitcodeReader::findFunctionInStream( 459291bc56edSDimitry Andric Function *F, 4593dff0c46cSDimitry Andric DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) { 4594dff0c46cSDimitry Andric while (DeferredFunctionInfoIterator->second == 0) { 45957d523365SDimitry Andric // This is the fallback handling for the old format bitcode that 45967d523365SDimitry Andric // didn't contain the function index in the VST, or when we have 45977d523365SDimitry Andric // an anonymous function which would not have a VST entry. 45987d523365SDimitry Andric // Assert that we have one of those two cases. 45997d523365SDimitry Andric assert(VSTOffset == 0 || !F->hasName()); 46007d523365SDimitry Andric // Parse the next body in the stream and set its position in the 46017d523365SDimitry Andric // DeferredFunctionInfo map. 4602d88c1a5aSDimitry Andric if (Error Err = rememberAndSkipFunctionBodies()) 4603d88c1a5aSDimitry Andric return Err; 4604dff0c46cSDimitry Andric } 4605d88c1a5aSDimitry Andric return Error::success(); 4606dff0c46cSDimitry Andric } 4607dff0c46cSDimitry Andric 4608c4394386SDimitry Andric SyncScope::ID BitcodeReader::getDecodedSyncScopeID(unsigned Val) { 4609c4394386SDimitry Andric if (Val == SyncScope::SingleThread || Val == SyncScope::System) 4610c4394386SDimitry Andric return SyncScope::ID(Val); 4611c4394386SDimitry Andric if (Val >= SSIDs.size()) 4612c4394386SDimitry Andric return SyncScope::System; // Map unknown synchronization scopes to system. 4613c4394386SDimitry Andric return SSIDs[Val]; 4614c4394386SDimitry Andric } 4615c4394386SDimitry Andric 4616f22ef01cSRoman Divacky //===----------------------------------------------------------------------===// 4617f22ef01cSRoman Divacky // GVMaterializer implementation 4618f22ef01cSRoman Divacky //===----------------------------------------------------------------------===// 4619f22ef01cSRoman Divacky 4620d88c1a5aSDimitry Andric Error BitcodeReader::materialize(GlobalValue *GV) { 4621f22ef01cSRoman Divacky Function *F = dyn_cast<Function>(GV); 4622f22ef01cSRoman Divacky // If it's not a function or is already material, ignore the request. 4623f785676fSDimitry Andric if (!F || !F->isMaterializable()) 4624d88c1a5aSDimitry Andric return Error::success(); 4625f22ef01cSRoman Divacky 4626f22ef01cSRoman Divacky DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F); 4627f22ef01cSRoman Divacky assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!"); 4628dff0c46cSDimitry Andric // If its position is recorded as 0, its body is somewhere in the stream 4629dff0c46cSDimitry Andric // but we haven't seen it yet. 46303dac3a9bSDimitry Andric if (DFII->second == 0) 4631d88c1a5aSDimitry Andric if (Error Err = findFunctionInStream(F, DFII)) 4632d88c1a5aSDimitry Andric return Err; 4633f22ef01cSRoman Divacky 46343ca95b02SDimitry Andric // Materialize metadata before parsing any function bodies. 4635d88c1a5aSDimitry Andric if (Error Err = materializeMetadata()) 4636d88c1a5aSDimitry Andric return Err; 46373ca95b02SDimitry Andric 4638f22ef01cSRoman Divacky // Move the bit stream to the saved position of the deferred function body. 4639f22ef01cSRoman Divacky Stream.JumpToBit(DFII->second); 4640f22ef01cSRoman Divacky 4641d88c1a5aSDimitry Andric if (Error Err = parseFunctionBody(F)) 4642d88c1a5aSDimitry Andric return Err; 464339d628a0SDimitry Andric F->setIsMaterializable(false); 4644f22ef01cSRoman Divacky 4645ff0cc061SDimitry Andric if (StripDebugInfo) 4646ff0cc061SDimitry Andric stripDebugInfo(*F); 4647ff0cc061SDimitry Andric 4648f22ef01cSRoman Divacky // Upgrade any old intrinsic calls in the function. 46493dac3a9bSDimitry Andric for (auto &I : UpgradedIntrinsics) { 46507d523365SDimitry Andric for (auto UI = I.first->materialized_user_begin(), UE = I.first->user_end(); 46517d523365SDimitry Andric UI != UE;) { 46523dac3a9bSDimitry Andric User *U = *UI; 46533dac3a9bSDimitry Andric ++UI; 46543dac3a9bSDimitry Andric if (CallInst *CI = dyn_cast<CallInst>(U)) 46553dac3a9bSDimitry Andric UpgradeIntrinsicCall(CI, I.second); 4656f22ef01cSRoman Divacky } 4657f22ef01cSRoman Divacky } 4658f22ef01cSRoman Divacky 46593ca95b02SDimitry Andric // Update calls to the remangled intrinsics 46603ca95b02SDimitry Andric for (auto &I : RemangledIntrinsics) 46613ca95b02SDimitry Andric for (auto UI = I.first->materialized_user_begin(), UE = I.first->user_end(); 46623ca95b02SDimitry Andric UI != UE;) 46633ca95b02SDimitry Andric // Don't expect any other users than call sites 46643ca95b02SDimitry Andric CallSite(*UI++).setCalledFunction(I.second); 46653ca95b02SDimitry Andric 46667d523365SDimitry Andric // Finish fn->subprogram upgrade for materialized functions. 4667d88c1a5aSDimitry Andric if (DISubprogram *SP = MDLoader->lookupSubprogramForFunction(F)) 46687d523365SDimitry Andric F->setSubprogram(SP); 46697d523365SDimitry Andric 4670d88c1a5aSDimitry Andric // Check if the TBAA Metadata are valid, otherwise we will need to strip them. 4671d88c1a5aSDimitry Andric if (!MDLoader->isStrippingTBAA()) { 4672d88c1a5aSDimitry Andric for (auto &I : instructions(F)) { 4673d88c1a5aSDimitry Andric MDNode *TBAA = I.getMetadata(LLVMContext::MD_tbaa); 4674d88c1a5aSDimitry Andric if (!TBAA || TBAAVerifyHelper.visitTBAAMetadata(I, TBAA)) 4675d88c1a5aSDimitry Andric continue; 4676d88c1a5aSDimitry Andric MDLoader->setStripTBAA(true); 4677d88c1a5aSDimitry Andric stripTBAA(F->getParent()); 4678d88c1a5aSDimitry Andric } 4679d88c1a5aSDimitry Andric } 4680d88c1a5aSDimitry Andric 468139d628a0SDimitry Andric // Bring in any functions that this function forward-referenced via 468239d628a0SDimitry Andric // blockaddresses. 468339d628a0SDimitry Andric return materializeForwardReferencedFunctions(); 4684f22ef01cSRoman Divacky } 4685f22ef01cSRoman Divacky 4686d88c1a5aSDimitry Andric Error BitcodeReader::materializeModule() { 4687d88c1a5aSDimitry Andric if (Error Err = materializeMetadata()) 4688d88c1a5aSDimitry Andric return Err; 4689ff0cc061SDimitry Andric 469039d628a0SDimitry Andric // Promise to materialize all forward references. 469139d628a0SDimitry Andric WillMaterializeAllForwardRefs = true; 469239d628a0SDimitry Andric 4693f22ef01cSRoman Divacky // Iterate over the module, deserializing any functions that are still on 4694f22ef01cSRoman Divacky // disk. 46957d523365SDimitry Andric for (Function &F : *TheModule) { 4696d88c1a5aSDimitry Andric if (Error Err = materialize(&F)) 4697d88c1a5aSDimitry Andric return Err; 4698f785676fSDimitry Andric } 46997d523365SDimitry Andric // At this point, if there are any function bodies, parse the rest of 47007d523365SDimitry Andric // the bits in the module past the last function block we have recorded 47017d523365SDimitry Andric // through either lazy scanning or the VST. 47027d523365SDimitry Andric if (LastFunctionBlockBit || NextUnreadBit) 4703d88c1a5aSDimitry Andric if (Error Err = parseModule(LastFunctionBlockBit > NextUnreadBit 4704d88c1a5aSDimitry Andric ? LastFunctionBlockBit 4705d88c1a5aSDimitry Andric : NextUnreadBit)) 4706d88c1a5aSDimitry Andric return Err; 4707dff0c46cSDimitry Andric 470839d628a0SDimitry Andric // Check that all block address forward references got resolved (as we 470939d628a0SDimitry Andric // promised above). 471039d628a0SDimitry Andric if (!BasicBlockFwdRefs.empty()) 47118f0fd8f6SDimitry Andric return error("Never resolved function from blockaddress"); 471239d628a0SDimitry Andric 4713f22ef01cSRoman Divacky // Upgrade any intrinsic calls that slipped through (should not happen!) and 4714f22ef01cSRoman Divacky // delete the old functions to clean up. We can't do this unless the entire 4715f22ef01cSRoman Divacky // module is materialized because there could always be another function body 4716f22ef01cSRoman Divacky // with calls to the old function. 47173dac3a9bSDimitry Andric for (auto &I : UpgradedIntrinsics) { 47183dac3a9bSDimitry Andric for (auto *U : I.first->users()) { 47193dac3a9bSDimitry Andric if (CallInst *CI = dyn_cast<CallInst>(U)) 47203dac3a9bSDimitry Andric UpgradeIntrinsicCall(CI, I.second); 4721f22ef01cSRoman Divacky } 47223dac3a9bSDimitry Andric if (!I.first->use_empty()) 47233dac3a9bSDimitry Andric I.first->replaceAllUsesWith(I.second); 47243dac3a9bSDimitry Andric I.first->eraseFromParent(); 4725f22ef01cSRoman Divacky } 47263dac3a9bSDimitry Andric UpgradedIntrinsics.clear(); 47273ca95b02SDimitry Andric // Do the same for remangled intrinsics 47283ca95b02SDimitry Andric for (auto &I : RemangledIntrinsics) { 47293ca95b02SDimitry Andric I.first->replaceAllUsesWith(I.second); 47303ca95b02SDimitry Andric I.first->eraseFromParent(); 47313ca95b02SDimitry Andric } 47323ca95b02SDimitry Andric RemangledIntrinsics.clear(); 4733f785676fSDimitry Andric 47347d523365SDimitry Andric UpgradeDebugInfo(*TheModule); 47353ca95b02SDimitry Andric 47363ca95b02SDimitry Andric UpgradeModuleFlags(*TheModule); 4737d88c1a5aSDimitry Andric return Error::success(); 4738dff0c46cSDimitry Andric } 47396122f3e6SDimitry Andric 474039d628a0SDimitry Andric std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const { 474139d628a0SDimitry Andric return IdentifiedStructTypes; 474239d628a0SDimitry Andric } 474339d628a0SDimitry Andric 47443ca95b02SDimitry Andric ModuleSummaryIndexBitcodeReader::ModuleSummaryIndexBitcodeReader( 4745f37b6182SDimitry Andric BitstreamCursor Cursor, StringRef Strtab, ModuleSummaryIndex &TheIndex, 4746f37b6182SDimitry Andric StringRef ModulePath, unsigned ModuleId) 4747f37b6182SDimitry Andric : BitcodeReaderBase(std::move(Cursor), Strtab), TheIndex(TheIndex), 4748f37b6182SDimitry Andric ModulePath(ModulePath), ModuleId(ModuleId) {} 4749f37b6182SDimitry Andric 475024d58133SDimitry Andric ModuleSummaryIndex::ModuleInfo * 475124d58133SDimitry Andric ModuleSummaryIndexBitcodeReader::addThisModule() { 475224d58133SDimitry Andric return TheIndex.addModule(ModulePath, ModuleId); 4753f37b6182SDimitry Andric } 47543ca95b02SDimitry Andric 47550f5676f4SDimitry Andric std::pair<ValueInfo, GlobalValue::GUID> 47560f5676f4SDimitry Andric ModuleSummaryIndexBitcodeReader::getValueInfoFromValueId(unsigned ValueId) { 47570f5676f4SDimitry Andric auto VGI = ValueIdToValueInfoMap[ValueId]; 47580f5676f4SDimitry Andric assert(VGI.first); 47590f5676f4SDimitry Andric return VGI; 47607d523365SDimitry Andric } 47617d523365SDimitry Andric 47626bc11b14SDimitry Andric void ModuleSummaryIndexBitcodeReader::setValueGUID( 47636bc11b14SDimitry Andric uint64_t ValueID, StringRef ValueName, GlobalValue::LinkageTypes Linkage, 47646bc11b14SDimitry Andric StringRef SourceFileName) { 47656bc11b14SDimitry Andric std::string GlobalId = 47666bc11b14SDimitry Andric GlobalValue::getGlobalIdentifier(ValueName, Linkage, SourceFileName); 47676bc11b14SDimitry Andric auto ValueGUID = GlobalValue::getGUID(GlobalId); 47686bc11b14SDimitry Andric auto OriginalNameID = ValueGUID; 47696bc11b14SDimitry Andric if (GlobalValue::isLocalLinkage(Linkage)) 47706bc11b14SDimitry Andric OriginalNameID = GlobalValue::getGUID(ValueName); 47716bc11b14SDimitry Andric if (PrintSummaryGUIDs) 47726bc11b14SDimitry Andric dbgs() << "GUID " << ValueGUID << "(" << OriginalNameID << ") is " 47736bc11b14SDimitry Andric << ValueName << "\n"; 47740f5676f4SDimitry Andric ValueIdToValueInfoMap[ValueID] = 47750f5676f4SDimitry Andric std::make_pair(TheIndex.getOrInsertValueInfo(ValueGUID), OriginalNameID); 47766bc11b14SDimitry Andric } 47776bc11b14SDimitry Andric 47783ca95b02SDimitry Andric // Specialized value symbol table parser used when reading module index 47793ca95b02SDimitry Andric // blocks where we don't actually create global values. The parsed information 47803ca95b02SDimitry Andric // is saved in the bitcode reader for use when later parsing summaries. 4781d88c1a5aSDimitry Andric Error ModuleSummaryIndexBitcodeReader::parseValueSymbolTable( 47823ca95b02SDimitry Andric uint64_t Offset, 47833ca95b02SDimitry Andric DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap) { 47846bc11b14SDimitry Andric // With a strtab the VST is not required to parse the summary. 47856bc11b14SDimitry Andric if (UseStrtab) 47866bc11b14SDimitry Andric return Error::success(); 47876bc11b14SDimitry Andric 47883ca95b02SDimitry Andric assert(Offset > 0 && "Expected non-zero VST offset"); 47893ca95b02SDimitry Andric uint64_t CurrentBit = jumpToValueSymbolTable(Offset, Stream); 47907d523365SDimitry Andric 47917d523365SDimitry Andric if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID)) 47927d523365SDimitry Andric return error("Invalid record"); 47937d523365SDimitry Andric 47947d523365SDimitry Andric SmallVector<uint64_t, 64> Record; 47957d523365SDimitry Andric 47967d523365SDimitry Andric // Read all the records for this value table. 47977d523365SDimitry Andric SmallString<128> ValueName; 4798d88c1a5aSDimitry Andric 4799d88c1a5aSDimitry Andric while (true) { 48007d523365SDimitry Andric BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 48017d523365SDimitry Andric 48027d523365SDimitry Andric switch (Entry.Kind) { 48037d523365SDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already. 48047d523365SDimitry Andric case BitstreamEntry::Error: 48057d523365SDimitry Andric return error("Malformed block"); 48067d523365SDimitry Andric case BitstreamEntry::EndBlock: 48073ca95b02SDimitry Andric // Done parsing VST, jump back to wherever we came from. 48083ca95b02SDimitry Andric Stream.JumpToBit(CurrentBit); 4809d88c1a5aSDimitry Andric return Error::success(); 48107d523365SDimitry Andric case BitstreamEntry::Record: 48117d523365SDimitry Andric // The interesting case. 48127d523365SDimitry Andric break; 48137d523365SDimitry Andric } 48147d523365SDimitry Andric 48157d523365SDimitry Andric // Read a record. 48167d523365SDimitry Andric Record.clear(); 48177d523365SDimitry Andric switch (Stream.readRecord(Entry.ID, Record)) { 48187d523365SDimitry Andric default: // Default behavior: ignore (e.g. VST_CODE_BBENTRY records). 48197d523365SDimitry Andric break; 48203ca95b02SDimitry Andric case bitc::VST_CODE_ENTRY: { // VST_CODE_ENTRY: [valueid, namechar x N] 48213ca95b02SDimitry Andric if (convertToString(Record, 1, ValueName)) 48223ca95b02SDimitry Andric return error("Invalid record"); 48233ca95b02SDimitry Andric unsigned ValueID = Record[0]; 48243ca95b02SDimitry Andric assert(!SourceFileName.empty()); 48253ca95b02SDimitry Andric auto VLI = ValueIdToLinkageMap.find(ValueID); 48263ca95b02SDimitry Andric assert(VLI != ValueIdToLinkageMap.end() && 48273ca95b02SDimitry Andric "No linkage found for VST entry?"); 48283ca95b02SDimitry Andric auto Linkage = VLI->second; 48296bc11b14SDimitry Andric setValueGUID(ValueID, ValueName, Linkage, SourceFileName); 48303ca95b02SDimitry Andric ValueName.clear(); 48313ca95b02SDimitry Andric break; 48323ca95b02SDimitry Andric } 48337d523365SDimitry Andric case bitc::VST_CODE_FNENTRY: { 48343ca95b02SDimitry Andric // VST_CODE_FNENTRY: [valueid, offset, namechar x N] 48357d523365SDimitry Andric if (convertToString(Record, 2, ValueName)) 48367d523365SDimitry Andric return error("Invalid record"); 48377d523365SDimitry Andric unsigned ValueID = Record[0]; 48383ca95b02SDimitry Andric assert(!SourceFileName.empty()); 48393ca95b02SDimitry Andric auto VLI = ValueIdToLinkageMap.find(ValueID); 48403ca95b02SDimitry Andric assert(VLI != ValueIdToLinkageMap.end() && 48413ca95b02SDimitry Andric "No linkage found for VST entry?"); 48423ca95b02SDimitry Andric auto Linkage = VLI->second; 48436bc11b14SDimitry Andric setValueGUID(ValueID, ValueName, Linkage, SourceFileName); 48447d523365SDimitry Andric ValueName.clear(); 48457d523365SDimitry Andric break; 48467d523365SDimitry Andric } 48473ca95b02SDimitry Andric case bitc::VST_CODE_COMBINED_ENTRY: { 48483ca95b02SDimitry Andric // VST_CODE_COMBINED_ENTRY: [valueid, refguid] 48493ca95b02SDimitry Andric unsigned ValueID = Record[0]; 48503ca95b02SDimitry Andric GlobalValue::GUID RefGUID = Record[1]; 48513ca95b02SDimitry Andric // The "original name", which is the second value of the pair will be 48523ca95b02SDimitry Andric // overriden later by a FS_COMBINED_ORIGINAL_NAME in the combined index. 48530f5676f4SDimitry Andric ValueIdToValueInfoMap[ValueID] = 48540f5676f4SDimitry Andric std::make_pair(TheIndex.getOrInsertValueInfo(RefGUID), RefGUID); 48557d523365SDimitry Andric break; 48567d523365SDimitry Andric } 48577d523365SDimitry Andric } 48587d523365SDimitry Andric } 48597d523365SDimitry Andric } 48607d523365SDimitry Andric 48613ca95b02SDimitry Andric // Parse just the blocks needed for building the index out of the module. 48623ca95b02SDimitry Andric // At the end of this routine the module Index is populated with a map 48633ca95b02SDimitry Andric // from global value id to GlobalValueSummary objects. 4864f37b6182SDimitry Andric Error ModuleSummaryIndexBitcodeReader::parseModule() { 48657d523365SDimitry Andric if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID)) 48667d523365SDimitry Andric return error("Invalid record"); 48677d523365SDimitry Andric 48683ca95b02SDimitry Andric SmallVector<uint64_t, 64> Record; 48693ca95b02SDimitry Andric DenseMap<unsigned, GlobalValue::LinkageTypes> ValueIdToLinkageMap; 48703ca95b02SDimitry Andric unsigned ValueId = 0; 48713ca95b02SDimitry Andric 48723ca95b02SDimitry Andric // Read the index for this module. 4873d88c1a5aSDimitry Andric while (true) { 48747d523365SDimitry Andric BitstreamEntry Entry = Stream.advance(); 48757d523365SDimitry Andric 48767d523365SDimitry Andric switch (Entry.Kind) { 48777d523365SDimitry Andric case BitstreamEntry::Error: 48787d523365SDimitry Andric return error("Malformed block"); 48797d523365SDimitry Andric case BitstreamEntry::EndBlock: 4880d88c1a5aSDimitry Andric return Error::success(); 48817d523365SDimitry Andric 48827d523365SDimitry Andric case BitstreamEntry::SubBlock: 48837d523365SDimitry Andric switch (Entry.ID) { 48847d523365SDimitry Andric default: // Skip unknown content. 48857d523365SDimitry Andric if (Stream.SkipBlock()) 48867d523365SDimitry Andric return error("Invalid record"); 48877d523365SDimitry Andric break; 48887d523365SDimitry Andric case bitc::BLOCKINFO_BLOCK_ID: 48897d523365SDimitry Andric // Need to parse these to get abbrev ids (e.g. for VST) 4890d88c1a5aSDimitry Andric if (readBlockInfo()) 48917d523365SDimitry Andric return error("Malformed block"); 48927d523365SDimitry Andric break; 48937d523365SDimitry Andric case bitc::VALUE_SYMTAB_BLOCK_ID: 48943ca95b02SDimitry Andric // Should have been parsed earlier via VSTOffset, unless there 48953ca95b02SDimitry Andric // is no summary section. 48963ca95b02SDimitry Andric assert(((SeenValueSymbolTable && VSTOffset > 0) || 48973ca95b02SDimitry Andric !SeenGlobalValSummary) && 48983ca95b02SDimitry Andric "Expected early VST parse via VSTOffset record"); 48997d523365SDimitry Andric if (Stream.SkipBlock()) 49007d523365SDimitry Andric return error("Invalid record"); 49013ca95b02SDimitry Andric break; 49023ca95b02SDimitry Andric case bitc::GLOBALVAL_SUMMARY_BLOCK_ID: 490324d58133SDimitry Andric case bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID: 49043ca95b02SDimitry Andric assert(!SeenValueSymbolTable && 49053ca95b02SDimitry Andric "Already read VST when parsing summary block?"); 4906d88c1a5aSDimitry Andric // We might not have a VST if there were no values in the 4907d88c1a5aSDimitry Andric // summary. An empty summary block generated when we are 4908d88c1a5aSDimitry Andric // performing ThinLTO compiles so we don't later invoke 4909d88c1a5aSDimitry Andric // the regular LTO process on them. 4910d88c1a5aSDimitry Andric if (VSTOffset > 0) { 4911d88c1a5aSDimitry Andric if (Error Err = parseValueSymbolTable(VSTOffset, ValueIdToLinkageMap)) 4912d88c1a5aSDimitry Andric return Err; 49133ca95b02SDimitry Andric SeenValueSymbolTable = true; 4914d88c1a5aSDimitry Andric } 49153ca95b02SDimitry Andric SeenGlobalValSummary = true; 491624d58133SDimitry Andric if (Error Err = parseEntireSummary(Entry.ID)) 4917d88c1a5aSDimitry Andric return Err; 49187d523365SDimitry Andric break; 49197d523365SDimitry Andric case bitc::MODULE_STRTAB_BLOCK_ID: 4920d88c1a5aSDimitry Andric if (Error Err = parseModuleStringTable()) 4921d88c1a5aSDimitry Andric return Err; 49227d523365SDimitry Andric break; 49237d523365SDimitry Andric } 49247d523365SDimitry Andric continue; 49257d523365SDimitry Andric 49263ca95b02SDimitry Andric case BitstreamEntry::Record: { 49273ca95b02SDimitry Andric Record.clear(); 49283ca95b02SDimitry Andric auto BitCode = Stream.readRecord(Entry.ID, Record); 49293ca95b02SDimitry Andric switch (BitCode) { 49303ca95b02SDimitry Andric default: 49313ca95b02SDimitry Andric break; // Default behavior, ignore unknown content. 49326bc11b14SDimitry Andric case bitc::MODULE_CODE_VERSION: { 49336bc11b14SDimitry Andric if (Error Err = parseVersionRecord(Record).takeError()) 49346bc11b14SDimitry Andric return Err; 49356bc11b14SDimitry Andric break; 49366bc11b14SDimitry Andric } 49373ca95b02SDimitry Andric /// MODULE_CODE_SOURCE_FILENAME: [namechar x N] 49383ca95b02SDimitry Andric case bitc::MODULE_CODE_SOURCE_FILENAME: { 49393ca95b02SDimitry Andric SmallString<128> ValueName; 49403ca95b02SDimitry Andric if (convertToString(Record, 0, ValueName)) 49413ca95b02SDimitry Andric return error("Invalid record"); 49423ca95b02SDimitry Andric SourceFileName = ValueName.c_str(); 49433ca95b02SDimitry Andric break; 49443ca95b02SDimitry Andric } 49453ca95b02SDimitry Andric /// MODULE_CODE_HASH: [5*i32] 49463ca95b02SDimitry Andric case bitc::MODULE_CODE_HASH: { 49473ca95b02SDimitry Andric if (Record.size() != 5) 49483ca95b02SDimitry Andric return error("Invalid hash length " + Twine(Record.size()).str()); 494924d58133SDimitry Andric auto &Hash = addThisModule()->second.second; 49503ca95b02SDimitry Andric int Pos = 0; 49513ca95b02SDimitry Andric for (auto &Val : Record) { 49523ca95b02SDimitry Andric assert(!(Val >> 32) && "Unexpected high bits set"); 49533ca95b02SDimitry Andric Hash[Pos++] = Val; 49543ca95b02SDimitry Andric } 49553ca95b02SDimitry Andric break; 49563ca95b02SDimitry Andric } 49573ca95b02SDimitry Andric /// MODULE_CODE_VSTOFFSET: [offset] 49583ca95b02SDimitry Andric case bitc::MODULE_CODE_VSTOFFSET: 49593ca95b02SDimitry Andric if (Record.size() < 1) 49603ca95b02SDimitry Andric return error("Invalid record"); 4961d88c1a5aSDimitry Andric // Note that we subtract 1 here because the offset is relative to one 4962d88c1a5aSDimitry Andric // word before the start of the identification or module block, which 4963d88c1a5aSDimitry Andric // was historically always the start of the regular bitcode header. 4964d88c1a5aSDimitry Andric VSTOffset = Record[0] - 1; 49653ca95b02SDimitry Andric break; 49666bc11b14SDimitry Andric // v1 GLOBALVAR: [pointer type, isconst, initid, linkage, ...] 49676bc11b14SDimitry Andric // v1 FUNCTION: [type, callingconv, isproto, linkage, ...] 49686bc11b14SDimitry Andric // v1 ALIAS: [alias type, addrspace, aliasee val#, linkage, ...] 49696bc11b14SDimitry Andric // v2: [strtab offset, strtab size, v1] 49707a7e6055SDimitry Andric case bitc::MODULE_CODE_GLOBALVAR: 49717a7e6055SDimitry Andric case bitc::MODULE_CODE_FUNCTION: 49723ca95b02SDimitry Andric case bitc::MODULE_CODE_ALIAS: { 49736bc11b14SDimitry Andric StringRef Name; 49746bc11b14SDimitry Andric ArrayRef<uint64_t> GVRecord; 49756bc11b14SDimitry Andric std::tie(Name, GVRecord) = readNameFromStrtab(Record); 49766bc11b14SDimitry Andric if (GVRecord.size() <= 3) 49773ca95b02SDimitry Andric return error("Invalid record"); 49786bc11b14SDimitry Andric uint64_t RawLinkage = GVRecord[3]; 49793ca95b02SDimitry Andric GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage); 49806bc11b14SDimitry Andric if (!UseStrtab) { 49813ca95b02SDimitry Andric ValueIdToLinkageMap[ValueId++] = Linkage; 49823ca95b02SDimitry Andric break; 49833ca95b02SDimitry Andric } 49846bc11b14SDimitry Andric 49856bc11b14SDimitry Andric setValueGUID(ValueId++, Name, Linkage, SourceFileName); 49866bc11b14SDimitry Andric break; 49876bc11b14SDimitry Andric } 49883ca95b02SDimitry Andric } 49893ca95b02SDimitry Andric } 49907d523365SDimitry Andric continue; 49917d523365SDimitry Andric } 49927d523365SDimitry Andric } 49937d523365SDimitry Andric } 49947d523365SDimitry Andric 4995d88c1a5aSDimitry Andric std::vector<ValueInfo> 4996d88c1a5aSDimitry Andric ModuleSummaryIndexBitcodeReader::makeRefList(ArrayRef<uint64_t> Record) { 4997d88c1a5aSDimitry Andric std::vector<ValueInfo> Ret; 4998d88c1a5aSDimitry Andric Ret.reserve(Record.size()); 4999d88c1a5aSDimitry Andric for (uint64_t RefValueId : Record) 50000f5676f4SDimitry Andric Ret.push_back(getValueInfoFromValueId(RefValueId).first); 5001d88c1a5aSDimitry Andric return Ret; 5002d88c1a5aSDimitry Andric } 5003d88c1a5aSDimitry Andric 5004d88c1a5aSDimitry Andric std::vector<FunctionSummary::EdgeTy> ModuleSummaryIndexBitcodeReader::makeCallList( 5005d88c1a5aSDimitry Andric ArrayRef<uint64_t> Record, bool IsOldProfileFormat, bool HasProfile) { 5006d88c1a5aSDimitry Andric std::vector<FunctionSummary::EdgeTy> Ret; 5007d88c1a5aSDimitry Andric Ret.reserve(Record.size()); 5008d88c1a5aSDimitry Andric for (unsigned I = 0, E = Record.size(); I != E; ++I) { 5009d88c1a5aSDimitry Andric CalleeInfo::HotnessType Hotness = CalleeInfo::HotnessType::Unknown; 50100f5676f4SDimitry Andric ValueInfo Callee = getValueInfoFromValueId(Record[I]).first; 5011d88c1a5aSDimitry Andric if (IsOldProfileFormat) { 5012d88c1a5aSDimitry Andric I += 1; // Skip old callsitecount field 5013d88c1a5aSDimitry Andric if (HasProfile) 5014d88c1a5aSDimitry Andric I += 1; // Skip old profilecount field 5015d88c1a5aSDimitry Andric } else if (HasProfile) 5016d88c1a5aSDimitry Andric Hotness = static_cast<CalleeInfo::HotnessType>(Record[++I]); 50170f5676f4SDimitry Andric Ret.push_back(FunctionSummary::EdgeTy{Callee, CalleeInfo{Hotness}}); 5018d88c1a5aSDimitry Andric } 5019d88c1a5aSDimitry Andric return Ret; 5020d88c1a5aSDimitry Andric } 5021d88c1a5aSDimitry Andric 50223ca95b02SDimitry Andric // Eagerly parse the entire summary block. This populates the GlobalValueSummary 50233ca95b02SDimitry Andric // objects in the index. 502424d58133SDimitry Andric Error ModuleSummaryIndexBitcodeReader::parseEntireSummary(unsigned ID) { 502524d58133SDimitry Andric if (Stream.EnterSubBlock(ID)) 50267d523365SDimitry Andric return error("Invalid record"); 50277d523365SDimitry Andric SmallVector<uint64_t, 64> Record; 50287d523365SDimitry Andric 50293ca95b02SDimitry Andric // Parse version 50303ca95b02SDimitry Andric { 50313ca95b02SDimitry Andric BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 50323ca95b02SDimitry Andric if (Entry.Kind != BitstreamEntry::Record) 50333ca95b02SDimitry Andric return error("Invalid Summary Block: record for version expected"); 50343ca95b02SDimitry Andric if (Stream.readRecord(Entry.ID, Record) != bitc::FS_VERSION) 50353ca95b02SDimitry Andric return error("Invalid Summary Block: version expected"); 50363ca95b02SDimitry Andric } 50373ca95b02SDimitry Andric const uint64_t Version = Record[0]; 5038d88c1a5aSDimitry Andric const bool IsOldProfileFormat = Version == 1; 503995ec533aSDimitry Andric if (Version < 1 || Version > 3) 5040d88c1a5aSDimitry Andric return error("Invalid summary version " + Twine(Version) + 504195ec533aSDimitry Andric ", 1, 2 or 3 expected"); 50423ca95b02SDimitry Andric Record.clear(); 50433ca95b02SDimitry Andric 50443ca95b02SDimitry Andric // Keep around the last seen summary to be used when we see an optional 50453ca95b02SDimitry Andric // "OriginalName" attachement. 50463ca95b02SDimitry Andric GlobalValueSummary *LastSeenSummary = nullptr; 50477a7e6055SDimitry Andric GlobalValue::GUID LastSeenGUID = 0; 50487a7e6055SDimitry Andric 50497a7e6055SDimitry Andric // We can expect to see any number of type ID information records before 50507a7e6055SDimitry Andric // each function summary records; these variables store the information 50517a7e6055SDimitry Andric // collected so far so that it can be used to create the summary object. 5052d88c1a5aSDimitry Andric std::vector<GlobalValue::GUID> PendingTypeTests; 50537a7e6055SDimitry Andric std::vector<FunctionSummary::VFuncId> PendingTypeTestAssumeVCalls, 50547a7e6055SDimitry Andric PendingTypeCheckedLoadVCalls; 50557a7e6055SDimitry Andric std::vector<FunctionSummary::ConstVCall> PendingTypeTestAssumeConstVCalls, 50567a7e6055SDimitry Andric PendingTypeCheckedLoadConstVCalls; 5057d88c1a5aSDimitry Andric 5058d88c1a5aSDimitry Andric while (true) { 50597d523365SDimitry Andric BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 50607d523365SDimitry Andric 50617d523365SDimitry Andric switch (Entry.Kind) { 50627d523365SDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already. 50637d523365SDimitry Andric case BitstreamEntry::Error: 50647d523365SDimitry Andric return error("Malformed block"); 50657d523365SDimitry Andric case BitstreamEntry::EndBlock: 5066d88c1a5aSDimitry Andric return Error::success(); 50677d523365SDimitry Andric case BitstreamEntry::Record: 50687d523365SDimitry Andric // The interesting case. 50697d523365SDimitry Andric break; 50707d523365SDimitry Andric } 50717d523365SDimitry Andric 50727d523365SDimitry Andric // Read a record. The record format depends on whether this 50737d523365SDimitry Andric // is a per-module index or a combined index file. In the per-module 50747d523365SDimitry Andric // case the records contain the associated value's ID for correlation 50757d523365SDimitry Andric // with VST entries. In the combined index the correlation is done 50767d523365SDimitry Andric // via the bitcode offset of the summary records (which were saved 50777d523365SDimitry Andric // in the combined index VST entries). The records also contain 50787d523365SDimitry Andric // information used for ThinLTO renaming and importing. 50797d523365SDimitry Andric Record.clear(); 50803ca95b02SDimitry Andric auto BitCode = Stream.readRecord(Entry.ID, Record); 50813ca95b02SDimitry Andric switch (BitCode) { 50827d523365SDimitry Andric default: // Default behavior: ignore. 50837d523365SDimitry Andric break; 50846bc11b14SDimitry Andric case bitc::FS_VALUE_GUID: { // [valueid, refguid] 50856bc11b14SDimitry Andric uint64_t ValueID = Record[0]; 50866bc11b14SDimitry Andric GlobalValue::GUID RefGUID = Record[1]; 50870f5676f4SDimitry Andric ValueIdToValueInfoMap[ValueID] = 50880f5676f4SDimitry Andric std::make_pair(TheIndex.getOrInsertValueInfo(RefGUID), RefGUID); 50896bc11b14SDimitry Andric break; 50906bc11b14SDimitry Andric } 50913ca95b02SDimitry Andric // FS_PERMODULE: [valueid, flags, instcount, numrefs, numrefs x valueid, 5092d88c1a5aSDimitry Andric // n x (valueid)] 50933ca95b02SDimitry Andric // FS_PERMODULE_PROFILE: [valueid, flags, instcount, numrefs, 50943ca95b02SDimitry Andric // numrefs x valueid, 5095d88c1a5aSDimitry Andric // n x (valueid, hotness)] 50963ca95b02SDimitry Andric case bitc::FS_PERMODULE: 50973ca95b02SDimitry Andric case bitc::FS_PERMODULE_PROFILE: { 50987d523365SDimitry Andric unsigned ValueID = Record[0]; 50993ca95b02SDimitry Andric uint64_t RawFlags = Record[1]; 51007d523365SDimitry Andric unsigned InstCount = Record[2]; 51013ca95b02SDimitry Andric unsigned NumRefs = Record[3]; 51023ca95b02SDimitry Andric auto Flags = getDecodedGVSummaryFlags(RawFlags, Version); 51037d523365SDimitry Andric // The module path string ref set in the summary must be owned by the 51047d523365SDimitry Andric // index's module string table. Since we don't have a module path 51057d523365SDimitry Andric // string table section in the per-module index, we create a single 51067d523365SDimitry Andric // module path string table entry with an empty (0) ID to take 51077d523365SDimitry Andric // ownership. 51083ca95b02SDimitry Andric static int RefListStartIndex = 4; 51093ca95b02SDimitry Andric int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs; 51103ca95b02SDimitry Andric assert(Record.size() >= RefListStartIndex + NumRefs && 51113ca95b02SDimitry Andric "Record size inconsistent with number of references"); 5112d88c1a5aSDimitry Andric std::vector<ValueInfo> Refs = makeRefList( 5113d88c1a5aSDimitry Andric ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs)); 51143ca95b02SDimitry Andric bool HasProfile = (BitCode == bitc::FS_PERMODULE_PROFILE); 5115d88c1a5aSDimitry Andric std::vector<FunctionSummary::EdgeTy> Calls = makeCallList( 5116d88c1a5aSDimitry Andric ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex), 5117d88c1a5aSDimitry Andric IsOldProfileFormat, HasProfile); 5118d88c1a5aSDimitry Andric auto FS = llvm::make_unique<FunctionSummary>( 5119d88c1a5aSDimitry Andric Flags, InstCount, std::move(Refs), std::move(Calls), 51207a7e6055SDimitry Andric std::move(PendingTypeTests), std::move(PendingTypeTestAssumeVCalls), 51217a7e6055SDimitry Andric std::move(PendingTypeCheckedLoadVCalls), 51227a7e6055SDimitry Andric std::move(PendingTypeTestAssumeConstVCalls), 51237a7e6055SDimitry Andric std::move(PendingTypeCheckedLoadConstVCalls)); 5124d88c1a5aSDimitry Andric PendingTypeTests.clear(); 51257a7e6055SDimitry Andric PendingTypeTestAssumeVCalls.clear(); 51267a7e6055SDimitry Andric PendingTypeCheckedLoadVCalls.clear(); 51277a7e6055SDimitry Andric PendingTypeTestAssumeConstVCalls.clear(); 51287a7e6055SDimitry Andric PendingTypeCheckedLoadConstVCalls.clear(); 51290f5676f4SDimitry Andric auto VIAndOriginalGUID = getValueInfoFromValueId(ValueID); 513024d58133SDimitry Andric FS->setModulePath(addThisModule()->first()); 51310f5676f4SDimitry Andric FS->setOriginalName(VIAndOriginalGUID.second); 51320f5676f4SDimitry Andric TheIndex.addGlobalValueSummary(VIAndOriginalGUID.first, std::move(FS)); 51333ca95b02SDimitry Andric break; 51343ca95b02SDimitry Andric } 51353ca95b02SDimitry Andric // FS_ALIAS: [valueid, flags, valueid] 51363ca95b02SDimitry Andric // Aliases must be emitted (and parsed) after all FS_PERMODULE entries, as 51373ca95b02SDimitry Andric // they expect all aliasee summaries to be available. 51383ca95b02SDimitry Andric case bitc::FS_ALIAS: { 51393ca95b02SDimitry Andric unsigned ValueID = Record[0]; 51403ca95b02SDimitry Andric uint64_t RawFlags = Record[1]; 51413ca95b02SDimitry Andric unsigned AliaseeID = Record[2]; 51423ca95b02SDimitry Andric auto Flags = getDecodedGVSummaryFlags(RawFlags, Version); 5143d88c1a5aSDimitry Andric auto AS = 5144d88c1a5aSDimitry Andric llvm::make_unique<AliasSummary>(Flags, std::vector<ValueInfo>{}); 51453ca95b02SDimitry Andric // The module path string ref set in the summary must be owned by the 51463ca95b02SDimitry Andric // index's module string table. Since we don't have a module path 51473ca95b02SDimitry Andric // string table section in the per-module index, we create a single 51483ca95b02SDimitry Andric // module path string table entry with an empty (0) ID to take 51493ca95b02SDimitry Andric // ownership. 515024d58133SDimitry Andric AS->setModulePath(addThisModule()->first()); 51513ca95b02SDimitry Andric 51520f5676f4SDimitry Andric GlobalValue::GUID AliaseeGUID = 51530f5676f4SDimitry Andric getValueInfoFromValueId(AliaseeID).first.getGUID(); 5154f37b6182SDimitry Andric auto AliaseeInModule = 5155f37b6182SDimitry Andric TheIndex.findSummaryInModule(AliaseeGUID, ModulePath); 5156f37b6182SDimitry Andric if (!AliaseeInModule) 51573ca95b02SDimitry Andric return error("Alias expects aliasee summary to be parsed"); 5158f37b6182SDimitry Andric AS->setAliasee(AliaseeInModule); 51593ca95b02SDimitry Andric 51600f5676f4SDimitry Andric auto GUID = getValueInfoFromValueId(ValueID); 51613ca95b02SDimitry Andric AS->setOriginalName(GUID.second); 5162d88c1a5aSDimitry Andric TheIndex.addGlobalValueSummary(GUID.first, std::move(AS)); 51633ca95b02SDimitry Andric break; 51643ca95b02SDimitry Andric } 51653ca95b02SDimitry Andric // FS_PERMODULE_GLOBALVAR_INIT_REFS: [valueid, flags, n x valueid] 51663ca95b02SDimitry Andric case bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS: { 51673ca95b02SDimitry Andric unsigned ValueID = Record[0]; 51683ca95b02SDimitry Andric uint64_t RawFlags = Record[1]; 51693ca95b02SDimitry Andric auto Flags = getDecodedGVSummaryFlags(RawFlags, Version); 5170d88c1a5aSDimitry Andric std::vector<ValueInfo> Refs = 5171d88c1a5aSDimitry Andric makeRefList(ArrayRef<uint64_t>(Record).slice(2)); 5172d88c1a5aSDimitry Andric auto FS = llvm::make_unique<GlobalVarSummary>(Flags, std::move(Refs)); 517324d58133SDimitry Andric FS->setModulePath(addThisModule()->first()); 51740f5676f4SDimitry Andric auto GUID = getValueInfoFromValueId(ValueID); 51753ca95b02SDimitry Andric FS->setOriginalName(GUID.second); 5176d88c1a5aSDimitry Andric TheIndex.addGlobalValueSummary(GUID.first, std::move(FS)); 51773ca95b02SDimitry Andric break; 51783ca95b02SDimitry Andric } 51793ca95b02SDimitry Andric // FS_COMBINED: [valueid, modid, flags, instcount, numrefs, 5180d88c1a5aSDimitry Andric // numrefs x valueid, n x (valueid)] 51813ca95b02SDimitry Andric // FS_COMBINED_PROFILE: [valueid, modid, flags, instcount, numrefs, 5182d88c1a5aSDimitry Andric // numrefs x valueid, n x (valueid, hotness)] 51833ca95b02SDimitry Andric case bitc::FS_COMBINED: 51843ca95b02SDimitry Andric case bitc::FS_COMBINED_PROFILE: { 51853ca95b02SDimitry Andric unsigned ValueID = Record[0]; 51863ca95b02SDimitry Andric uint64_t ModuleId = Record[1]; 51873ca95b02SDimitry Andric uint64_t RawFlags = Record[2]; 51883ca95b02SDimitry Andric unsigned InstCount = Record[3]; 51893ca95b02SDimitry Andric unsigned NumRefs = Record[4]; 51903ca95b02SDimitry Andric auto Flags = getDecodedGVSummaryFlags(RawFlags, Version); 51913ca95b02SDimitry Andric static int RefListStartIndex = 5; 51923ca95b02SDimitry Andric int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs; 51933ca95b02SDimitry Andric assert(Record.size() >= RefListStartIndex + NumRefs && 51943ca95b02SDimitry Andric "Record size inconsistent with number of references"); 5195d88c1a5aSDimitry Andric std::vector<ValueInfo> Refs = makeRefList( 5196d88c1a5aSDimitry Andric ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs)); 51973ca95b02SDimitry Andric bool HasProfile = (BitCode == bitc::FS_COMBINED_PROFILE); 5198d88c1a5aSDimitry Andric std::vector<FunctionSummary::EdgeTy> Edges = makeCallList( 5199d88c1a5aSDimitry Andric ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex), 5200d88c1a5aSDimitry Andric IsOldProfileFormat, HasProfile); 52010f5676f4SDimitry Andric ValueInfo VI = getValueInfoFromValueId(ValueID).first; 5202d88c1a5aSDimitry Andric auto FS = llvm::make_unique<FunctionSummary>( 5203d88c1a5aSDimitry Andric Flags, InstCount, std::move(Refs), std::move(Edges), 52047a7e6055SDimitry Andric std::move(PendingTypeTests), std::move(PendingTypeTestAssumeVCalls), 52057a7e6055SDimitry Andric std::move(PendingTypeCheckedLoadVCalls), 52067a7e6055SDimitry Andric std::move(PendingTypeTestAssumeConstVCalls), 52077a7e6055SDimitry Andric std::move(PendingTypeCheckedLoadConstVCalls)); 5208d88c1a5aSDimitry Andric PendingTypeTests.clear(); 52097a7e6055SDimitry Andric PendingTypeTestAssumeVCalls.clear(); 52107a7e6055SDimitry Andric PendingTypeCheckedLoadVCalls.clear(); 52117a7e6055SDimitry Andric PendingTypeTestAssumeConstVCalls.clear(); 52127a7e6055SDimitry Andric PendingTypeCheckedLoadConstVCalls.clear(); 5213d88c1a5aSDimitry Andric LastSeenSummary = FS.get(); 52140f5676f4SDimitry Andric LastSeenGUID = VI.getGUID(); 5215d88c1a5aSDimitry Andric FS->setModulePath(ModuleIdMap[ModuleId]); 52160f5676f4SDimitry Andric TheIndex.addGlobalValueSummary(VI, std::move(FS)); 52173ca95b02SDimitry Andric break; 52183ca95b02SDimitry Andric } 52193ca95b02SDimitry Andric // FS_COMBINED_ALIAS: [valueid, modid, flags, valueid] 52203ca95b02SDimitry Andric // Aliases must be emitted (and parsed) after all FS_COMBINED entries, as 52213ca95b02SDimitry Andric // they expect all aliasee summaries to be available. 52223ca95b02SDimitry Andric case bitc::FS_COMBINED_ALIAS: { 52233ca95b02SDimitry Andric unsigned ValueID = Record[0]; 52243ca95b02SDimitry Andric uint64_t ModuleId = Record[1]; 52253ca95b02SDimitry Andric uint64_t RawFlags = Record[2]; 52263ca95b02SDimitry Andric unsigned AliaseeValueId = Record[3]; 52273ca95b02SDimitry Andric auto Flags = getDecodedGVSummaryFlags(RawFlags, Version); 5228d88c1a5aSDimitry Andric auto AS = llvm::make_unique<AliasSummary>(Flags, std::vector<ValueInfo>{}); 52293ca95b02SDimitry Andric LastSeenSummary = AS.get(); 52303ca95b02SDimitry Andric AS->setModulePath(ModuleIdMap[ModuleId]); 52313ca95b02SDimitry Andric 52320f5676f4SDimitry Andric auto AliaseeGUID = 52330f5676f4SDimitry Andric getValueInfoFromValueId(AliaseeValueId).first.getGUID(); 52343ca95b02SDimitry Andric auto AliaseeInModule = 5235d88c1a5aSDimitry Andric TheIndex.findSummaryInModule(AliaseeGUID, AS->modulePath()); 52363ca95b02SDimitry Andric if (!AliaseeInModule) 52373ca95b02SDimitry Andric return error("Alias expects aliasee summary to be parsed"); 52383ca95b02SDimitry Andric AS->setAliasee(AliaseeInModule); 52393ca95b02SDimitry Andric 52400f5676f4SDimitry Andric ValueInfo VI = getValueInfoFromValueId(ValueID).first; 52410f5676f4SDimitry Andric LastSeenGUID = VI.getGUID(); 52420f5676f4SDimitry Andric TheIndex.addGlobalValueSummary(VI, std::move(AS)); 52433ca95b02SDimitry Andric break; 52443ca95b02SDimitry Andric } 52453ca95b02SDimitry Andric // FS_COMBINED_GLOBALVAR_INIT_REFS: [valueid, modid, flags, n x valueid] 52463ca95b02SDimitry Andric case bitc::FS_COMBINED_GLOBALVAR_INIT_REFS: { 52473ca95b02SDimitry Andric unsigned ValueID = Record[0]; 52483ca95b02SDimitry Andric uint64_t ModuleId = Record[1]; 52493ca95b02SDimitry Andric uint64_t RawFlags = Record[2]; 52503ca95b02SDimitry Andric auto Flags = getDecodedGVSummaryFlags(RawFlags, Version); 5251d88c1a5aSDimitry Andric std::vector<ValueInfo> Refs = 5252d88c1a5aSDimitry Andric makeRefList(ArrayRef<uint64_t>(Record).slice(3)); 5253d88c1a5aSDimitry Andric auto FS = llvm::make_unique<GlobalVarSummary>(Flags, std::move(Refs)); 52543ca95b02SDimitry Andric LastSeenSummary = FS.get(); 52553ca95b02SDimitry Andric FS->setModulePath(ModuleIdMap[ModuleId]); 52560f5676f4SDimitry Andric ValueInfo VI = getValueInfoFromValueId(ValueID).first; 52570f5676f4SDimitry Andric LastSeenGUID = VI.getGUID(); 52580f5676f4SDimitry Andric TheIndex.addGlobalValueSummary(VI, std::move(FS)); 52593ca95b02SDimitry Andric break; 52603ca95b02SDimitry Andric } 52613ca95b02SDimitry Andric // FS_COMBINED_ORIGINAL_NAME: [original_name] 52623ca95b02SDimitry Andric case bitc::FS_COMBINED_ORIGINAL_NAME: { 52633ca95b02SDimitry Andric uint64_t OriginalName = Record[0]; 52643ca95b02SDimitry Andric if (!LastSeenSummary) 52653ca95b02SDimitry Andric return error("Name attachment that does not follow a combined record"); 52663ca95b02SDimitry Andric LastSeenSummary->setOriginalName(OriginalName); 52677a7e6055SDimitry Andric TheIndex.addOriginalName(LastSeenGUID, OriginalName); 52683ca95b02SDimitry Andric // Reset the LastSeenSummary 52693ca95b02SDimitry Andric LastSeenSummary = nullptr; 52707a7e6055SDimitry Andric LastSeenGUID = 0; 5271d88c1a5aSDimitry Andric break; 5272d88c1a5aSDimitry Andric } 5273d88c1a5aSDimitry Andric case bitc::FS_TYPE_TESTS: { 5274d88c1a5aSDimitry Andric assert(PendingTypeTests.empty()); 5275d88c1a5aSDimitry Andric PendingTypeTests.insert(PendingTypeTests.end(), Record.begin(), 5276d88c1a5aSDimitry Andric Record.end()); 5277d88c1a5aSDimitry Andric break; 52787d523365SDimitry Andric } 52797a7e6055SDimitry Andric case bitc::FS_TYPE_TEST_ASSUME_VCALLS: { 52807a7e6055SDimitry Andric assert(PendingTypeTestAssumeVCalls.empty()); 52817a7e6055SDimitry Andric for (unsigned I = 0; I != Record.size(); I += 2) 52827a7e6055SDimitry Andric PendingTypeTestAssumeVCalls.push_back({Record[I], Record[I+1]}); 52837a7e6055SDimitry Andric break; 52847a7e6055SDimitry Andric } 52857a7e6055SDimitry Andric case bitc::FS_TYPE_CHECKED_LOAD_VCALLS: { 52867a7e6055SDimitry Andric assert(PendingTypeCheckedLoadVCalls.empty()); 52877a7e6055SDimitry Andric for (unsigned I = 0; I != Record.size(); I += 2) 52887a7e6055SDimitry Andric PendingTypeCheckedLoadVCalls.push_back({Record[I], Record[I+1]}); 52897a7e6055SDimitry Andric break; 52907a7e6055SDimitry Andric } 52917a7e6055SDimitry Andric case bitc::FS_TYPE_TEST_ASSUME_CONST_VCALL: { 52927a7e6055SDimitry Andric PendingTypeTestAssumeConstVCalls.push_back( 52937a7e6055SDimitry Andric {{Record[0], Record[1]}, {Record.begin() + 2, Record.end()}}); 52947a7e6055SDimitry Andric break; 52957a7e6055SDimitry Andric } 52967a7e6055SDimitry Andric case bitc::FS_TYPE_CHECKED_LOAD_CONST_VCALL: { 52977a7e6055SDimitry Andric PendingTypeCheckedLoadConstVCalls.push_back( 52987a7e6055SDimitry Andric {{Record[0], Record[1]}, {Record.begin() + 2, Record.end()}}); 52997a7e6055SDimitry Andric break; 53007a7e6055SDimitry Andric } 530124d58133SDimitry Andric case bitc::FS_CFI_FUNCTION_DEFS: { 530224d58133SDimitry Andric std::set<std::string> &CfiFunctionDefs = TheIndex.cfiFunctionDefs(); 530324d58133SDimitry Andric for (unsigned I = 0; I != Record.size(); I += 2) 530424d58133SDimitry Andric CfiFunctionDefs.insert( 530524d58133SDimitry Andric {Strtab.data() + Record[I], static_cast<size_t>(Record[I + 1])}); 530624d58133SDimitry Andric break; 530724d58133SDimitry Andric } 530824d58133SDimitry Andric case bitc::FS_CFI_FUNCTION_DECLS: { 530924d58133SDimitry Andric std::set<std::string> &CfiFunctionDecls = TheIndex.cfiFunctionDecls(); 531024d58133SDimitry Andric for (unsigned I = 0; I != Record.size(); I += 2) 531124d58133SDimitry Andric CfiFunctionDecls.insert( 531224d58133SDimitry Andric {Strtab.data() + Record[I], static_cast<size_t>(Record[I + 1])}); 531324d58133SDimitry Andric break; 531424d58133SDimitry Andric } 53157d523365SDimitry Andric } 53167d523365SDimitry Andric } 53177d523365SDimitry Andric llvm_unreachable("Exit infinite loop"); 53187d523365SDimitry Andric } 53197d523365SDimitry Andric 53207d523365SDimitry Andric // Parse the module string table block into the Index. 53217d523365SDimitry Andric // This populates the ModulePathStringTable map in the index. 5322d88c1a5aSDimitry Andric Error ModuleSummaryIndexBitcodeReader::parseModuleStringTable() { 53237d523365SDimitry Andric if (Stream.EnterSubBlock(bitc::MODULE_STRTAB_BLOCK_ID)) 53247d523365SDimitry Andric return error("Invalid record"); 53257d523365SDimitry Andric 53267d523365SDimitry Andric SmallVector<uint64_t, 64> Record; 53277d523365SDimitry Andric 53287d523365SDimitry Andric SmallString<128> ModulePath; 532924d58133SDimitry Andric ModuleSummaryIndex::ModuleInfo *LastSeenModule = nullptr; 5330d88c1a5aSDimitry Andric 5331d88c1a5aSDimitry Andric while (true) { 53327d523365SDimitry Andric BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 53337d523365SDimitry Andric 53347d523365SDimitry Andric switch (Entry.Kind) { 53357d523365SDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already. 53367d523365SDimitry Andric case BitstreamEntry::Error: 53377d523365SDimitry Andric return error("Malformed block"); 53387d523365SDimitry Andric case BitstreamEntry::EndBlock: 5339d88c1a5aSDimitry Andric return Error::success(); 53407d523365SDimitry Andric case BitstreamEntry::Record: 53417d523365SDimitry Andric // The interesting case. 53427d523365SDimitry Andric break; 53437d523365SDimitry Andric } 53447d523365SDimitry Andric 53457d523365SDimitry Andric Record.clear(); 53467d523365SDimitry Andric switch (Stream.readRecord(Entry.ID, Record)) { 53477d523365SDimitry Andric default: // Default behavior: ignore. 53487d523365SDimitry Andric break; 53497d523365SDimitry Andric case bitc::MST_CODE_ENTRY: { 53507d523365SDimitry Andric // MST_ENTRY: [modid, namechar x N] 53513ca95b02SDimitry Andric uint64_t ModuleId = Record[0]; 53523ca95b02SDimitry Andric 53537d523365SDimitry Andric if (convertToString(Record, 1, ModulePath)) 53547d523365SDimitry Andric return error("Invalid record"); 53553ca95b02SDimitry Andric 535624d58133SDimitry Andric LastSeenModule = TheIndex.addModule(ModulePath, ModuleId); 535724d58133SDimitry Andric ModuleIdMap[ModuleId] = LastSeenModule->first(); 53583ca95b02SDimitry Andric 53597d523365SDimitry Andric ModulePath.clear(); 53607d523365SDimitry Andric break; 53617d523365SDimitry Andric } 53623ca95b02SDimitry Andric /// MST_CODE_HASH: [5*i32] 53633ca95b02SDimitry Andric case bitc::MST_CODE_HASH: { 53643ca95b02SDimitry Andric if (Record.size() != 5) 53653ca95b02SDimitry Andric return error("Invalid hash length " + Twine(Record.size()).str()); 536624d58133SDimitry Andric if (!LastSeenModule) 53673ca95b02SDimitry Andric return error("Invalid hash that does not follow a module path"); 53683ca95b02SDimitry Andric int Pos = 0; 53693ca95b02SDimitry Andric for (auto &Val : Record) { 53703ca95b02SDimitry Andric assert(!(Val >> 32) && "Unexpected high bits set"); 537124d58133SDimitry Andric LastSeenModule->second.second[Pos++] = Val; 53723ca95b02SDimitry Andric } 537324d58133SDimitry Andric // Reset LastSeenModule to avoid overriding the hash unexpectedly. 537424d58133SDimitry Andric LastSeenModule = nullptr; 53753ca95b02SDimitry Andric break; 53763ca95b02SDimitry Andric } 53777d523365SDimitry Andric } 53787d523365SDimitry Andric } 53797d523365SDimitry Andric llvm_unreachable("Exit infinite loop"); 53807d523365SDimitry Andric } 53817d523365SDimitry Andric 5382f785676fSDimitry Andric namespace { 5383d88c1a5aSDimitry Andric 53843ca95b02SDimitry Andric // FIXME: This class is only here to support the transition to llvm::Error. It 53853ca95b02SDimitry Andric // will be removed once this transition is complete. Clients should prefer to 53863ca95b02SDimitry Andric // deal with the Error value directly, rather than converting to error_code. 538791bc56edSDimitry Andric class BitcodeErrorCategoryType : public std::error_category { 5388d88c1a5aSDimitry Andric const char *name() const noexcept override { 5389f785676fSDimitry Andric return "llvm.bitcode"; 5390f785676fSDimitry Andric } 539191bc56edSDimitry Andric std::string message(int IE) const override { 539239d628a0SDimitry Andric BitcodeError E = static_cast<BitcodeError>(IE); 5393f785676fSDimitry Andric switch (E) { 539439d628a0SDimitry Andric case BitcodeError::CorruptedBitcode: 539539d628a0SDimitry Andric return "Corrupted bitcode"; 5396f785676fSDimitry Andric } 5397f785676fSDimitry Andric llvm_unreachable("Unknown error type!"); 5398f785676fSDimitry Andric } 5399f785676fSDimitry Andric }; 5400d88c1a5aSDimitry Andric 54013ca95b02SDimitry Andric } // end anonymous namespace 5402f785676fSDimitry Andric 540339d628a0SDimitry Andric static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory; 540439d628a0SDimitry Andric 540539d628a0SDimitry Andric const std::error_category &llvm::BitcodeErrorCategory() { 540639d628a0SDimitry Andric return *ErrorCategory; 5407dff0c46cSDimitry Andric } 5408f22ef01cSRoman Divacky 5409a580b014SDimitry Andric static Expected<StringRef> readBlobInRecord(BitstreamCursor &Stream, 5410a580b014SDimitry Andric unsigned Block, unsigned RecordID) { 5411a580b014SDimitry Andric if (Stream.EnterSubBlock(Block)) 54126bc11b14SDimitry Andric return error("Invalid record"); 54136bc11b14SDimitry Andric 54146bc11b14SDimitry Andric StringRef Strtab; 54156bc11b14SDimitry Andric while (1) { 54166bc11b14SDimitry Andric BitstreamEntry Entry = Stream.advance(); 54176bc11b14SDimitry Andric switch (Entry.Kind) { 54186bc11b14SDimitry Andric case BitstreamEntry::EndBlock: 54196bc11b14SDimitry Andric return Strtab; 54206bc11b14SDimitry Andric 54216bc11b14SDimitry Andric case BitstreamEntry::Error: 54226bc11b14SDimitry Andric return error("Malformed block"); 54236bc11b14SDimitry Andric 54246bc11b14SDimitry Andric case BitstreamEntry::SubBlock: 54256bc11b14SDimitry Andric if (Stream.SkipBlock()) 54266bc11b14SDimitry Andric return error("Malformed block"); 54276bc11b14SDimitry Andric break; 54286bc11b14SDimitry Andric 54296bc11b14SDimitry Andric case BitstreamEntry::Record: 54306bc11b14SDimitry Andric StringRef Blob; 54316bc11b14SDimitry Andric SmallVector<uint64_t, 1> Record; 5432a580b014SDimitry Andric if (Stream.readRecord(Entry.ID, Record, &Blob) == RecordID) 54336bc11b14SDimitry Andric Strtab = Blob; 54346bc11b14SDimitry Andric break; 54356bc11b14SDimitry Andric } 54366bc11b14SDimitry Andric } 54376bc11b14SDimitry Andric } 54386bc11b14SDimitry Andric 5439f22ef01cSRoman Divacky //===----------------------------------------------------------------------===// 5440f22ef01cSRoman Divacky // External interface 5441f22ef01cSRoman Divacky //===----------------------------------------------------------------------===// 5442f22ef01cSRoman Divacky 5443d88c1a5aSDimitry Andric Expected<std::vector<BitcodeModule>> 5444d88c1a5aSDimitry Andric llvm::getBitcodeModuleList(MemoryBufferRef Buffer) { 5445db17bf38SDimitry Andric auto FOrErr = getBitcodeFileContents(Buffer); 5446db17bf38SDimitry Andric if (!FOrErr) 5447db17bf38SDimitry Andric return FOrErr.takeError(); 5448db17bf38SDimitry Andric return std::move(FOrErr->Mods); 5449db17bf38SDimitry Andric } 5450db17bf38SDimitry Andric 5451db17bf38SDimitry Andric Expected<BitcodeFileContents> 5452db17bf38SDimitry Andric llvm::getBitcodeFileContents(MemoryBufferRef Buffer) { 5453d88c1a5aSDimitry Andric Expected<BitstreamCursor> StreamOrErr = initStream(Buffer); 5454d88c1a5aSDimitry Andric if (!StreamOrErr) 5455d88c1a5aSDimitry Andric return StreamOrErr.takeError(); 5456d88c1a5aSDimitry Andric BitstreamCursor &Stream = *StreamOrErr; 54578f0fd8f6SDimitry Andric 5458db17bf38SDimitry Andric BitcodeFileContents F; 5459d88c1a5aSDimitry Andric while (true) { 5460d88c1a5aSDimitry Andric uint64_t BCBegin = Stream.getCurrentByteNo(); 54618f0fd8f6SDimitry Andric 5462d88c1a5aSDimitry Andric // We may be consuming bitcode from a client that leaves garbage at the end 5463d88c1a5aSDimitry Andric // of the bitcode stream (e.g. Apple's ar tool). If we are close enough to 5464d88c1a5aSDimitry Andric // the end that there cannot possibly be another module, stop looking. 5465d88c1a5aSDimitry Andric if (BCBegin + 8 >= Stream.getBitcodeBytes().size()) 5466db17bf38SDimitry Andric return F; 54678f0fd8f6SDimitry Andric 5468d88c1a5aSDimitry Andric BitstreamEntry Entry = Stream.advance(); 5469d88c1a5aSDimitry Andric switch (Entry.Kind) { 5470d88c1a5aSDimitry Andric case BitstreamEntry::EndBlock: 5471d88c1a5aSDimitry Andric case BitstreamEntry::Error: 5472d88c1a5aSDimitry Andric return error("Malformed block"); 5473d88c1a5aSDimitry Andric 5474d88c1a5aSDimitry Andric case BitstreamEntry::SubBlock: { 5475d88c1a5aSDimitry Andric uint64_t IdentificationBit = -1ull; 5476d88c1a5aSDimitry Andric if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) { 5477d88c1a5aSDimitry Andric IdentificationBit = Stream.GetCurrentBitNo() - BCBegin * 8; 5478d88c1a5aSDimitry Andric if (Stream.SkipBlock()) 5479d88c1a5aSDimitry Andric return error("Malformed block"); 5480d88c1a5aSDimitry Andric 5481d88c1a5aSDimitry Andric Entry = Stream.advance(); 5482d88c1a5aSDimitry Andric if (Entry.Kind != BitstreamEntry::SubBlock || 5483d88c1a5aSDimitry Andric Entry.ID != bitc::MODULE_BLOCK_ID) 5484d88c1a5aSDimitry Andric return error("Malformed block"); 54858f0fd8f6SDimitry Andric } 5486d88c1a5aSDimitry Andric 5487d88c1a5aSDimitry Andric if (Entry.ID == bitc::MODULE_BLOCK_ID) { 5488d88c1a5aSDimitry Andric uint64_t ModuleBit = Stream.GetCurrentBitNo() - BCBegin * 8; 5489d88c1a5aSDimitry Andric if (Stream.SkipBlock()) 5490d88c1a5aSDimitry Andric return error("Malformed block"); 5491d88c1a5aSDimitry Andric 5492db17bf38SDimitry Andric F.Mods.push_back({Stream.getBitcodeBytes().slice( 5493d88c1a5aSDimitry Andric BCBegin, Stream.getCurrentByteNo() - BCBegin), 5494d88c1a5aSDimitry Andric Buffer.getBufferIdentifier(), IdentificationBit, 5495d88c1a5aSDimitry Andric ModuleBit}); 5496d88c1a5aSDimitry Andric continue; 5497d88c1a5aSDimitry Andric } 5498d88c1a5aSDimitry Andric 54996bc11b14SDimitry Andric if (Entry.ID == bitc::STRTAB_BLOCK_ID) { 5500a580b014SDimitry Andric Expected<StringRef> Strtab = 5501a580b014SDimitry Andric readBlobInRecord(Stream, bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB); 55026bc11b14SDimitry Andric if (!Strtab) 55036bc11b14SDimitry Andric return Strtab.takeError(); 55046bc11b14SDimitry Andric // This string table is used by every preceding bitcode module that does 55056bc11b14SDimitry Andric // not have its own string table. A bitcode file may have multiple 55066bc11b14SDimitry Andric // string tables if it was created by binary concatenation, for example 55076bc11b14SDimitry Andric // with "llvm-cat -b". 5508db17bf38SDimitry Andric for (auto I = F.Mods.rbegin(), E = F.Mods.rend(); I != E; ++I) { 55096bc11b14SDimitry Andric if (!I->Strtab.empty()) 55106bc11b14SDimitry Andric break; 55116bc11b14SDimitry Andric I->Strtab = *Strtab; 55126bc11b14SDimitry Andric } 5513a580b014SDimitry Andric // Similarly, the string table is used by every preceding symbol table; 5514a580b014SDimitry Andric // normally there will be just one unless the bitcode file was created 5515a580b014SDimitry Andric // by binary concatenation. 5516a580b014SDimitry Andric if (!F.Symtab.empty() && F.StrtabForSymtab.empty()) 5517a580b014SDimitry Andric F.StrtabForSymtab = *Strtab; 5518a580b014SDimitry Andric continue; 5519a580b014SDimitry Andric } 5520a580b014SDimitry Andric 5521a580b014SDimitry Andric if (Entry.ID == bitc::SYMTAB_BLOCK_ID) { 5522a580b014SDimitry Andric Expected<StringRef> SymtabOrErr = 5523a580b014SDimitry Andric readBlobInRecord(Stream, bitc::SYMTAB_BLOCK_ID, bitc::SYMTAB_BLOB); 5524a580b014SDimitry Andric if (!SymtabOrErr) 5525a580b014SDimitry Andric return SymtabOrErr.takeError(); 5526a580b014SDimitry Andric 5527a580b014SDimitry Andric // We can expect the bitcode file to have multiple symbol tables if it 5528a580b014SDimitry Andric // was created by binary concatenation. In that case we silently 5529a580b014SDimitry Andric // ignore any subsequent symbol tables, which is fine because this is a 5530a580b014SDimitry Andric // low level function. The client is expected to notice that the number 5531a580b014SDimitry Andric // of modules in the symbol table does not match the number of modules 5532a580b014SDimitry Andric // in the input file and regenerate the symbol table. 5533a580b014SDimitry Andric if (F.Symtab.empty()) 5534a580b014SDimitry Andric F.Symtab = *SymtabOrErr; 55356bc11b14SDimitry Andric continue; 55366bc11b14SDimitry Andric } 55376bc11b14SDimitry Andric 5538d88c1a5aSDimitry Andric if (Stream.SkipBlock()) 5539d88c1a5aSDimitry Andric return error("Malformed block"); 5540d88c1a5aSDimitry Andric continue; 5541d88c1a5aSDimitry Andric } 5542d88c1a5aSDimitry Andric case BitstreamEntry::Record: 5543d88c1a5aSDimitry Andric Stream.skipRecord(Entry.ID); 5544d88c1a5aSDimitry Andric continue; 5545d88c1a5aSDimitry Andric } 5546d88c1a5aSDimitry Andric } 55478f0fd8f6SDimitry Andric } 55488f0fd8f6SDimitry Andric 554939d628a0SDimitry Andric /// \brief Get a lazy one-at-time loading module from bitcode. 5550f22ef01cSRoman Divacky /// 555139d628a0SDimitry Andric /// This isn't always used in a lazy context. In particular, it's also used by 5552d88c1a5aSDimitry Andric /// \a parseModule(). If this is truly lazy, then we need to eagerly pull 555339d628a0SDimitry Andric /// in forward-referenced functions from block address references. 555439d628a0SDimitry Andric /// 55558f0fd8f6SDimitry Andric /// \param[in] MaterializeAll Set to \c true if we should materialize 55568f0fd8f6SDimitry Andric /// everything. 5557d88c1a5aSDimitry Andric Expected<std::unique_ptr<Module>> 5558d88c1a5aSDimitry Andric BitcodeModule::getModuleImpl(LLVMContext &Context, bool MaterializeAll, 5559d88c1a5aSDimitry Andric bool ShouldLazyLoadMetadata, bool IsImporting) { 5560d88c1a5aSDimitry Andric BitstreamCursor Stream(Buffer); 556139d628a0SDimitry Andric 5562d88c1a5aSDimitry Andric std::string ProducerIdentification; 5563d88c1a5aSDimitry Andric if (IdentificationBit != -1ull) { 5564d88c1a5aSDimitry Andric Stream.JumpToBit(IdentificationBit); 5565d88c1a5aSDimitry Andric Expected<std::string> ProducerIdentificationOrErr = 5566d88c1a5aSDimitry Andric readIdentificationBlock(Stream); 5567d88c1a5aSDimitry Andric if (!ProducerIdentificationOrErr) 5568d88c1a5aSDimitry Andric return ProducerIdentificationOrErr.takeError(); 556939d628a0SDimitry Andric 5570d88c1a5aSDimitry Andric ProducerIdentification = *ProducerIdentificationOrErr; 5571dff0c46cSDimitry Andric } 5572dff0c46cSDimitry Andric 5573d88c1a5aSDimitry Andric Stream.JumpToBit(ModuleBit); 55746bc11b14SDimitry Andric auto *R = new BitcodeReader(std::move(Stream), Strtab, ProducerIdentification, 55756bc11b14SDimitry Andric Context); 5576d88c1a5aSDimitry Andric 5577d88c1a5aSDimitry Andric std::unique_ptr<Module> M = 5578d88c1a5aSDimitry Andric llvm::make_unique<Module>(ModuleIdentifier, Context); 5579d88c1a5aSDimitry Andric M->setMaterializer(R); 5580d88c1a5aSDimitry Andric 5581d88c1a5aSDimitry Andric // Delay parsing Metadata if ShouldLazyLoadMetadata is true. 5582d88c1a5aSDimitry Andric if (Error Err = 5583d88c1a5aSDimitry Andric R->parseBitcodeInto(M.get(), ShouldLazyLoadMetadata, IsImporting)) 5584d88c1a5aSDimitry Andric return std::move(Err); 5585d88c1a5aSDimitry Andric 5586d88c1a5aSDimitry Andric if (MaterializeAll) { 5587d88c1a5aSDimitry Andric // Read in the entire module, and destroy the BitcodeReader. 5588d88c1a5aSDimitry Andric if (Error Err = M->materializeAll()) 5589d88c1a5aSDimitry Andric return std::move(Err); 5590d88c1a5aSDimitry Andric } else { 5591d88c1a5aSDimitry Andric // Resolve forward references from blockaddresses. 5592d88c1a5aSDimitry Andric if (Error Err = R->materializeForwardReferencedFunctions()) 5593d88c1a5aSDimitry Andric return std::move(Err); 5594d88c1a5aSDimitry Andric } 5595d88c1a5aSDimitry Andric return std::move(M); 5596f22ef01cSRoman Divacky } 5597f22ef01cSRoman Divacky 5598d88c1a5aSDimitry Andric Expected<std::unique_ptr<Module>> 5599d88c1a5aSDimitry Andric BitcodeModule::getLazyModule(LLVMContext &Context, bool ShouldLazyLoadMetadata, 5600d88c1a5aSDimitry Andric bool IsImporting) { 5601d88c1a5aSDimitry Andric return getModuleImpl(Context, false, ShouldLazyLoadMetadata, IsImporting); 56027d523365SDimitry Andric } 56037d523365SDimitry Andric 5604f37b6182SDimitry Andric // Parse the specified bitcode buffer and merge the index into CombinedIndex. 560524d58133SDimitry Andric // We don't use ModuleIdentifier here because the client may need to control the 560624d58133SDimitry Andric // module path used in the combined summary (e.g. when reading summaries for 560724d58133SDimitry Andric // regular LTO modules). 5608f37b6182SDimitry Andric Error BitcodeModule::readSummary(ModuleSummaryIndex &CombinedIndex, 560924d58133SDimitry Andric StringRef ModulePath, uint64_t ModuleId) { 5610f37b6182SDimitry Andric BitstreamCursor Stream(Buffer); 5611f37b6182SDimitry Andric Stream.JumpToBit(ModuleBit); 5612f37b6182SDimitry Andric 5613f37b6182SDimitry Andric ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, CombinedIndex, 561424d58133SDimitry Andric ModulePath, ModuleId); 5615f37b6182SDimitry Andric return R.parseModule(); 5616f37b6182SDimitry Andric } 5617f37b6182SDimitry Andric 56187d523365SDimitry Andric // Parse the specified bitcode buffer, returning the function info index. 5619d88c1a5aSDimitry Andric Expected<std::unique_ptr<ModuleSummaryIndex>> BitcodeModule::getSummary() { 5620d88c1a5aSDimitry Andric BitstreamCursor Stream(Buffer); 5621d88c1a5aSDimitry Andric Stream.JumpToBit(ModuleBit); 56227d523365SDimitry Andric 56233ca95b02SDimitry Andric auto Index = llvm::make_unique<ModuleSummaryIndex>(); 5624f37b6182SDimitry Andric ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, *Index, 5625f37b6182SDimitry Andric ModuleIdentifier, 0); 56267d523365SDimitry Andric 5627f37b6182SDimitry Andric if (Error Err = R.parseModule()) 5628d88c1a5aSDimitry Andric return std::move(Err); 56297d523365SDimitry Andric 56307d523365SDimitry Andric return std::move(Index); 56317d523365SDimitry Andric } 56327d523365SDimitry Andric 56333ca95b02SDimitry Andric // Check if the given bitcode buffer contains a global value summary block. 563424d58133SDimitry Andric Expected<BitcodeLTOInfo> BitcodeModule::getLTOInfo() { 5635d88c1a5aSDimitry Andric BitstreamCursor Stream(Buffer); 5636d88c1a5aSDimitry Andric Stream.JumpToBit(ModuleBit); 56377d523365SDimitry Andric 5638d88c1a5aSDimitry Andric if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID)) 5639d88c1a5aSDimitry Andric return error("Invalid record"); 5640d88c1a5aSDimitry Andric 5641d88c1a5aSDimitry Andric while (true) { 5642d88c1a5aSDimitry Andric BitstreamEntry Entry = Stream.advance(); 5643d88c1a5aSDimitry Andric 5644d88c1a5aSDimitry Andric switch (Entry.Kind) { 5645d88c1a5aSDimitry Andric case BitstreamEntry::Error: 5646d88c1a5aSDimitry Andric return error("Malformed block"); 5647d88c1a5aSDimitry Andric case BitstreamEntry::EndBlock: 564824d58133SDimitry Andric return BitcodeLTOInfo{/*IsThinLTO=*/false, /*HasSummary=*/false}; 56497d523365SDimitry Andric 5650d88c1a5aSDimitry Andric case BitstreamEntry::SubBlock: 5651d88c1a5aSDimitry Andric if (Entry.ID == bitc::GLOBALVAL_SUMMARY_BLOCK_ID) 565224d58133SDimitry Andric return BitcodeLTOInfo{/*IsThinLTO=*/true, /*HasSummary=*/true}; 565324d58133SDimitry Andric 565424d58133SDimitry Andric if (Entry.ID == bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID) 565524d58133SDimitry Andric return BitcodeLTOInfo{/*IsThinLTO=*/false, /*HasSummary=*/true}; 56567d523365SDimitry Andric 5657d88c1a5aSDimitry Andric // Ignore other sub-blocks. 5658d88c1a5aSDimitry Andric if (Stream.SkipBlock()) 5659d88c1a5aSDimitry Andric return error("Malformed block"); 5660d88c1a5aSDimitry Andric continue; 5661d88c1a5aSDimitry Andric 5662d88c1a5aSDimitry Andric case BitstreamEntry::Record: 5663d88c1a5aSDimitry Andric Stream.skipRecord(Entry.ID); 5664d88c1a5aSDimitry Andric continue; 5665d88c1a5aSDimitry Andric } 5666d88c1a5aSDimitry Andric } 5667d88c1a5aSDimitry Andric } 5668d88c1a5aSDimitry Andric 5669d88c1a5aSDimitry Andric static Expected<BitcodeModule> getSingleModule(MemoryBufferRef Buffer) { 5670d88c1a5aSDimitry Andric Expected<std::vector<BitcodeModule>> MsOrErr = getBitcodeModuleList(Buffer); 5671d88c1a5aSDimitry Andric if (!MsOrErr) 5672d88c1a5aSDimitry Andric return MsOrErr.takeError(); 5673d88c1a5aSDimitry Andric 5674d88c1a5aSDimitry Andric if (MsOrErr->size() != 1) 5675d88c1a5aSDimitry Andric return error("Expected a single module"); 5676d88c1a5aSDimitry Andric 5677d88c1a5aSDimitry Andric return (*MsOrErr)[0]; 5678d88c1a5aSDimitry Andric } 5679d88c1a5aSDimitry Andric 5680d88c1a5aSDimitry Andric Expected<std::unique_ptr<Module>> 5681d88c1a5aSDimitry Andric llvm::getLazyBitcodeModule(MemoryBufferRef Buffer, LLVMContext &Context, 5682d88c1a5aSDimitry Andric bool ShouldLazyLoadMetadata, bool IsImporting) { 5683d88c1a5aSDimitry Andric Expected<BitcodeModule> BM = getSingleModule(Buffer); 5684d88c1a5aSDimitry Andric if (!BM) 5685d88c1a5aSDimitry Andric return BM.takeError(); 5686d88c1a5aSDimitry Andric 5687d88c1a5aSDimitry Andric return BM->getLazyModule(Context, ShouldLazyLoadMetadata, IsImporting); 5688d88c1a5aSDimitry Andric } 5689d88c1a5aSDimitry Andric 5690d88c1a5aSDimitry Andric Expected<std::unique_ptr<Module>> llvm::getOwningLazyBitcodeModule( 5691d88c1a5aSDimitry Andric std::unique_ptr<MemoryBuffer> &&Buffer, LLVMContext &Context, 5692d88c1a5aSDimitry Andric bool ShouldLazyLoadMetadata, bool IsImporting) { 5693d88c1a5aSDimitry Andric auto MOrErr = getLazyBitcodeModule(*Buffer, Context, ShouldLazyLoadMetadata, 5694d88c1a5aSDimitry Andric IsImporting); 5695d88c1a5aSDimitry Andric if (MOrErr) 5696d88c1a5aSDimitry Andric (*MOrErr)->setOwnedMemoryBuffer(std::move(Buffer)); 5697d88c1a5aSDimitry Andric return MOrErr; 5698d88c1a5aSDimitry Andric } 5699d88c1a5aSDimitry Andric 5700d88c1a5aSDimitry Andric Expected<std::unique_ptr<Module>> 5701d88c1a5aSDimitry Andric BitcodeModule::parseModule(LLVMContext &Context) { 5702d88c1a5aSDimitry Andric return getModuleImpl(Context, true, false, false); 5703d88c1a5aSDimitry Andric // TODO: Restore the use-lists to the in-memory state when the bitcode was 5704d88c1a5aSDimitry Andric // written. We must defer until the Module has been fully materialized. 5705d88c1a5aSDimitry Andric } 5706d88c1a5aSDimitry Andric 5707d88c1a5aSDimitry Andric Expected<std::unique_ptr<Module>> llvm::parseBitcodeFile(MemoryBufferRef Buffer, 5708d88c1a5aSDimitry Andric LLVMContext &Context) { 5709d88c1a5aSDimitry Andric Expected<BitcodeModule> BM = getSingleModule(Buffer); 5710d88c1a5aSDimitry Andric if (!BM) 5711d88c1a5aSDimitry Andric return BM.takeError(); 5712d88c1a5aSDimitry Andric 5713d88c1a5aSDimitry Andric return BM->parseModule(Context); 5714d88c1a5aSDimitry Andric } 5715d88c1a5aSDimitry Andric 5716d88c1a5aSDimitry Andric Expected<std::string> llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer) { 5717d88c1a5aSDimitry Andric Expected<BitstreamCursor> StreamOrErr = initStream(Buffer); 5718d88c1a5aSDimitry Andric if (!StreamOrErr) 5719d88c1a5aSDimitry Andric return StreamOrErr.takeError(); 5720d88c1a5aSDimitry Andric 5721d88c1a5aSDimitry Andric return readTriple(*StreamOrErr); 5722d88c1a5aSDimitry Andric } 5723d88c1a5aSDimitry Andric 5724d88c1a5aSDimitry Andric Expected<bool> llvm::isBitcodeContainingObjCCategory(MemoryBufferRef Buffer) { 5725d88c1a5aSDimitry Andric Expected<BitstreamCursor> StreamOrErr = initStream(Buffer); 5726d88c1a5aSDimitry Andric if (!StreamOrErr) 5727d88c1a5aSDimitry Andric return StreamOrErr.takeError(); 5728d88c1a5aSDimitry Andric 5729d88c1a5aSDimitry Andric return hasObjCCategory(*StreamOrErr); 5730d88c1a5aSDimitry Andric } 5731d88c1a5aSDimitry Andric 5732d88c1a5aSDimitry Andric Expected<std::string> llvm::getBitcodeProducerString(MemoryBufferRef Buffer) { 5733d88c1a5aSDimitry Andric Expected<BitstreamCursor> StreamOrErr = initStream(Buffer); 5734d88c1a5aSDimitry Andric if (!StreamOrErr) 5735d88c1a5aSDimitry Andric return StreamOrErr.takeError(); 5736d88c1a5aSDimitry Andric 5737d88c1a5aSDimitry Andric return readIdentificationCode(*StreamOrErr); 5738d88c1a5aSDimitry Andric } 5739d88c1a5aSDimitry Andric 5740f37b6182SDimitry Andric Error llvm::readModuleSummaryIndex(MemoryBufferRef Buffer, 5741f37b6182SDimitry Andric ModuleSummaryIndex &CombinedIndex, 574224d58133SDimitry Andric uint64_t ModuleId) { 5743f37b6182SDimitry Andric Expected<BitcodeModule> BM = getSingleModule(Buffer); 5744f37b6182SDimitry Andric if (!BM) 5745f37b6182SDimitry Andric return BM.takeError(); 5746f37b6182SDimitry Andric 574724d58133SDimitry Andric return BM->readSummary(CombinedIndex, BM->getModuleIdentifier(), ModuleId); 5748f37b6182SDimitry Andric } 5749f37b6182SDimitry Andric 5750d88c1a5aSDimitry Andric Expected<std::unique_ptr<ModuleSummaryIndex>> 5751d88c1a5aSDimitry Andric llvm::getModuleSummaryIndex(MemoryBufferRef Buffer) { 5752d88c1a5aSDimitry Andric Expected<BitcodeModule> BM = getSingleModule(Buffer); 5753d88c1a5aSDimitry Andric if (!BM) 5754d88c1a5aSDimitry Andric return BM.takeError(); 5755d88c1a5aSDimitry Andric 5756d88c1a5aSDimitry Andric return BM->getSummary(); 5757d88c1a5aSDimitry Andric } 5758d88c1a5aSDimitry Andric 575924d58133SDimitry Andric Expected<BitcodeLTOInfo> llvm::getBitcodeLTOInfo(MemoryBufferRef Buffer) { 5760d88c1a5aSDimitry Andric Expected<BitcodeModule> BM = getSingleModule(Buffer); 5761d88c1a5aSDimitry Andric if (!BM) 5762d88c1a5aSDimitry Andric return BM.takeError(); 5763d88c1a5aSDimitry Andric 576424d58133SDimitry Andric return BM->getLTOInfo(); 57657d523365SDimitry Andric } 5766f37b6182SDimitry Andric 5767f37b6182SDimitry Andric Expected<std::unique_ptr<ModuleSummaryIndex>> 57685517e702SDimitry Andric llvm::getModuleSummaryIndexForFile(StringRef Path, 57695517e702SDimitry Andric bool IgnoreEmptyThinLTOIndexFile) { 5770f37b6182SDimitry Andric ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr = 5771f37b6182SDimitry Andric MemoryBuffer::getFileOrSTDIN(Path); 5772f37b6182SDimitry Andric if (!FileOrErr) 5773f37b6182SDimitry Andric return errorCodeToError(FileOrErr.getError()); 5774f37b6182SDimitry Andric if (IgnoreEmptyThinLTOIndexFile && !(*FileOrErr)->getBufferSize()) 5775f37b6182SDimitry Andric return nullptr; 5776f37b6182SDimitry Andric return getModuleSummaryIndex(**FileOrErr); 5777f37b6182SDimitry Andric } 5778