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 #include "llvm/ADT/APFloat.h" 14d88c1a5aSDimitry Andric #include "llvm/ADT/APInt.h" 15d88c1a5aSDimitry Andric #include "llvm/ADT/ArrayRef.h" 16d88c1a5aSDimitry Andric #include "llvm/ADT/DenseMap.h" 172cab237bSDimitry Andric #include "llvm/ADT/Optional.h" 18ff0cc061SDimitry Andric #include "llvm/ADT/STLExtras.h" 19f22ef01cSRoman Divacky #include "llvm/ADT/SmallString.h" 20f22ef01cSRoman Divacky #include "llvm/ADT/SmallVector.h" 21d88c1a5aSDimitry Andric #include "llvm/ADT/StringRef.h" 22ff0cc061SDimitry Andric #include "llvm/ADT/Triple.h" 23d88c1a5aSDimitry Andric #include "llvm/ADT/Twine.h" 24ff0cc061SDimitry Andric #include "llvm/Bitcode/BitstreamReader.h" 25f785676fSDimitry Andric #include "llvm/Bitcode/LLVMBitCodes.h" 26d88c1a5aSDimitry Andric #include "llvm/IR/Argument.h" 27d88c1a5aSDimitry Andric #include "llvm/IR/Attributes.h" 2891bc56edSDimitry Andric #include "llvm/IR/AutoUpgrade.h" 29d88c1a5aSDimitry Andric #include "llvm/IR/BasicBlock.h" 303ca95b02SDimitry Andric #include "llvm/IR/CallSite.h" 31db17bf38SDimitry Andric #include "llvm/IR/CallingConv.h" 32d88c1a5aSDimitry Andric #include "llvm/IR/Comdat.h" 33d88c1a5aSDimitry Andric #include "llvm/IR/Constant.h" 34139f7f9bSDimitry Andric #include "llvm/IR/Constants.h" 352cab237bSDimitry Andric #include "llvm/IR/DataLayout.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/Function.h" 41db17bf38SDimitry Andric #include "llvm/IR/GVMaterializer.h" 42d88c1a5aSDimitry Andric #include "llvm/IR/GlobalAlias.h" 43d88c1a5aSDimitry Andric #include "llvm/IR/GlobalIFunc.h" 44d88c1a5aSDimitry Andric #include "llvm/IR/GlobalIndirectSymbol.h" 45d88c1a5aSDimitry Andric #include "llvm/IR/GlobalObject.h" 46d88c1a5aSDimitry Andric #include "llvm/IR/GlobalValue.h" 47d88c1a5aSDimitry Andric #include "llvm/IR/GlobalVariable.h" 48139f7f9bSDimitry Andric #include "llvm/IR/InlineAsm.h" 49d88c1a5aSDimitry Andric #include "llvm/IR/InstIterator.h" 50d88c1a5aSDimitry Andric #include "llvm/IR/InstrTypes.h" 51d88c1a5aSDimitry Andric #include "llvm/IR/Instruction.h" 52d88c1a5aSDimitry Andric #include "llvm/IR/Instructions.h" 53d88c1a5aSDimitry Andric #include "llvm/IR/Intrinsics.h" 54f785676fSDimitry Andric #include "llvm/IR/LLVMContext.h" 552cab237bSDimitry Andric #include "llvm/IR/Metadata.h" 56139f7f9bSDimitry Andric #include "llvm/IR/Module.h" 573ca95b02SDimitry Andric #include "llvm/IR/ModuleSummaryIndex.h" 58139f7f9bSDimitry Andric #include "llvm/IR/Operator.h" 59d88c1a5aSDimitry Andric #include "llvm/IR/Type.h" 602cab237bSDimitry Andric #include "llvm/IR/Value.h" 61d88c1a5aSDimitry Andric #include "llvm/IR/Verifier.h" 62d88c1a5aSDimitry Andric #include "llvm/Support/AtomicOrdering.h" 63d88c1a5aSDimitry Andric #include "llvm/Support/Casting.h" 643ca95b02SDimitry Andric #include "llvm/Support/CommandLine.h" 65d88c1a5aSDimitry Andric #include "llvm/Support/Compiler.h" 663ca95b02SDimitry Andric #include "llvm/Support/Debug.h" 67d88c1a5aSDimitry Andric #include "llvm/Support/Error.h" 68d88c1a5aSDimitry Andric #include "llvm/Support/ErrorHandling.h" 692cab237bSDimitry Andric #include "llvm/Support/ErrorOr.h" 7039d628a0SDimitry Andric #include "llvm/Support/ManagedStatic.h" 712cab237bSDimitry Andric #include "llvm/Support/MathExtras.h" 72f22ef01cSRoman Divacky #include "llvm/Support/MemoryBuffer.h" 73f785676fSDimitry Andric #include "llvm/Support/raw_ostream.h" 74d88c1a5aSDimitry Andric #include <algorithm> 75d88c1a5aSDimitry Andric #include <cassert> 76d88c1a5aSDimitry Andric #include <cstddef> 77d88c1a5aSDimitry Andric #include <cstdint> 78ff0cc061SDimitry Andric #include <deque> 79d88c1a5aSDimitry Andric #include <map> 80d88c1a5aSDimitry Andric #include <memory> 812cab237bSDimitry Andric #include <set> 82d88c1a5aSDimitry Andric #include <string> 83d88c1a5aSDimitry Andric #include <system_error> 84d88c1a5aSDimitry Andric #include <tuple> 853ca95b02SDimitry Andric #include <utility> 86d88c1a5aSDimitry Andric #include <vector> 873ca95b02SDimitry Andric 88f22ef01cSRoman Divacky using namespace llvm; 89f22ef01cSRoman Divacky 903ca95b02SDimitry Andric static cl::opt<bool> PrintSummaryGUIDs( 913ca95b02SDimitry Andric "print-summary-global-ids", cl::init(false), cl::Hidden, 923ca95b02SDimitry Andric cl::desc( 933ca95b02SDimitry Andric "Print the global id for each value when reading the module summary")); 943ca95b02SDimitry Andric 95ff0cc061SDimitry Andric namespace { 96d88c1a5aSDimitry Andric 977ae0e2c9SDimitry Andric enum { 987ae0e2c9SDimitry Andric SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex 997ae0e2c9SDimitry Andric }; 1007ae0e2c9SDimitry Andric 1012cab237bSDimitry Andric } // end anonymous namespace 1022cab237bSDimitry Andric 1032cab237bSDimitry Andric static Error error(const Twine &Message) { 104d88c1a5aSDimitry Andric return make_error<StringError>( 105d88c1a5aSDimitry Andric Message, make_error_code(BitcodeError::CorruptedBitcode)); 106ff0cc061SDimitry Andric } 107ff0cc061SDimitry Andric 108d88c1a5aSDimitry Andric /// Helper to read the header common to all bitcode files. 1092cab237bSDimitry Andric static bool hasValidBitcodeHeader(BitstreamCursor &Stream) { 110d88c1a5aSDimitry Andric // Sniff for the signature. 111d88c1a5aSDimitry Andric if (!Stream.canSkipToPos(4) || 112d88c1a5aSDimitry Andric Stream.Read(8) != 'B' || 113d88c1a5aSDimitry Andric Stream.Read(8) != 'C' || 114d88c1a5aSDimitry Andric Stream.Read(4) != 0x0 || 115d88c1a5aSDimitry Andric Stream.Read(4) != 0xC || 116d88c1a5aSDimitry Andric Stream.Read(4) != 0xE || 117d88c1a5aSDimitry Andric Stream.Read(4) != 0xD) 118d88c1a5aSDimitry Andric return false; 119d88c1a5aSDimitry Andric return true; 120ff0cc061SDimitry Andric } 121ff0cc061SDimitry Andric 1222cab237bSDimitry Andric static Expected<BitstreamCursor> initStream(MemoryBufferRef Buffer) { 123d88c1a5aSDimitry Andric const unsigned char *BufPtr = (const unsigned char *)Buffer.getBufferStart(); 124d88c1a5aSDimitry Andric const unsigned char *BufEnd = BufPtr + Buffer.getBufferSize(); 125d88c1a5aSDimitry Andric 126d88c1a5aSDimitry Andric if (Buffer.getBufferSize() & 3) 127d88c1a5aSDimitry Andric return error("Invalid bitcode signature"); 128d88c1a5aSDimitry Andric 129d88c1a5aSDimitry Andric // If we have a wrapper header, parse it and ignore the non-bc file contents. 130d88c1a5aSDimitry Andric // The magic number is 0x0B17C0DE stored in little endian. 131d88c1a5aSDimitry Andric if (isBitcodeWrapper(BufPtr, BufEnd)) 132d88c1a5aSDimitry Andric if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true)) 133d88c1a5aSDimitry Andric return error("Invalid bitcode wrapper header"); 134d88c1a5aSDimitry Andric 135d88c1a5aSDimitry Andric BitstreamCursor Stream(ArrayRef<uint8_t>(BufPtr, BufEnd)); 136d88c1a5aSDimitry Andric if (!hasValidBitcodeHeader(Stream)) 137d88c1a5aSDimitry Andric return error("Invalid bitcode signature"); 138d88c1a5aSDimitry Andric 139d88c1a5aSDimitry Andric return std::move(Stream); 140ff0cc061SDimitry Andric } 141ff0cc061SDimitry Andric 142d88c1a5aSDimitry Andric /// Convert a string from a record into an std::string, return true on failure. 143d88c1a5aSDimitry Andric template <typename StrTy> 144d88c1a5aSDimitry Andric static bool convertToString(ArrayRef<uint64_t> Record, unsigned Idx, 145d88c1a5aSDimitry Andric StrTy &Result) { 146d88c1a5aSDimitry Andric if (Idx > Record.size()) 147d88c1a5aSDimitry Andric return true; 148d88c1a5aSDimitry Andric 149d88c1a5aSDimitry Andric for (unsigned i = Idx, e = Record.size(); i != e; ++i) 150d88c1a5aSDimitry Andric Result += (char)Record[i]; 151d88c1a5aSDimitry Andric return false; 152ff0cc061SDimitry Andric } 153ff0cc061SDimitry Andric 154d88c1a5aSDimitry Andric // Strip all the TBAA attachment for the module. 1552cab237bSDimitry Andric static void stripTBAA(Module *M) { 156d88c1a5aSDimitry Andric for (auto &F : *M) { 157d88c1a5aSDimitry Andric if (F.isMaterializable()) 158d88c1a5aSDimitry Andric continue; 159d88c1a5aSDimitry Andric for (auto &I : instructions(F)) 160d88c1a5aSDimitry Andric I.setMetadata(LLVMContext::MD_tbaa, nullptr); 161d88c1a5aSDimitry Andric } 162d88c1a5aSDimitry Andric } 163ff0cc061SDimitry Andric 164d88c1a5aSDimitry Andric /// Read the "IDENTIFICATION_BLOCK_ID" block, do some basic enforcement on the 165d88c1a5aSDimitry Andric /// "epoch" encoded in the bitcode, and return the producer name if any. 1662cab237bSDimitry Andric static Expected<std::string> readIdentificationBlock(BitstreamCursor &Stream) { 167d88c1a5aSDimitry Andric if (Stream.EnterSubBlock(bitc::IDENTIFICATION_BLOCK_ID)) 168d88c1a5aSDimitry Andric return error("Invalid record"); 169ff0cc061SDimitry Andric 170d88c1a5aSDimitry Andric // Read all the records. 171d88c1a5aSDimitry Andric SmallVector<uint64_t, 64> Record; 172d88c1a5aSDimitry Andric 173d88c1a5aSDimitry Andric std::string ProducerIdentification; 174d88c1a5aSDimitry Andric 175d88c1a5aSDimitry Andric while (true) { 176d88c1a5aSDimitry Andric BitstreamEntry Entry = Stream.advance(); 177d88c1a5aSDimitry Andric 178d88c1a5aSDimitry Andric switch (Entry.Kind) { 179d88c1a5aSDimitry Andric default: 180d88c1a5aSDimitry Andric case BitstreamEntry::Error: 181d88c1a5aSDimitry Andric return error("Malformed block"); 182d88c1a5aSDimitry Andric case BitstreamEntry::EndBlock: 183d88c1a5aSDimitry Andric return ProducerIdentification; 184d88c1a5aSDimitry Andric case BitstreamEntry::Record: 185d88c1a5aSDimitry Andric // The interesting case. 186d88c1a5aSDimitry Andric break; 187d88c1a5aSDimitry Andric } 188d88c1a5aSDimitry Andric 189d88c1a5aSDimitry Andric // Read a record. 190d88c1a5aSDimitry Andric Record.clear(); 191d88c1a5aSDimitry Andric unsigned BitCode = Stream.readRecord(Entry.ID, Record); 192d88c1a5aSDimitry Andric switch (BitCode) { 193d88c1a5aSDimitry Andric default: // Default behavior: reject 194d88c1a5aSDimitry Andric return error("Invalid value"); 195d88c1a5aSDimitry Andric case bitc::IDENTIFICATION_CODE_STRING: // IDENTIFICATION: [strchr x N] 196d88c1a5aSDimitry Andric convertToString(Record, 0, ProducerIdentification); 197d88c1a5aSDimitry Andric break; 198d88c1a5aSDimitry Andric case bitc::IDENTIFICATION_CODE_EPOCH: { // EPOCH: [epoch#] 199d88c1a5aSDimitry Andric unsigned epoch = (unsigned)Record[0]; 200d88c1a5aSDimitry Andric if (epoch != bitc::BITCODE_CURRENT_EPOCH) { 201d88c1a5aSDimitry Andric return error( 202d88c1a5aSDimitry Andric Twine("Incompatible epoch: Bitcode '") + Twine(epoch) + 203d88c1a5aSDimitry Andric "' vs current: '" + Twine(bitc::BITCODE_CURRENT_EPOCH) + "'"); 204d88c1a5aSDimitry Andric } 205d88c1a5aSDimitry Andric } 206d88c1a5aSDimitry Andric } 207d88c1a5aSDimitry Andric } 208d88c1a5aSDimitry Andric } 209d88c1a5aSDimitry Andric 2102cab237bSDimitry Andric static Expected<std::string> readIdentificationCode(BitstreamCursor &Stream) { 211d88c1a5aSDimitry Andric // We expect a number of well-defined blocks, though we don't necessarily 212d88c1a5aSDimitry Andric // need to understand them all. 213d88c1a5aSDimitry Andric while (true) { 214d88c1a5aSDimitry Andric if (Stream.AtEndOfStream()) 215d88c1a5aSDimitry Andric return ""; 216d88c1a5aSDimitry Andric 217d88c1a5aSDimitry Andric BitstreamEntry Entry = Stream.advance(); 218d88c1a5aSDimitry Andric switch (Entry.Kind) { 219d88c1a5aSDimitry Andric case BitstreamEntry::EndBlock: 220d88c1a5aSDimitry Andric case BitstreamEntry::Error: 221d88c1a5aSDimitry Andric return error("Malformed block"); 222d88c1a5aSDimitry Andric 223d88c1a5aSDimitry Andric case BitstreamEntry::SubBlock: 224d88c1a5aSDimitry Andric if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) 225d88c1a5aSDimitry Andric return readIdentificationBlock(Stream); 226d88c1a5aSDimitry Andric 227d88c1a5aSDimitry Andric // Ignore other sub-blocks. 228d88c1a5aSDimitry Andric if (Stream.SkipBlock()) 229d88c1a5aSDimitry Andric return error("Malformed block"); 230d88c1a5aSDimitry Andric continue; 231d88c1a5aSDimitry Andric case BitstreamEntry::Record: 232d88c1a5aSDimitry Andric Stream.skipRecord(Entry.ID); 233d88c1a5aSDimitry Andric continue; 234d88c1a5aSDimitry Andric } 235d88c1a5aSDimitry Andric } 236d88c1a5aSDimitry Andric } 237d88c1a5aSDimitry Andric 2382cab237bSDimitry Andric static Expected<bool> hasObjCCategoryInModule(BitstreamCursor &Stream) { 239d88c1a5aSDimitry Andric if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID)) 240d88c1a5aSDimitry Andric return error("Invalid record"); 241d88c1a5aSDimitry Andric 242d88c1a5aSDimitry Andric SmallVector<uint64_t, 64> Record; 243d88c1a5aSDimitry Andric // Read all the records for this module. 244d88c1a5aSDimitry Andric 245d88c1a5aSDimitry Andric while (true) { 246d88c1a5aSDimitry Andric BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 247d88c1a5aSDimitry Andric 248d88c1a5aSDimitry Andric switch (Entry.Kind) { 249d88c1a5aSDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already. 250d88c1a5aSDimitry Andric case BitstreamEntry::Error: 251d88c1a5aSDimitry Andric return error("Malformed block"); 252d88c1a5aSDimitry Andric case BitstreamEntry::EndBlock: 253d88c1a5aSDimitry Andric return false; 254d88c1a5aSDimitry Andric case BitstreamEntry::Record: 255d88c1a5aSDimitry Andric // The interesting case. 256d88c1a5aSDimitry Andric break; 257d88c1a5aSDimitry Andric } 258d88c1a5aSDimitry Andric 259d88c1a5aSDimitry Andric // Read a record. 260d88c1a5aSDimitry Andric switch (Stream.readRecord(Entry.ID, Record)) { 261d88c1a5aSDimitry Andric default: 262d88c1a5aSDimitry Andric break; // Default behavior, ignore unknown content. 263d88c1a5aSDimitry Andric case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N] 264d88c1a5aSDimitry Andric std::string S; 265d88c1a5aSDimitry Andric if (convertToString(Record, 0, S)) 266d88c1a5aSDimitry Andric return error("Invalid record"); 267d88c1a5aSDimitry Andric // Check for the i386 and other (x86_64, ARM) conventions 268d88c1a5aSDimitry Andric if (S.find("__DATA,__objc_catlist") != std::string::npos || 269d88c1a5aSDimitry Andric S.find("__OBJC,__category") != std::string::npos) 270d88c1a5aSDimitry Andric return true; 271d88c1a5aSDimitry Andric break; 272d88c1a5aSDimitry Andric } 273d88c1a5aSDimitry Andric } 274d88c1a5aSDimitry Andric Record.clear(); 275d88c1a5aSDimitry Andric } 276d88c1a5aSDimitry Andric llvm_unreachable("Exit infinite loop"); 277d88c1a5aSDimitry Andric } 278d88c1a5aSDimitry Andric 2792cab237bSDimitry Andric static Expected<bool> hasObjCCategory(BitstreamCursor &Stream) { 280d88c1a5aSDimitry Andric // We expect a number of well-defined blocks, though we don't necessarily 281d88c1a5aSDimitry Andric // need to understand them all. 282d88c1a5aSDimitry Andric while (true) { 283d88c1a5aSDimitry Andric BitstreamEntry Entry = Stream.advance(); 284d88c1a5aSDimitry Andric 285d88c1a5aSDimitry Andric switch (Entry.Kind) { 286d88c1a5aSDimitry Andric case BitstreamEntry::Error: 287d88c1a5aSDimitry Andric return error("Malformed block"); 288d88c1a5aSDimitry Andric case BitstreamEntry::EndBlock: 289d88c1a5aSDimitry Andric return false; 290d88c1a5aSDimitry Andric 291d88c1a5aSDimitry Andric case BitstreamEntry::SubBlock: 292d88c1a5aSDimitry Andric if (Entry.ID == bitc::MODULE_BLOCK_ID) 293d88c1a5aSDimitry Andric return hasObjCCategoryInModule(Stream); 294d88c1a5aSDimitry Andric 295d88c1a5aSDimitry Andric // Ignore other sub-blocks. 296d88c1a5aSDimitry Andric if (Stream.SkipBlock()) 297d88c1a5aSDimitry Andric return error("Malformed block"); 298d88c1a5aSDimitry Andric continue; 299d88c1a5aSDimitry Andric 300d88c1a5aSDimitry Andric case BitstreamEntry::Record: 301d88c1a5aSDimitry Andric Stream.skipRecord(Entry.ID); 302d88c1a5aSDimitry Andric continue; 303d88c1a5aSDimitry Andric } 304d88c1a5aSDimitry Andric } 305d88c1a5aSDimitry Andric } 306d88c1a5aSDimitry Andric 3072cab237bSDimitry Andric static Expected<std::string> readModuleTriple(BitstreamCursor &Stream) { 308d88c1a5aSDimitry Andric if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID)) 309d88c1a5aSDimitry Andric return error("Invalid record"); 310d88c1a5aSDimitry Andric 311d88c1a5aSDimitry Andric SmallVector<uint64_t, 64> Record; 312d88c1a5aSDimitry Andric 313d88c1a5aSDimitry Andric std::string Triple; 314d88c1a5aSDimitry Andric 315d88c1a5aSDimitry Andric // Read all the records for this module. 316d88c1a5aSDimitry Andric while (true) { 317d88c1a5aSDimitry Andric BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 318d88c1a5aSDimitry Andric 319d88c1a5aSDimitry Andric switch (Entry.Kind) { 320d88c1a5aSDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already. 321d88c1a5aSDimitry Andric case BitstreamEntry::Error: 322d88c1a5aSDimitry Andric return error("Malformed block"); 323d88c1a5aSDimitry Andric case BitstreamEntry::EndBlock: 324d88c1a5aSDimitry Andric return Triple; 325d88c1a5aSDimitry Andric case BitstreamEntry::Record: 326d88c1a5aSDimitry Andric // The interesting case. 327d88c1a5aSDimitry Andric break; 328d88c1a5aSDimitry Andric } 329d88c1a5aSDimitry Andric 330d88c1a5aSDimitry Andric // Read a record. 331d88c1a5aSDimitry Andric switch (Stream.readRecord(Entry.ID, Record)) { 332d88c1a5aSDimitry Andric default: break; // Default behavior, ignore unknown content. 333d88c1a5aSDimitry Andric case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N] 334d88c1a5aSDimitry Andric std::string S; 335d88c1a5aSDimitry Andric if (convertToString(Record, 0, S)) 336d88c1a5aSDimitry Andric return error("Invalid record"); 337d88c1a5aSDimitry Andric Triple = S; 338d88c1a5aSDimitry Andric break; 339d88c1a5aSDimitry Andric } 340d88c1a5aSDimitry Andric } 341d88c1a5aSDimitry Andric Record.clear(); 342d88c1a5aSDimitry Andric } 343d88c1a5aSDimitry Andric llvm_unreachable("Exit infinite loop"); 344d88c1a5aSDimitry Andric } 345d88c1a5aSDimitry Andric 3462cab237bSDimitry Andric static Expected<std::string> readTriple(BitstreamCursor &Stream) { 347d88c1a5aSDimitry Andric // We expect a number of well-defined blocks, though we don't necessarily 348d88c1a5aSDimitry Andric // need to understand them all. 349d88c1a5aSDimitry Andric while (true) { 350d88c1a5aSDimitry Andric BitstreamEntry Entry = Stream.advance(); 351d88c1a5aSDimitry Andric 352d88c1a5aSDimitry Andric switch (Entry.Kind) { 353d88c1a5aSDimitry Andric case BitstreamEntry::Error: 354d88c1a5aSDimitry Andric return error("Malformed block"); 355d88c1a5aSDimitry Andric case BitstreamEntry::EndBlock: 356d88c1a5aSDimitry Andric return ""; 357d88c1a5aSDimitry Andric 358d88c1a5aSDimitry Andric case BitstreamEntry::SubBlock: 359d88c1a5aSDimitry Andric if (Entry.ID == bitc::MODULE_BLOCK_ID) 360d88c1a5aSDimitry Andric return readModuleTriple(Stream); 361d88c1a5aSDimitry Andric 362d88c1a5aSDimitry Andric // Ignore other sub-blocks. 363d88c1a5aSDimitry Andric if (Stream.SkipBlock()) 364d88c1a5aSDimitry Andric return error("Malformed block"); 365d88c1a5aSDimitry Andric continue; 366d88c1a5aSDimitry Andric 367d88c1a5aSDimitry Andric case BitstreamEntry::Record: 368d88c1a5aSDimitry Andric Stream.skipRecord(Entry.ID); 369d88c1a5aSDimitry Andric continue; 370d88c1a5aSDimitry Andric } 371d88c1a5aSDimitry Andric } 372d88c1a5aSDimitry Andric } 373d88c1a5aSDimitry Andric 3742cab237bSDimitry Andric namespace { 3752cab237bSDimitry Andric 376d88c1a5aSDimitry Andric class BitcodeReaderBase { 377d88c1a5aSDimitry Andric protected: 3786bc11b14SDimitry Andric BitcodeReaderBase(BitstreamCursor Stream, StringRef Strtab) 3796bc11b14SDimitry Andric : Stream(std::move(Stream)), Strtab(Strtab) { 380d88c1a5aSDimitry Andric this->Stream.setBlockInfo(&BlockInfo); 381d88c1a5aSDimitry Andric } 382d88c1a5aSDimitry Andric 383d88c1a5aSDimitry Andric BitstreamBlockInfo BlockInfo; 384d88c1a5aSDimitry Andric BitstreamCursor Stream; 3856bc11b14SDimitry Andric StringRef Strtab; 3866bc11b14SDimitry Andric 3876bc11b14SDimitry Andric /// In version 2 of the bitcode we store names of global values and comdats in 3886bc11b14SDimitry Andric /// a string table rather than in the VST. 3896bc11b14SDimitry Andric bool UseStrtab = false; 390d88c1a5aSDimitry Andric 3917a7e6055SDimitry Andric Expected<unsigned> parseVersionRecord(ArrayRef<uint64_t> Record); 3927a7e6055SDimitry Andric 3936bc11b14SDimitry Andric /// If this module uses a string table, pop the reference to the string table 3946bc11b14SDimitry Andric /// and return the referenced string and the rest of the record. Otherwise 3956bc11b14SDimitry Andric /// just return the record itself. 3966bc11b14SDimitry Andric std::pair<StringRef, ArrayRef<uint64_t>> 3976bc11b14SDimitry Andric readNameFromStrtab(ArrayRef<uint64_t> Record); 3986bc11b14SDimitry Andric 399d88c1a5aSDimitry Andric bool readBlockInfo(); 400d88c1a5aSDimitry Andric 401d88c1a5aSDimitry Andric // Contains an arbitrary and optional string identifying the bitcode producer 402d88c1a5aSDimitry Andric std::string ProducerIdentification; 403d88c1a5aSDimitry Andric 404d88c1a5aSDimitry Andric Error error(const Twine &Message); 405ff0cc061SDimitry Andric }; 406ff0cc061SDimitry Andric 4072cab237bSDimitry Andric } // end anonymous namespace 4082cab237bSDimitry Andric 409d88c1a5aSDimitry Andric Error BitcodeReaderBase::error(const Twine &Message) { 410d88c1a5aSDimitry Andric std::string FullMsg = Message.str(); 411d88c1a5aSDimitry Andric if (!ProducerIdentification.empty()) 412d88c1a5aSDimitry Andric FullMsg += " (Producer: '" + ProducerIdentification + "' Reader: 'LLVM " + 413d88c1a5aSDimitry Andric LLVM_VERSION_STRING "')"; 414d88c1a5aSDimitry Andric return ::error(FullMsg); 415ff0cc061SDimitry Andric } 416ff0cc061SDimitry Andric 4177a7e6055SDimitry Andric Expected<unsigned> 4187a7e6055SDimitry Andric BitcodeReaderBase::parseVersionRecord(ArrayRef<uint64_t> Record) { 4192cab237bSDimitry Andric if (Record.empty()) 4207a7e6055SDimitry Andric return error("Invalid record"); 4217a7e6055SDimitry Andric unsigned ModuleVersion = Record[0]; 4226bc11b14SDimitry Andric if (ModuleVersion > 2) 4237a7e6055SDimitry Andric return error("Invalid value"); 4246bc11b14SDimitry Andric UseStrtab = ModuleVersion >= 2; 4257a7e6055SDimitry Andric return ModuleVersion; 4267a7e6055SDimitry Andric } 4277a7e6055SDimitry Andric 4286bc11b14SDimitry Andric std::pair<StringRef, ArrayRef<uint64_t>> 4296bc11b14SDimitry Andric BitcodeReaderBase::readNameFromStrtab(ArrayRef<uint64_t> Record) { 4306bc11b14SDimitry Andric if (!UseStrtab) 4316bc11b14SDimitry Andric return {"", Record}; 4326bc11b14SDimitry Andric // Invalid reference. Let the caller complain about the record being empty. 4336bc11b14SDimitry Andric if (Record[0] + Record[1] > Strtab.size()) 4346bc11b14SDimitry Andric return {"", {}}; 4356bc11b14SDimitry Andric return {StringRef(Strtab.data() + Record[0], Record[1]), Record.slice(2)}; 4366bc11b14SDimitry Andric } 4376bc11b14SDimitry Andric 4382cab237bSDimitry Andric namespace { 4392cab237bSDimitry Andric 440d88c1a5aSDimitry Andric class BitcodeReader : public BitcodeReaderBase, public GVMaterializer { 441ff0cc061SDimitry Andric LLVMContext &Context; 4428f0fd8f6SDimitry Andric Module *TheModule = nullptr; 4437d523365SDimitry Andric // Next offset to start scanning for lazy parsing of function bodies. 4448f0fd8f6SDimitry Andric uint64_t NextUnreadBit = 0; 4457d523365SDimitry Andric // Last function offset found in the VST. 4467d523365SDimitry Andric uint64_t LastFunctionBlockBit = 0; 4478f0fd8f6SDimitry Andric bool SeenValueSymbolTable = false; 4487d523365SDimitry Andric uint64_t VSTOffset = 0; 449ff0cc061SDimitry Andric 4507a7e6055SDimitry Andric std::vector<std::string> SectionTable; 4517a7e6055SDimitry Andric std::vector<std::string> GCTable; 4527a7e6055SDimitry Andric 453ff0cc061SDimitry Andric std::vector<Type*> TypeList; 454ff0cc061SDimitry Andric BitcodeReaderValueList ValueList; 455d88c1a5aSDimitry Andric Optional<MetadataLoader> MDLoader; 456ff0cc061SDimitry Andric std::vector<Comdat *> ComdatList; 457ff0cc061SDimitry Andric SmallVector<Instruction *, 64> InstructionList; 458ff0cc061SDimitry Andric 459ff0cc061SDimitry Andric std::vector<std::pair<GlobalVariable *, unsigned>> GlobalInits; 4603ca95b02SDimitry Andric std::vector<std::pair<GlobalIndirectSymbol *, unsigned>> IndirectSymbolInits; 461ff0cc061SDimitry Andric std::vector<std::pair<Function *, unsigned>> FunctionPrefixes; 462ff0cc061SDimitry Andric std::vector<std::pair<Function *, unsigned>> FunctionPrologues; 4638f0fd8f6SDimitry Andric std::vector<std::pair<Function *, unsigned>> FunctionPersonalityFns; 464ff0cc061SDimitry Andric 4658f0fd8f6SDimitry Andric /// The set of attributes by index. Index zero in the file is for null, and 4668f0fd8f6SDimitry Andric /// is thus not represented here. As such all indices are off by one. 4677a7e6055SDimitry Andric std::vector<AttributeList> MAttributes; 468ff0cc061SDimitry Andric 4697d523365SDimitry Andric /// The set of attribute groups. 4707a7e6055SDimitry Andric std::map<unsigned, AttributeList> MAttributeGroups; 471ff0cc061SDimitry Andric 4728f0fd8f6SDimitry Andric /// While parsing a function body, this is a list of the basic blocks for the 4738f0fd8f6SDimitry Andric /// function. 474ff0cc061SDimitry Andric std::vector<BasicBlock*> FunctionBBs; 475ff0cc061SDimitry Andric 476ff0cc061SDimitry Andric // When reading the module header, this list is populated with functions that 477ff0cc061SDimitry Andric // have bodies later in the file. 478ff0cc061SDimitry Andric std::vector<Function*> FunctionsWithBodies; 479ff0cc061SDimitry Andric 480ff0cc061SDimitry Andric // When intrinsic functions are encountered which require upgrading they are 481ff0cc061SDimitry Andric // stored here with their replacement function. 4822cab237bSDimitry Andric using UpdatedIntrinsicMap = DenseMap<Function *, Function *>; 4833ca95b02SDimitry Andric UpdatedIntrinsicMap UpgradedIntrinsics; 4843ca95b02SDimitry Andric // Intrinsics which were remangled because of types rename 4853ca95b02SDimitry Andric UpdatedIntrinsicMap RemangledIntrinsics; 486ff0cc061SDimitry Andric 487ff0cc061SDimitry Andric // Several operations happen after the module header has been read, but 488ff0cc061SDimitry Andric // before function bodies are processed. This keeps track of whether 489ff0cc061SDimitry Andric // we've done this yet. 4908f0fd8f6SDimitry Andric bool SeenFirstFunctionBody = false; 491ff0cc061SDimitry Andric 4928f0fd8f6SDimitry Andric /// When function bodies are initially scanned, this map contains info about 4938f0fd8f6SDimitry Andric /// where to find deferred function body in the stream. 494ff0cc061SDimitry Andric DenseMap<Function*, uint64_t> DeferredFunctionInfo; 495ff0cc061SDimitry Andric 496ff0cc061SDimitry Andric /// When Metadata block is initially scanned when parsing the module, we may 497ff0cc061SDimitry Andric /// choose to defer parsing of the metadata. This vector contains info about 498ff0cc061SDimitry Andric /// which Metadata blocks are deferred. 499ff0cc061SDimitry Andric std::vector<uint64_t> DeferredMetadataInfo; 500ff0cc061SDimitry Andric 501ff0cc061SDimitry Andric /// These are basic blocks forward-referenced by block addresses. They are 502ff0cc061SDimitry Andric /// inserted lazily into functions when they're loaded. The basic block ID is 503ff0cc061SDimitry Andric /// its index into the vector. 504ff0cc061SDimitry Andric DenseMap<Function *, std::vector<BasicBlock *>> BasicBlockFwdRefs; 505ff0cc061SDimitry Andric std::deque<Function *> BasicBlockFwdRefQueue; 506ff0cc061SDimitry Andric 5078f0fd8f6SDimitry Andric /// Indicates that we are using a new encoding for instruction operands where 5088f0fd8f6SDimitry Andric /// most operands in the current FUNCTION_BLOCK are encoded relative to the 5098f0fd8f6SDimitry Andric /// instruction number, for a more compact encoding. Some instruction 5108f0fd8f6SDimitry Andric /// operands are not relative to the instruction ID: basic block numbers, and 5118f0fd8f6SDimitry Andric /// types. Once the old style function blocks have been phased out, we would 512ff0cc061SDimitry Andric /// not need this flag. 5138f0fd8f6SDimitry Andric bool UseRelativeIDs = false; 514ff0cc061SDimitry Andric 515ff0cc061SDimitry Andric /// True if all functions will be materialized, negating the need to process 516ff0cc061SDimitry Andric /// (e.g.) blockaddress forward references. 5178f0fd8f6SDimitry Andric bool WillMaterializeAllForwardRefs = false; 518ff0cc061SDimitry Andric 519ff0cc061SDimitry Andric bool StripDebugInfo = false; 520d88c1a5aSDimitry Andric TBAAVerifier TBAAVerifyHelper; 5217d523365SDimitry Andric 5227d523365SDimitry Andric std::vector<std::string> BundleTags; 523c4394386SDimitry Andric SmallVector<SyncScope::ID, 8> SSIDs; 5247d523365SDimitry Andric 525ff0cc061SDimitry Andric public: 5266bc11b14SDimitry Andric BitcodeReader(BitstreamCursor Stream, StringRef Strtab, 5276bc11b14SDimitry Andric StringRef ProducerIdentification, LLVMContext &Context); 528ff0cc061SDimitry Andric 529d88c1a5aSDimitry Andric Error materializeForwardReferencedFunctions(); 530ff0cc061SDimitry Andric 531d88c1a5aSDimitry Andric Error materialize(GlobalValue *GV) override; 532d88c1a5aSDimitry Andric Error materializeModule() override; 533ff0cc061SDimitry Andric std::vector<StructType *> getIdentifiedStructTypes() const override; 534ff0cc061SDimitry Andric 5358f0fd8f6SDimitry Andric /// \brief Main interface to parsing a bitcode buffer. 5368f0fd8f6SDimitry Andric /// \returns true if an error occurred. 537d88c1a5aSDimitry Andric Error parseBitcodeInto(Module *M, bool ShouldLazyLoadMetadata = false, 538d88c1a5aSDimitry Andric bool IsImporting = false); 5393ca95b02SDimitry Andric 540ff0cc061SDimitry Andric static uint64_t decodeSignRotatedValue(uint64_t V); 541ff0cc061SDimitry Andric 542ff0cc061SDimitry Andric /// Materialize any deferred Metadata block. 543d88c1a5aSDimitry Andric Error materializeMetadata() override; 544ff0cc061SDimitry Andric 545ff0cc061SDimitry Andric void setStripDebugInfo() override; 546ff0cc061SDimitry Andric 547ff0cc061SDimitry Andric private: 548ff0cc061SDimitry Andric std::vector<StructType *> IdentifiedStructTypes; 549ff0cc061SDimitry Andric StructType *createIdentifiedStructType(LLVMContext &Context, StringRef Name); 550ff0cc061SDimitry Andric StructType *createIdentifiedStructType(LLVMContext &Context); 551ff0cc061SDimitry Andric 552ff0cc061SDimitry Andric Type *getTypeByID(unsigned ID); 553d88c1a5aSDimitry Andric 554ff0cc061SDimitry Andric Value *getFnValueByID(unsigned ID, Type *Ty) { 555ff0cc061SDimitry Andric if (Ty && Ty->isMetadataTy()) 556ff0cc061SDimitry Andric return MetadataAsValue::get(Ty->getContext(), getFnMetadataByID(ID)); 557ff0cc061SDimitry Andric return ValueList.getValueFwdRef(ID, Ty); 558ff0cc061SDimitry Andric } 559d88c1a5aSDimitry Andric 560ff0cc061SDimitry Andric Metadata *getFnMetadataByID(unsigned ID) { 561f8496407SDimitry Andric return MDLoader->getMetadataFwdRefOrLoad(ID); 562ff0cc061SDimitry Andric } 563d88c1a5aSDimitry Andric 564ff0cc061SDimitry Andric BasicBlock *getBasicBlock(unsigned ID) const { 565ff0cc061SDimitry Andric if (ID >= FunctionBBs.size()) return nullptr; // Invalid ID 566ff0cc061SDimitry Andric return FunctionBBs[ID]; 567ff0cc061SDimitry Andric } 568d88c1a5aSDimitry Andric 5697a7e6055SDimitry Andric AttributeList getAttributes(unsigned i) const { 570ff0cc061SDimitry Andric if (i-1 < MAttributes.size()) 571ff0cc061SDimitry Andric return MAttributes[i-1]; 5727a7e6055SDimitry Andric return AttributeList(); 573ff0cc061SDimitry Andric } 574ff0cc061SDimitry Andric 5758f0fd8f6SDimitry Andric /// Read a value/type pair out of the specified record from slot 'Slot'. 5768f0fd8f6SDimitry Andric /// Increment Slot past the number of slots used in the record. Return true on 5778f0fd8f6SDimitry Andric /// failure. 578ff0cc061SDimitry Andric bool getValueTypePair(SmallVectorImpl<uint64_t> &Record, unsigned &Slot, 579ff0cc061SDimitry Andric unsigned InstNum, Value *&ResVal) { 580ff0cc061SDimitry Andric if (Slot == Record.size()) return true; 581ff0cc061SDimitry Andric unsigned ValNo = (unsigned)Record[Slot++]; 582ff0cc061SDimitry Andric // Adjust the ValNo, if it was encoded relative to the InstNum. 583ff0cc061SDimitry Andric if (UseRelativeIDs) 584ff0cc061SDimitry Andric ValNo = InstNum - ValNo; 585ff0cc061SDimitry Andric if (ValNo < InstNum) { 586ff0cc061SDimitry Andric // If this is not a forward reference, just return the value we already 587ff0cc061SDimitry Andric // have. 588ff0cc061SDimitry Andric ResVal = getFnValueByID(ValNo, nullptr); 589ff0cc061SDimitry Andric return ResVal == nullptr; 590ff0cc061SDimitry Andric } 591ff0cc061SDimitry Andric if (Slot == Record.size()) 592ff0cc061SDimitry Andric return true; 593ff0cc061SDimitry Andric 594ff0cc061SDimitry Andric unsigned TypeNo = (unsigned)Record[Slot++]; 595ff0cc061SDimitry Andric ResVal = getFnValueByID(ValNo, getTypeByID(TypeNo)); 596ff0cc061SDimitry Andric return ResVal == nullptr; 597ff0cc061SDimitry Andric } 598ff0cc061SDimitry Andric 5998f0fd8f6SDimitry Andric /// Read a value out of the specified record from slot 'Slot'. Increment Slot 6008f0fd8f6SDimitry Andric /// past the number of slots used by the value in the record. Return true if 6018f0fd8f6SDimitry Andric /// there is an error. 602ff0cc061SDimitry Andric bool popValue(SmallVectorImpl<uint64_t> &Record, unsigned &Slot, 603ff0cc061SDimitry Andric unsigned InstNum, Type *Ty, Value *&ResVal) { 604ff0cc061SDimitry Andric if (getValue(Record, Slot, InstNum, Ty, ResVal)) 605ff0cc061SDimitry Andric return true; 606ff0cc061SDimitry Andric // All values currently take a single record slot. 607ff0cc061SDimitry Andric ++Slot; 608ff0cc061SDimitry Andric return false; 609ff0cc061SDimitry Andric } 610ff0cc061SDimitry Andric 6118f0fd8f6SDimitry Andric /// Like popValue, but does not increment the Slot number. 612ff0cc061SDimitry Andric bool getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot, 613ff0cc061SDimitry Andric unsigned InstNum, Type *Ty, Value *&ResVal) { 614ff0cc061SDimitry Andric ResVal = getValue(Record, Slot, InstNum, Ty); 615ff0cc061SDimitry Andric return ResVal == nullptr; 616ff0cc061SDimitry Andric } 617ff0cc061SDimitry Andric 6188f0fd8f6SDimitry Andric /// Version of getValue that returns ResVal directly, or 0 if there is an 6198f0fd8f6SDimitry Andric /// error. 620ff0cc061SDimitry Andric Value *getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot, 621ff0cc061SDimitry Andric unsigned InstNum, Type *Ty) { 622ff0cc061SDimitry Andric if (Slot == Record.size()) return nullptr; 623ff0cc061SDimitry Andric unsigned ValNo = (unsigned)Record[Slot]; 624ff0cc061SDimitry Andric // Adjust the ValNo, if it was encoded relative to the InstNum. 625ff0cc061SDimitry Andric if (UseRelativeIDs) 626ff0cc061SDimitry Andric ValNo = InstNum - ValNo; 627ff0cc061SDimitry Andric return getFnValueByID(ValNo, Ty); 628ff0cc061SDimitry Andric } 629ff0cc061SDimitry Andric 6308f0fd8f6SDimitry Andric /// Like getValue, but decodes signed VBRs. 631ff0cc061SDimitry Andric Value *getValueSigned(SmallVectorImpl<uint64_t> &Record, unsigned Slot, 632ff0cc061SDimitry Andric unsigned InstNum, Type *Ty) { 633ff0cc061SDimitry Andric if (Slot == Record.size()) return nullptr; 634ff0cc061SDimitry Andric unsigned ValNo = (unsigned)decodeSignRotatedValue(Record[Slot]); 635ff0cc061SDimitry Andric // Adjust the ValNo, if it was encoded relative to the InstNum. 636ff0cc061SDimitry Andric if (UseRelativeIDs) 637ff0cc061SDimitry Andric ValNo = InstNum - ValNo; 638ff0cc061SDimitry Andric return getFnValueByID(ValNo, Ty); 639ff0cc061SDimitry Andric } 640ff0cc061SDimitry Andric 641ff0cc061SDimitry Andric /// Converts alignment exponent (i.e. power of two (or zero)) to the 642ff0cc061SDimitry Andric /// corresponding alignment to use. If alignment is too large, returns 643ff0cc061SDimitry Andric /// a corresponding error code. 644d88c1a5aSDimitry Andric Error parseAlignmentValue(uint64_t Exponent, unsigned &Alignment); 645d88c1a5aSDimitry Andric Error parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind); 646d88c1a5aSDimitry Andric Error parseModule(uint64_t ResumeBit, bool ShouldLazyLoadMetadata = false); 6477a7e6055SDimitry Andric 6487a7e6055SDimitry Andric Error parseComdatRecord(ArrayRef<uint64_t> Record); 6497a7e6055SDimitry Andric Error parseGlobalVarRecord(ArrayRef<uint64_t> Record); 6507a7e6055SDimitry Andric Error parseFunctionRecord(ArrayRef<uint64_t> Record); 6517a7e6055SDimitry Andric Error parseGlobalIndirectSymbolRecord(unsigned BitCode, 6527a7e6055SDimitry Andric ArrayRef<uint64_t> Record); 6537a7e6055SDimitry Andric 654d88c1a5aSDimitry Andric Error parseAttributeBlock(); 655d88c1a5aSDimitry Andric Error parseAttributeGroupBlock(); 656d88c1a5aSDimitry Andric Error parseTypeTable(); 657d88c1a5aSDimitry Andric Error parseTypeTableBody(); 658d88c1a5aSDimitry Andric Error parseOperandBundleTags(); 659c4394386SDimitry Andric Error parseSyncScopeNames(); 660ff0cc061SDimitry Andric 661d88c1a5aSDimitry Andric Expected<Value *> recordValue(SmallVectorImpl<uint64_t> &Record, 6627d523365SDimitry Andric unsigned NameIndex, Triple &TT); 6636bc11b14SDimitry Andric void setDeferredFunctionInfo(unsigned FuncBitcodeOffsetDelta, Function *F, 6646bc11b14SDimitry Andric ArrayRef<uint64_t> Record); 665d88c1a5aSDimitry Andric Error parseValueSymbolTable(uint64_t Offset = 0); 6666bc11b14SDimitry Andric Error parseGlobalValueSymbolTable(); 667d88c1a5aSDimitry Andric Error parseConstants(); 668d88c1a5aSDimitry Andric Error rememberAndSkipFunctionBodies(); 669d88c1a5aSDimitry Andric Error rememberAndSkipFunctionBody(); 670ff0cc061SDimitry Andric /// Save the positions of the Metadata blocks and skip parsing the blocks. 671d88c1a5aSDimitry Andric Error rememberAndSkipMetadata(); 672d88c1a5aSDimitry Andric Error typeCheckLoadStoreInst(Type *ValType, Type *PtrType); 673d88c1a5aSDimitry Andric Error parseFunctionBody(Function *F); 674d88c1a5aSDimitry Andric Error globalCleanup(); 675d88c1a5aSDimitry Andric Error resolveGlobalAndIndirectSymbolInits(); 676d88c1a5aSDimitry Andric Error parseUseLists(); 677d88c1a5aSDimitry Andric Error findFunctionInStream( 678ff0cc061SDimitry Andric Function *F, 679ff0cc061SDimitry Andric DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator); 680c4394386SDimitry Andric 681c4394386SDimitry Andric SyncScope::ID getDecodedSyncScopeID(unsigned Val); 682ff0cc061SDimitry Andric }; 6837d523365SDimitry Andric 6847d523365SDimitry Andric /// Class to manage reading and parsing function summary index bitcode 6857d523365SDimitry Andric /// files/sections. 686d88c1a5aSDimitry Andric class ModuleSummaryIndexBitcodeReader : public BitcodeReaderBase { 687d88c1a5aSDimitry Andric /// The module index built during parsing. 688d88c1a5aSDimitry Andric ModuleSummaryIndex &TheIndex; 6897d523365SDimitry Andric 6903ca95b02SDimitry Andric /// Indicates whether we have encountered a global value summary section 691d88c1a5aSDimitry Andric /// yet during parsing. 6923ca95b02SDimitry Andric bool SeenGlobalValSummary = false; 6937d523365SDimitry Andric 6943ca95b02SDimitry Andric /// Indicates whether we have already parsed the VST, used for error checking. 6953ca95b02SDimitry Andric bool SeenValueSymbolTable = false; 6963ca95b02SDimitry Andric 6973ca95b02SDimitry Andric /// Set to the offset of the VST recorded in the MODULE_CODE_VSTOFFSET record. 6983ca95b02SDimitry Andric /// Used to enable on-demand parsing of the VST. 6993ca95b02SDimitry Andric uint64_t VSTOffset = 0; 7003ca95b02SDimitry Andric 7010f5676f4SDimitry Andric // Map to save ValueId to ValueInfo association that was recorded in the 7023ca95b02SDimitry Andric // ValueSymbolTable. It is used after the VST is parsed to convert 7033ca95b02SDimitry Andric // call graph edges read from the function summary from referencing 7040f5676f4SDimitry Andric // callees by their ValueId to using the ValueInfo instead, which is how 7053ca95b02SDimitry Andric // they are recorded in the summary index being built. 7060f5676f4SDimitry Andric // We save a GUID which refers to the same global as the ValueInfo, but 7070f5676f4SDimitry Andric // ignoring the linkage, i.e. for values other than local linkage they are 7080f5676f4SDimitry Andric // identical. 7090f5676f4SDimitry Andric DenseMap<unsigned, std::pair<ValueInfo, GlobalValue::GUID>> 7100f5676f4SDimitry Andric ValueIdToValueInfoMap; 7117d523365SDimitry Andric 7127d523365SDimitry Andric /// Map populated during module path string table parsing, from the 7137d523365SDimitry Andric /// module ID to a string reference owned by the index's module 7143ca95b02SDimitry Andric /// path string table, used to correlate with combined index 7157d523365SDimitry Andric /// summary records. 7167d523365SDimitry Andric DenseMap<uint64_t, StringRef> ModuleIdMap; 7177d523365SDimitry Andric 7183ca95b02SDimitry Andric /// Original source file name recorded in a bitcode record. 7193ca95b02SDimitry Andric std::string SourceFileName; 7203ca95b02SDimitry Andric 721f37b6182SDimitry Andric /// The string identifier given to this module by the client, normally the 722f37b6182SDimitry Andric /// path to the bitcode file. 723f37b6182SDimitry Andric StringRef ModulePath; 724f37b6182SDimitry Andric 725f37b6182SDimitry Andric /// For per-module summary indexes, the unique numerical identifier given to 726f37b6182SDimitry Andric /// this module by the client. 727f37b6182SDimitry Andric unsigned ModuleId; 728f37b6182SDimitry Andric 7297d523365SDimitry Andric public: 7306bc11b14SDimitry Andric ModuleSummaryIndexBitcodeReader(BitstreamCursor Stream, StringRef Strtab, 731f37b6182SDimitry Andric ModuleSummaryIndex &TheIndex, 732f37b6182SDimitry Andric StringRef ModulePath, unsigned ModuleId); 7337d523365SDimitry Andric 734f37b6182SDimitry Andric Error parseModule(); 7357d523365SDimitry Andric 7367d523365SDimitry Andric private: 7376bc11b14SDimitry Andric void setValueGUID(uint64_t ValueID, StringRef ValueName, 7386bc11b14SDimitry Andric GlobalValue::LinkageTypes Linkage, 7396bc11b14SDimitry Andric StringRef SourceFileName); 740d88c1a5aSDimitry Andric Error parseValueSymbolTable( 7413ca95b02SDimitry Andric uint64_t Offset, 7423ca95b02SDimitry Andric DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap); 743d88c1a5aSDimitry Andric std::vector<ValueInfo> makeRefList(ArrayRef<uint64_t> Record); 744d88c1a5aSDimitry Andric std::vector<FunctionSummary::EdgeTy> makeCallList(ArrayRef<uint64_t> Record, 745d88c1a5aSDimitry Andric bool IsOldProfileFormat, 746d88c1a5aSDimitry Andric bool HasProfile); 74724d58133SDimitry Andric Error parseEntireSummary(unsigned ID); 748d88c1a5aSDimitry Andric Error parseModuleStringTable(); 749d88c1a5aSDimitry Andric 7500f5676f4SDimitry Andric std::pair<ValueInfo, GlobalValue::GUID> 7510f5676f4SDimitry Andric getValueInfoFromValueId(unsigned ValueId); 752f37b6182SDimitry Andric 75324d58133SDimitry Andric ModuleSummaryIndex::ModuleInfo *addThisModule(); 7547d523365SDimitry Andric }; 755d88c1a5aSDimitry Andric 7563ca95b02SDimitry Andric } // end anonymous namespace 757ff0cc061SDimitry Andric 758d88c1a5aSDimitry Andric std::error_code llvm::errorToErrorCodeAndEmitErrors(LLVMContext &Ctx, 759d88c1a5aSDimitry Andric Error Err) { 760d88c1a5aSDimitry Andric if (Err) { 761d88c1a5aSDimitry Andric std::error_code EC; 762d88c1a5aSDimitry Andric handleAllErrors(std::move(Err), [&](ErrorInfoBase &EIB) { 763d88c1a5aSDimitry Andric EC = EIB.convertToErrorCode(); 764d88c1a5aSDimitry Andric Ctx.emitError(EIB.message()); 765d88c1a5aSDimitry Andric }); 76639d628a0SDimitry Andric return EC; 767dff0c46cSDimitry Andric } 76839d628a0SDimitry Andric return std::error_code(); 769d88c1a5aSDimitry Andric } 770d88c1a5aSDimitry Andric 7716bc11b14SDimitry Andric BitcodeReader::BitcodeReader(BitstreamCursor Stream, StringRef Strtab, 772d88c1a5aSDimitry Andric StringRef ProducerIdentification, 773d88c1a5aSDimitry Andric LLVMContext &Context) 7746bc11b14SDimitry Andric : BitcodeReaderBase(std::move(Stream), Strtab), Context(Context), 775d88c1a5aSDimitry Andric ValueList(Context) { 776d88c1a5aSDimitry Andric this->ProducerIdentification = ProducerIdentification; 777d88c1a5aSDimitry Andric } 778d88c1a5aSDimitry Andric 779d88c1a5aSDimitry Andric Error BitcodeReader::materializeForwardReferencedFunctions() { 780d88c1a5aSDimitry Andric if (WillMaterializeAllForwardRefs) 781d88c1a5aSDimitry Andric return Error::success(); 78239d628a0SDimitry Andric 78339d628a0SDimitry Andric // Prevent recursion. 78439d628a0SDimitry Andric WillMaterializeAllForwardRefs = true; 78539d628a0SDimitry Andric 78639d628a0SDimitry Andric while (!BasicBlockFwdRefQueue.empty()) { 78739d628a0SDimitry Andric Function *F = BasicBlockFwdRefQueue.front(); 78839d628a0SDimitry Andric BasicBlockFwdRefQueue.pop_front(); 78939d628a0SDimitry Andric assert(F && "Expected valid function"); 79039d628a0SDimitry Andric if (!BasicBlockFwdRefs.count(F)) 79139d628a0SDimitry Andric // Already materialized. 79239d628a0SDimitry Andric continue; 79339d628a0SDimitry Andric 79439d628a0SDimitry Andric // Check for a function that isn't materializable to prevent an infinite 79539d628a0SDimitry Andric // loop. When parsing a blockaddress stored in a global variable, there 79639d628a0SDimitry Andric // isn't a trivial way to check if a function will have a body without a 79739d628a0SDimitry Andric // linear search through FunctionsWithBodies, so just check it here. 79839d628a0SDimitry Andric if (!F->isMaterializable()) 7998f0fd8f6SDimitry Andric return error("Never resolved function from blockaddress"); 80039d628a0SDimitry Andric 80139d628a0SDimitry Andric // Try to materialize F. 802d88c1a5aSDimitry Andric if (Error Err = materialize(F)) 803d88c1a5aSDimitry Andric return Err; 80439d628a0SDimitry Andric } 80539d628a0SDimitry Andric assert(BasicBlockFwdRefs.empty() && "Function missing from queue"); 80639d628a0SDimitry Andric 80739d628a0SDimitry Andric // Reset state. 80839d628a0SDimitry Andric WillMaterializeAllForwardRefs = false; 809d88c1a5aSDimitry Andric return Error::success(); 810f22ef01cSRoman Divacky } 811f22ef01cSRoman Divacky 812f22ef01cSRoman Divacky //===----------------------------------------------------------------------===// 813f22ef01cSRoman Divacky // Helper functions to implement forward reference resolution, etc. 814f22ef01cSRoman Divacky //===----------------------------------------------------------------------===// 815f22ef01cSRoman Divacky 816ff0cc061SDimitry Andric static bool hasImplicitComdat(size_t Val) { 817ff0cc061SDimitry Andric switch (Val) { 818ff0cc061SDimitry Andric default: 819ff0cc061SDimitry Andric return false; 820ff0cc061SDimitry Andric case 1: // Old WeakAnyLinkage 821ff0cc061SDimitry Andric case 4: // Old LinkOnceAnyLinkage 822ff0cc061SDimitry Andric case 10: // Old WeakODRLinkage 823ff0cc061SDimitry Andric case 11: // Old LinkOnceODRLinkage 824ff0cc061SDimitry Andric return true; 825ff0cc061SDimitry Andric } 826ff0cc061SDimitry Andric } 827ff0cc061SDimitry Andric 82839d628a0SDimitry Andric static GlobalValue::LinkageTypes getDecodedLinkage(unsigned Val) { 829f22ef01cSRoman Divacky switch (Val) { 830f22ef01cSRoman Divacky default: // Map unknown/new linkages to external 83139d628a0SDimitry Andric case 0: 83239d628a0SDimitry Andric return GlobalValue::ExternalLinkage; 83339d628a0SDimitry Andric case 2: 83439d628a0SDimitry Andric return GlobalValue::AppendingLinkage; 83539d628a0SDimitry Andric case 3: 83639d628a0SDimitry Andric return GlobalValue::InternalLinkage; 83739d628a0SDimitry Andric case 5: 83839d628a0SDimitry Andric return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage 83939d628a0SDimitry Andric case 6: 84039d628a0SDimitry Andric return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage 84139d628a0SDimitry Andric case 7: 84239d628a0SDimitry Andric return GlobalValue::ExternalWeakLinkage; 84339d628a0SDimitry Andric case 8: 84439d628a0SDimitry Andric return GlobalValue::CommonLinkage; 84539d628a0SDimitry Andric case 9: 84639d628a0SDimitry Andric return GlobalValue::PrivateLinkage; 84739d628a0SDimitry Andric case 12: 84839d628a0SDimitry Andric return GlobalValue::AvailableExternallyLinkage; 84991bc56edSDimitry Andric case 13: 85091bc56edSDimitry Andric return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage 85191bc56edSDimitry Andric case 14: 85291bc56edSDimitry Andric return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage 85339d628a0SDimitry Andric case 15: 85439d628a0SDimitry Andric return GlobalValue::ExternalLinkage; // Obsolete LinkOnceODRAutoHideLinkage 855ff0cc061SDimitry Andric case 1: // Old value with implicit comdat. 856ff0cc061SDimitry Andric case 16: 857ff0cc061SDimitry Andric return GlobalValue::WeakAnyLinkage; 858ff0cc061SDimitry Andric case 10: // Old value with implicit comdat. 859ff0cc061SDimitry Andric case 17: 860ff0cc061SDimitry Andric return GlobalValue::WeakODRLinkage; 861ff0cc061SDimitry Andric case 4: // Old value with implicit comdat. 862ff0cc061SDimitry Andric case 18: 863ff0cc061SDimitry Andric return GlobalValue::LinkOnceAnyLinkage; 864ff0cc061SDimitry Andric case 11: // Old value with implicit comdat. 865ff0cc061SDimitry Andric case 19: 866ff0cc061SDimitry Andric return GlobalValue::LinkOnceODRLinkage; 867f22ef01cSRoman Divacky } 868f22ef01cSRoman Divacky } 869f22ef01cSRoman Divacky 8702cab237bSDimitry Andric static FunctionSummary::FFlags getDecodedFFlags(uint64_t RawFlags) { 8712cab237bSDimitry Andric FunctionSummary::FFlags Flags; 8722cab237bSDimitry Andric Flags.ReadNone = RawFlags & 0x1; 8732cab237bSDimitry Andric Flags.ReadOnly = (RawFlags >> 1) & 0x1; 8742cab237bSDimitry Andric Flags.NoRecurse = (RawFlags >> 2) & 0x1; 8752cab237bSDimitry Andric Flags.ReturnDoesNotAlias = (RawFlags >> 3) & 0x1; 8762cab237bSDimitry Andric return Flags; 8772cab237bSDimitry Andric } 8782cab237bSDimitry Andric 879d88c1a5aSDimitry Andric /// Decode the flags for GlobalValue in the summary. 8803ca95b02SDimitry Andric static GlobalValueSummary::GVFlags getDecodedGVSummaryFlags(uint64_t RawFlags, 8813ca95b02SDimitry Andric uint64_t Version) { 8823ca95b02SDimitry Andric // Summary were not emitted before LLVM 3.9, we don't need to upgrade Linkage 8833ca95b02SDimitry Andric // like getDecodedLinkage() above. Any future change to the linkage enum and 8843ca95b02SDimitry Andric // to getDecodedLinkage() will need to be taken into account here as above. 8853ca95b02SDimitry Andric auto Linkage = GlobalValue::LinkageTypes(RawFlags & 0xF); // 4 bits 8863ca95b02SDimitry Andric RawFlags = RawFlags >> 4; 88795ec533aSDimitry Andric bool NotEligibleToImport = (RawFlags & 0x1) || Version < 3; 8886d97bb29SDimitry Andric // The Live flag wasn't introduced until version 3. For dead stripping 88995ec533aSDimitry Andric // to work correctly on earlier versions, we must conservatively treat all 89095ec533aSDimitry Andric // values as live. 8916d97bb29SDimitry Andric bool Live = (RawFlags & 0x2) || Version < 3; 8922cab237bSDimitry Andric bool Local = (RawFlags & 0x4); 8932cab237bSDimitry Andric 8942cab237bSDimitry Andric return GlobalValueSummary::GVFlags(Linkage, NotEligibleToImport, Live, Local); 8953ca95b02SDimitry Andric } 8963ca95b02SDimitry Andric 8978f0fd8f6SDimitry Andric static GlobalValue::VisibilityTypes getDecodedVisibility(unsigned Val) { 898f22ef01cSRoman Divacky switch (Val) { 899f22ef01cSRoman Divacky default: // Map unknown visibilities to default. 900f22ef01cSRoman Divacky case 0: return GlobalValue::DefaultVisibility; 901f22ef01cSRoman Divacky case 1: return GlobalValue::HiddenVisibility; 902f22ef01cSRoman Divacky case 2: return GlobalValue::ProtectedVisibility; 903f22ef01cSRoman Divacky } 904f22ef01cSRoman Divacky } 905f22ef01cSRoman Divacky 90691bc56edSDimitry Andric static GlobalValue::DLLStorageClassTypes 9078f0fd8f6SDimitry Andric getDecodedDLLStorageClass(unsigned Val) { 90891bc56edSDimitry Andric switch (Val) { 90991bc56edSDimitry Andric default: // Map unknown values to default. 91091bc56edSDimitry Andric case 0: return GlobalValue::DefaultStorageClass; 91191bc56edSDimitry Andric case 1: return GlobalValue::DLLImportStorageClass; 91291bc56edSDimitry Andric case 2: return GlobalValue::DLLExportStorageClass; 91391bc56edSDimitry Andric } 91491bc56edSDimitry Andric } 91591bc56edSDimitry Andric 9162cab237bSDimitry Andric static bool getDecodedDSOLocal(unsigned Val) { 9172cab237bSDimitry Andric switch(Val) { 9182cab237bSDimitry Andric default: // Map unknown values to preemptable. 9192cab237bSDimitry Andric case 0: return false; 9202cab237bSDimitry Andric case 1: return true; 9212cab237bSDimitry Andric } 9222cab237bSDimitry Andric } 9232cab237bSDimitry Andric 9248f0fd8f6SDimitry Andric static GlobalVariable::ThreadLocalMode getDecodedThreadLocalMode(unsigned Val) { 9257ae0e2c9SDimitry Andric switch (Val) { 9267ae0e2c9SDimitry Andric case 0: return GlobalVariable::NotThreadLocal; 9277ae0e2c9SDimitry Andric default: // Map unknown non-zero value to general dynamic. 9287ae0e2c9SDimitry Andric case 1: return GlobalVariable::GeneralDynamicTLSModel; 9297ae0e2c9SDimitry Andric case 2: return GlobalVariable::LocalDynamicTLSModel; 9307ae0e2c9SDimitry Andric case 3: return GlobalVariable::InitialExecTLSModel; 9317ae0e2c9SDimitry Andric case 4: return GlobalVariable::LocalExecTLSModel; 9327ae0e2c9SDimitry Andric } 9337ae0e2c9SDimitry Andric } 9347ae0e2c9SDimitry Andric 9353ca95b02SDimitry Andric static GlobalVariable::UnnamedAddr getDecodedUnnamedAddrType(unsigned Val) { 9363ca95b02SDimitry Andric switch (Val) { 9373ca95b02SDimitry Andric default: // Map unknown to UnnamedAddr::None. 9383ca95b02SDimitry Andric case 0: return GlobalVariable::UnnamedAddr::None; 9393ca95b02SDimitry Andric case 1: return GlobalVariable::UnnamedAddr::Global; 9403ca95b02SDimitry Andric case 2: return GlobalVariable::UnnamedAddr::Local; 9413ca95b02SDimitry Andric } 9423ca95b02SDimitry Andric } 9433ca95b02SDimitry Andric 9448f0fd8f6SDimitry Andric static int getDecodedCastOpcode(unsigned Val) { 945f22ef01cSRoman Divacky switch (Val) { 946f22ef01cSRoman Divacky default: return -1; 947f22ef01cSRoman Divacky case bitc::CAST_TRUNC : return Instruction::Trunc; 948f22ef01cSRoman Divacky case bitc::CAST_ZEXT : return Instruction::ZExt; 949f22ef01cSRoman Divacky case bitc::CAST_SEXT : return Instruction::SExt; 950f22ef01cSRoman Divacky case bitc::CAST_FPTOUI : return Instruction::FPToUI; 951f22ef01cSRoman Divacky case bitc::CAST_FPTOSI : return Instruction::FPToSI; 952f22ef01cSRoman Divacky case bitc::CAST_UITOFP : return Instruction::UIToFP; 953f22ef01cSRoman Divacky case bitc::CAST_SITOFP : return Instruction::SIToFP; 954f22ef01cSRoman Divacky case bitc::CAST_FPTRUNC : return Instruction::FPTrunc; 955f22ef01cSRoman Divacky case bitc::CAST_FPEXT : return Instruction::FPExt; 956f22ef01cSRoman Divacky case bitc::CAST_PTRTOINT: return Instruction::PtrToInt; 957f22ef01cSRoman Divacky case bitc::CAST_INTTOPTR: return Instruction::IntToPtr; 958f22ef01cSRoman Divacky case bitc::CAST_BITCAST : return Instruction::BitCast; 959f785676fSDimitry Andric case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast; 960f22ef01cSRoman Divacky } 961f22ef01cSRoman Divacky } 962ff0cc061SDimitry Andric 9638f0fd8f6SDimitry Andric static int getDecodedBinaryOpcode(unsigned Val, Type *Ty) { 964ff0cc061SDimitry Andric bool IsFP = Ty->isFPOrFPVectorTy(); 965ff0cc061SDimitry Andric // BinOps are only valid for int/fp or vector of int/fp types 966ff0cc061SDimitry Andric if (!IsFP && !Ty->isIntOrIntVectorTy()) 967ff0cc061SDimitry Andric return -1; 968ff0cc061SDimitry Andric 969f22ef01cSRoman Divacky switch (Val) { 970ff0cc061SDimitry Andric default: 971ff0cc061SDimitry Andric return -1; 972f22ef01cSRoman Divacky case bitc::BINOP_ADD: 973ff0cc061SDimitry Andric return IsFP ? Instruction::FAdd : Instruction::Add; 974f22ef01cSRoman Divacky case bitc::BINOP_SUB: 975ff0cc061SDimitry Andric return IsFP ? Instruction::FSub : Instruction::Sub; 976f22ef01cSRoman Divacky case bitc::BINOP_MUL: 977ff0cc061SDimitry Andric return IsFP ? Instruction::FMul : Instruction::Mul; 978ff0cc061SDimitry Andric case bitc::BINOP_UDIV: 979ff0cc061SDimitry Andric return IsFP ? -1 : Instruction::UDiv; 980f22ef01cSRoman Divacky case bitc::BINOP_SDIV: 981ff0cc061SDimitry Andric return IsFP ? Instruction::FDiv : Instruction::SDiv; 982ff0cc061SDimitry Andric case bitc::BINOP_UREM: 983ff0cc061SDimitry Andric return IsFP ? -1 : Instruction::URem; 984f22ef01cSRoman Divacky case bitc::BINOP_SREM: 985ff0cc061SDimitry Andric return IsFP ? Instruction::FRem : Instruction::SRem; 986ff0cc061SDimitry Andric case bitc::BINOP_SHL: 987ff0cc061SDimitry Andric return IsFP ? -1 : Instruction::Shl; 988ff0cc061SDimitry Andric case bitc::BINOP_LSHR: 989ff0cc061SDimitry Andric return IsFP ? -1 : Instruction::LShr; 990ff0cc061SDimitry Andric case bitc::BINOP_ASHR: 991ff0cc061SDimitry Andric return IsFP ? -1 : Instruction::AShr; 992ff0cc061SDimitry Andric case bitc::BINOP_AND: 993ff0cc061SDimitry Andric return IsFP ? -1 : Instruction::And; 994ff0cc061SDimitry Andric case bitc::BINOP_OR: 995ff0cc061SDimitry Andric return IsFP ? -1 : Instruction::Or; 996ff0cc061SDimitry Andric case bitc::BINOP_XOR: 997ff0cc061SDimitry Andric return IsFP ? -1 : Instruction::Xor; 998f22ef01cSRoman Divacky } 999f22ef01cSRoman Divacky } 1000f22ef01cSRoman Divacky 10018f0fd8f6SDimitry Andric static AtomicRMWInst::BinOp getDecodedRMWOperation(unsigned Val) { 10026122f3e6SDimitry Andric switch (Val) { 10036122f3e6SDimitry Andric default: return AtomicRMWInst::BAD_BINOP; 10046122f3e6SDimitry Andric case bitc::RMW_XCHG: return AtomicRMWInst::Xchg; 10056122f3e6SDimitry Andric case bitc::RMW_ADD: return AtomicRMWInst::Add; 10066122f3e6SDimitry Andric case bitc::RMW_SUB: return AtomicRMWInst::Sub; 10076122f3e6SDimitry Andric case bitc::RMW_AND: return AtomicRMWInst::And; 10086122f3e6SDimitry Andric case bitc::RMW_NAND: return AtomicRMWInst::Nand; 10096122f3e6SDimitry Andric case bitc::RMW_OR: return AtomicRMWInst::Or; 10106122f3e6SDimitry Andric case bitc::RMW_XOR: return AtomicRMWInst::Xor; 10116122f3e6SDimitry Andric case bitc::RMW_MAX: return AtomicRMWInst::Max; 10126122f3e6SDimitry Andric case bitc::RMW_MIN: return AtomicRMWInst::Min; 10136122f3e6SDimitry Andric case bitc::RMW_UMAX: return AtomicRMWInst::UMax; 10146122f3e6SDimitry Andric case bitc::RMW_UMIN: return AtomicRMWInst::UMin; 10156122f3e6SDimitry Andric } 10166122f3e6SDimitry Andric } 10176122f3e6SDimitry Andric 10188f0fd8f6SDimitry Andric static AtomicOrdering getDecodedOrdering(unsigned Val) { 10196122f3e6SDimitry Andric switch (Val) { 10203ca95b02SDimitry Andric case bitc::ORDERING_NOTATOMIC: return AtomicOrdering::NotAtomic; 10213ca95b02SDimitry Andric case bitc::ORDERING_UNORDERED: return AtomicOrdering::Unordered; 10223ca95b02SDimitry Andric case bitc::ORDERING_MONOTONIC: return AtomicOrdering::Monotonic; 10233ca95b02SDimitry Andric case bitc::ORDERING_ACQUIRE: return AtomicOrdering::Acquire; 10243ca95b02SDimitry Andric case bitc::ORDERING_RELEASE: return AtomicOrdering::Release; 10253ca95b02SDimitry Andric case bitc::ORDERING_ACQREL: return AtomicOrdering::AcquireRelease; 10266122f3e6SDimitry Andric default: // Map unknown orderings to sequentially-consistent. 10273ca95b02SDimitry Andric case bitc::ORDERING_SEQCST: return AtomicOrdering::SequentiallyConsistent; 10286122f3e6SDimitry Andric } 10296122f3e6SDimitry Andric } 10306122f3e6SDimitry Andric 103191bc56edSDimitry Andric static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val) { 103291bc56edSDimitry Andric switch (Val) { 103391bc56edSDimitry Andric default: // Map unknown selection kinds to any. 103491bc56edSDimitry Andric case bitc::COMDAT_SELECTION_KIND_ANY: 103591bc56edSDimitry Andric return Comdat::Any; 103691bc56edSDimitry Andric case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH: 103791bc56edSDimitry Andric return Comdat::ExactMatch; 103891bc56edSDimitry Andric case bitc::COMDAT_SELECTION_KIND_LARGEST: 103991bc56edSDimitry Andric return Comdat::Largest; 104091bc56edSDimitry Andric case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES: 104191bc56edSDimitry Andric return Comdat::NoDuplicates; 104291bc56edSDimitry Andric case bitc::COMDAT_SELECTION_KIND_SAME_SIZE: 104391bc56edSDimitry Andric return Comdat::SameSize; 104491bc56edSDimitry Andric } 104591bc56edSDimitry Andric } 104691bc56edSDimitry Andric 1047875ed548SDimitry Andric static FastMathFlags getDecodedFastMathFlags(unsigned Val) { 1048875ed548SDimitry Andric FastMathFlags FMF; 10494f8786afSDimitry Andric if (0 != (Val & bitc::UnsafeAlgebra)) 10504f8786afSDimitry Andric FMF.setFast(); 10514f8786afSDimitry Andric if (0 != (Val & bitc::AllowReassoc)) 10522cab237bSDimitry Andric FMF.setAllowReassoc(); 10534f8786afSDimitry Andric if (0 != (Val & bitc::NoNaNs)) 1054875ed548SDimitry Andric FMF.setNoNaNs(); 10554f8786afSDimitry Andric if (0 != (Val & bitc::NoInfs)) 1056875ed548SDimitry Andric FMF.setNoInfs(); 10574f8786afSDimitry Andric if (0 != (Val & bitc::NoSignedZeros)) 1058875ed548SDimitry Andric FMF.setNoSignedZeros(); 10594f8786afSDimitry Andric if (0 != (Val & bitc::AllowReciprocal)) 1060875ed548SDimitry Andric FMF.setAllowReciprocal(); 10614f8786afSDimitry Andric if (0 != (Val & bitc::AllowContract)) 10627a7e6055SDimitry Andric FMF.setAllowContract(true); 10634f8786afSDimitry Andric if (0 != (Val & bitc::ApproxFunc)) 10642cab237bSDimitry Andric FMF.setApproxFunc(); 1065875ed548SDimitry Andric return FMF; 1066875ed548SDimitry Andric } 1067875ed548SDimitry Andric 1068d88c1a5aSDimitry Andric static void upgradeDLLImportExportLinkage(GlobalValue *GV, unsigned Val) { 106991bc56edSDimitry Andric switch (Val) { 107091bc56edSDimitry Andric case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break; 107191bc56edSDimitry Andric case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break; 107291bc56edSDimitry Andric } 107391bc56edSDimitry Andric } 107491bc56edSDimitry Andric 107517a519f9SDimitry Andric Type *BitcodeReader::getTypeByID(unsigned ID) { 107617a519f9SDimitry Andric // The type table size is always specified correctly. 107717a519f9SDimitry Andric if (ID >= TypeList.size()) 107891bc56edSDimitry Andric return nullptr; 1079f22ef01cSRoman Divacky 108017a519f9SDimitry Andric if (Type *Ty = TypeList[ID]) 108117a519f9SDimitry Andric return Ty; 108217a519f9SDimitry Andric 108317a519f9SDimitry Andric // If we have a forward reference, the only possible case is when it is to a 108417a519f9SDimitry Andric // named struct. Just create a placeholder for now. 108539d628a0SDimitry Andric return TypeList[ID] = createIdentifiedStructType(Context); 108639d628a0SDimitry Andric } 108739d628a0SDimitry Andric 108839d628a0SDimitry Andric StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context, 108939d628a0SDimitry Andric StringRef Name) { 109039d628a0SDimitry Andric auto *Ret = StructType::create(Context, Name); 109139d628a0SDimitry Andric IdentifiedStructTypes.push_back(Ret); 109239d628a0SDimitry Andric return Ret; 109339d628a0SDimitry Andric } 109439d628a0SDimitry Andric 109539d628a0SDimitry Andric StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context) { 109639d628a0SDimitry Andric auto *Ret = StructType::create(Context); 109739d628a0SDimitry Andric IdentifiedStructTypes.push_back(Ret); 109839d628a0SDimitry Andric return Ret; 1099f22ef01cSRoman Divacky } 1100f22ef01cSRoman Divacky 1101f22ef01cSRoman Divacky //===----------------------------------------------------------------------===// 1102f22ef01cSRoman Divacky // Functions for parsing blocks from the bitcode file 1103f22ef01cSRoman Divacky //===----------------------------------------------------------------------===// 1104f22ef01cSRoman Divacky 1105d88c1a5aSDimitry Andric static uint64_t getRawAttributeMask(Attribute::AttrKind Val) { 1106d88c1a5aSDimitry Andric switch (Val) { 1107d88c1a5aSDimitry Andric case Attribute::EndAttrKinds: 1108d88c1a5aSDimitry Andric llvm_unreachable("Synthetic enumerators which should never get here"); 1109d88c1a5aSDimitry Andric 1110d88c1a5aSDimitry Andric case Attribute::None: return 0; 1111d88c1a5aSDimitry Andric case Attribute::ZExt: return 1 << 0; 1112d88c1a5aSDimitry Andric case Attribute::SExt: return 1 << 1; 1113d88c1a5aSDimitry Andric case Attribute::NoReturn: return 1 << 2; 1114d88c1a5aSDimitry Andric case Attribute::InReg: return 1 << 3; 1115d88c1a5aSDimitry Andric case Attribute::StructRet: return 1 << 4; 1116d88c1a5aSDimitry Andric case Attribute::NoUnwind: return 1 << 5; 1117d88c1a5aSDimitry Andric case Attribute::NoAlias: return 1 << 6; 1118d88c1a5aSDimitry Andric case Attribute::ByVal: return 1 << 7; 1119d88c1a5aSDimitry Andric case Attribute::Nest: return 1 << 8; 1120d88c1a5aSDimitry Andric case Attribute::ReadNone: return 1 << 9; 1121d88c1a5aSDimitry Andric case Attribute::ReadOnly: return 1 << 10; 1122d88c1a5aSDimitry Andric case Attribute::NoInline: return 1 << 11; 1123d88c1a5aSDimitry Andric case Attribute::AlwaysInline: return 1 << 12; 1124d88c1a5aSDimitry Andric case Attribute::OptimizeForSize: return 1 << 13; 1125d88c1a5aSDimitry Andric case Attribute::StackProtect: return 1 << 14; 1126d88c1a5aSDimitry Andric case Attribute::StackProtectReq: return 1 << 15; 1127d88c1a5aSDimitry Andric case Attribute::Alignment: return 31 << 16; 1128d88c1a5aSDimitry Andric case Attribute::NoCapture: return 1 << 21; 1129d88c1a5aSDimitry Andric case Attribute::NoRedZone: return 1 << 22; 1130d88c1a5aSDimitry Andric case Attribute::NoImplicitFloat: return 1 << 23; 1131d88c1a5aSDimitry Andric case Attribute::Naked: return 1 << 24; 1132d88c1a5aSDimitry Andric case Attribute::InlineHint: return 1 << 25; 1133d88c1a5aSDimitry Andric case Attribute::StackAlignment: return 7 << 26; 1134d88c1a5aSDimitry Andric case Attribute::ReturnsTwice: return 1 << 29; 1135d88c1a5aSDimitry Andric case Attribute::UWTable: return 1 << 30; 1136d88c1a5aSDimitry Andric case Attribute::NonLazyBind: return 1U << 31; 1137d88c1a5aSDimitry Andric case Attribute::SanitizeAddress: return 1ULL << 32; 1138d88c1a5aSDimitry Andric case Attribute::MinSize: return 1ULL << 33; 1139d88c1a5aSDimitry Andric case Attribute::NoDuplicate: return 1ULL << 34; 1140d88c1a5aSDimitry Andric case Attribute::StackProtectStrong: return 1ULL << 35; 1141d88c1a5aSDimitry Andric case Attribute::SanitizeThread: return 1ULL << 36; 1142d88c1a5aSDimitry Andric case Attribute::SanitizeMemory: return 1ULL << 37; 1143d88c1a5aSDimitry Andric case Attribute::NoBuiltin: return 1ULL << 38; 1144d88c1a5aSDimitry Andric case Attribute::Returned: return 1ULL << 39; 1145d88c1a5aSDimitry Andric case Attribute::Cold: return 1ULL << 40; 1146d88c1a5aSDimitry Andric case Attribute::Builtin: return 1ULL << 41; 1147d88c1a5aSDimitry Andric case Attribute::OptimizeNone: return 1ULL << 42; 1148d88c1a5aSDimitry Andric case Attribute::InAlloca: return 1ULL << 43; 1149d88c1a5aSDimitry Andric case Attribute::NonNull: return 1ULL << 44; 1150d88c1a5aSDimitry Andric case Attribute::JumpTable: return 1ULL << 45; 1151d88c1a5aSDimitry Andric case Attribute::Convergent: return 1ULL << 46; 1152d88c1a5aSDimitry Andric case Attribute::SafeStack: return 1ULL << 47; 1153d88c1a5aSDimitry Andric case Attribute::NoRecurse: return 1ULL << 48; 1154d88c1a5aSDimitry Andric case Attribute::InaccessibleMemOnly: return 1ULL << 49; 1155d88c1a5aSDimitry Andric case Attribute::InaccessibleMemOrArgMemOnly: return 1ULL << 50; 1156d88c1a5aSDimitry Andric case Attribute::SwiftSelf: return 1ULL << 51; 1157d88c1a5aSDimitry Andric case Attribute::SwiftError: return 1ULL << 52; 1158d88c1a5aSDimitry Andric case Attribute::WriteOnly: return 1ULL << 53; 1159f37b6182SDimitry Andric case Attribute::Speculatable: return 1ULL << 54; 11602cab237bSDimitry Andric case Attribute::StrictFP: return 1ULL << 55; 11612cab237bSDimitry Andric case Attribute::SanitizeHWAddress: return 1ULL << 56; 1162d88c1a5aSDimitry Andric case Attribute::Dereferenceable: 1163d88c1a5aSDimitry Andric llvm_unreachable("dereferenceable attribute not supported in raw format"); 1164d88c1a5aSDimitry Andric break; 1165d88c1a5aSDimitry Andric case Attribute::DereferenceableOrNull: 1166d88c1a5aSDimitry Andric llvm_unreachable("dereferenceable_or_null attribute not supported in raw " 1167d88c1a5aSDimitry Andric "format"); 1168d88c1a5aSDimitry Andric break; 1169d88c1a5aSDimitry Andric case Attribute::ArgMemOnly: 1170d88c1a5aSDimitry Andric llvm_unreachable("argmemonly attribute not supported in raw format"); 1171d88c1a5aSDimitry Andric break; 1172d88c1a5aSDimitry Andric case Attribute::AllocSize: 1173d88c1a5aSDimitry Andric llvm_unreachable("allocsize not supported in raw format"); 1174d88c1a5aSDimitry Andric break; 1175d88c1a5aSDimitry Andric } 1176d88c1a5aSDimitry Andric llvm_unreachable("Unsupported attribute type"); 1177d88c1a5aSDimitry Andric } 1178d88c1a5aSDimitry Andric 1179d88c1a5aSDimitry Andric static void addRawAttributeValue(AttrBuilder &B, uint64_t Val) { 1180d88c1a5aSDimitry Andric if (!Val) return; 1181d88c1a5aSDimitry Andric 1182d88c1a5aSDimitry Andric for (Attribute::AttrKind I = Attribute::None; I != Attribute::EndAttrKinds; 1183d88c1a5aSDimitry Andric I = Attribute::AttrKind(I + 1)) { 1184d88c1a5aSDimitry Andric if (I == Attribute::Dereferenceable || 1185d88c1a5aSDimitry Andric I == Attribute::DereferenceableOrNull || 1186d88c1a5aSDimitry Andric I == Attribute::ArgMemOnly || 1187d88c1a5aSDimitry Andric I == Attribute::AllocSize) 1188d88c1a5aSDimitry Andric continue; 1189d88c1a5aSDimitry Andric if (uint64_t A = (Val & getRawAttributeMask(I))) { 1190d88c1a5aSDimitry Andric if (I == Attribute::Alignment) 1191d88c1a5aSDimitry Andric B.addAlignmentAttr(1ULL << ((A >> 16) - 1)); 1192d88c1a5aSDimitry Andric else if (I == Attribute::StackAlignment) 1193d88c1a5aSDimitry Andric B.addStackAlignmentAttr(1ULL << ((A >> 26)-1)); 1194d88c1a5aSDimitry Andric else 1195d88c1a5aSDimitry Andric B.addAttribute(I); 1196d88c1a5aSDimitry Andric } 1197d88c1a5aSDimitry Andric } 1198d88c1a5aSDimitry Andric } 1199139f7f9bSDimitry Andric 1200139f7f9bSDimitry Andric /// \brief This fills an AttrBuilder object with the LLVM attributes that have 1201139f7f9bSDimitry Andric /// been decoded from the given integer. This function must stay in sync with 1202139f7f9bSDimitry Andric /// 'encodeLLVMAttributesForBitcode'. 1203139f7f9bSDimitry Andric static void decodeLLVMAttributesForBitcode(AttrBuilder &B, 1204139f7f9bSDimitry Andric uint64_t EncodedAttrs) { 1205139f7f9bSDimitry Andric // FIXME: Remove in 4.0. 1206139f7f9bSDimitry Andric 1207139f7f9bSDimitry Andric // The alignment is stored as a 16-bit raw value from bits 31--16. We shift 1208139f7f9bSDimitry Andric // the bits above 31 down by 11 bits. 1209139f7f9bSDimitry Andric unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16; 1210139f7f9bSDimitry Andric assert((!Alignment || isPowerOf2_32(Alignment)) && 1211139f7f9bSDimitry Andric "Alignment must be a power of two."); 1212139f7f9bSDimitry Andric 1213139f7f9bSDimitry Andric if (Alignment) 1214139f7f9bSDimitry Andric B.addAlignmentAttr(Alignment); 1215d88c1a5aSDimitry Andric addRawAttributeValue(B, ((EncodedAttrs & (0xfffffULL << 32)) >> 11) | 1216139f7f9bSDimitry Andric (EncodedAttrs & 0xffff)); 1217139f7f9bSDimitry Andric } 1218139f7f9bSDimitry Andric 1219d88c1a5aSDimitry Andric Error BitcodeReader::parseAttributeBlock() { 1220f22ef01cSRoman Divacky if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID)) 12218f0fd8f6SDimitry Andric return error("Invalid record"); 1222f22ef01cSRoman Divacky 1223f22ef01cSRoman Divacky if (!MAttributes.empty()) 12248f0fd8f6SDimitry Andric return error("Invalid multiple blocks"); 1225f22ef01cSRoman Divacky 1226f22ef01cSRoman Divacky SmallVector<uint64_t, 64> Record; 1227f22ef01cSRoman Divacky 12287a7e6055SDimitry Andric SmallVector<AttributeList, 8> Attrs; 1229f22ef01cSRoman Divacky 1230f22ef01cSRoman Divacky // Read all the records. 1231d88c1a5aSDimitry Andric while (true) { 1232139f7f9bSDimitry Andric BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 1233139f7f9bSDimitry Andric 1234139f7f9bSDimitry Andric switch (Entry.Kind) { 1235139f7f9bSDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already. 1236139f7f9bSDimitry Andric case BitstreamEntry::Error: 12378f0fd8f6SDimitry Andric return error("Malformed block"); 1238139f7f9bSDimitry Andric case BitstreamEntry::EndBlock: 1239d88c1a5aSDimitry Andric return Error::success(); 1240139f7f9bSDimitry Andric case BitstreamEntry::Record: 1241139f7f9bSDimitry Andric // The interesting case. 1242139f7f9bSDimitry Andric break; 1243f22ef01cSRoman Divacky } 1244f22ef01cSRoman Divacky 1245f22ef01cSRoman Divacky // Read a record. 1246f22ef01cSRoman Divacky Record.clear(); 1247139f7f9bSDimitry Andric switch (Stream.readRecord(Entry.ID, Record)) { 1248f22ef01cSRoman Divacky default: // Default behavior: ignore. 1249f22ef01cSRoman Divacky break; 12502cab237bSDimitry Andric case bitc::PARAMATTR_CODE_ENTRY_OLD: // ENTRY: [paramidx0, attr0, ...] 1251139f7f9bSDimitry Andric // FIXME: Remove in 4.0. 1252f22ef01cSRoman Divacky if (Record.size() & 1) 12538f0fd8f6SDimitry Andric return error("Invalid record"); 1254f22ef01cSRoman Divacky 1255f22ef01cSRoman Divacky for (unsigned i = 0, e = Record.size(); i != e; i += 2) { 1256139f7f9bSDimitry Andric AttrBuilder B; 1257139f7f9bSDimitry Andric decodeLLVMAttributesForBitcode(B, Record[i+1]); 12587a7e6055SDimitry Andric Attrs.push_back(AttributeList::get(Context, Record[i], B)); 1259f22ef01cSRoman Divacky } 1260f22ef01cSRoman Divacky 12617a7e6055SDimitry Andric MAttributes.push_back(AttributeList::get(Context, Attrs)); 1262f22ef01cSRoman Divacky Attrs.clear(); 1263f22ef01cSRoman Divacky break; 12642cab237bSDimitry Andric case bitc::PARAMATTR_CODE_ENTRY: // ENTRY: [attrgrp0, attrgrp1, ...] 1265139f7f9bSDimitry Andric for (unsigned i = 0, e = Record.size(); i != e; ++i) 1266139f7f9bSDimitry Andric Attrs.push_back(MAttributeGroups[Record[i]]); 1267139f7f9bSDimitry Andric 12687a7e6055SDimitry Andric MAttributes.push_back(AttributeList::get(Context, Attrs)); 1269139f7f9bSDimitry Andric Attrs.clear(); 1270139f7f9bSDimitry Andric break; 1271139f7f9bSDimitry Andric } 1272139f7f9bSDimitry Andric } 1273139f7f9bSDimitry Andric } 1274139f7f9bSDimitry Andric 1275f785676fSDimitry Andric // Returns Attribute::None on unrecognized codes. 12768f0fd8f6SDimitry Andric static Attribute::AttrKind getAttrFromCode(uint64_t Code) { 1277f785676fSDimitry Andric switch (Code) { 1278f785676fSDimitry Andric default: 1279f785676fSDimitry Andric return Attribute::None; 1280f785676fSDimitry Andric case bitc::ATTR_KIND_ALIGNMENT: 1281f785676fSDimitry Andric return Attribute::Alignment; 1282f785676fSDimitry Andric case bitc::ATTR_KIND_ALWAYS_INLINE: 1283f785676fSDimitry Andric return Attribute::AlwaysInline; 1284875ed548SDimitry Andric case bitc::ATTR_KIND_ARGMEMONLY: 1285875ed548SDimitry Andric return Attribute::ArgMemOnly; 1286f785676fSDimitry Andric case bitc::ATTR_KIND_BUILTIN: 1287f785676fSDimitry Andric return Attribute::Builtin; 1288f785676fSDimitry Andric case bitc::ATTR_KIND_BY_VAL: 1289f785676fSDimitry Andric return Attribute::ByVal; 129091bc56edSDimitry Andric case bitc::ATTR_KIND_IN_ALLOCA: 129191bc56edSDimitry Andric return Attribute::InAlloca; 1292f785676fSDimitry Andric case bitc::ATTR_KIND_COLD: 1293f785676fSDimitry Andric return Attribute::Cold; 1294ff0cc061SDimitry Andric case bitc::ATTR_KIND_CONVERGENT: 1295ff0cc061SDimitry Andric return Attribute::Convergent; 12967d523365SDimitry Andric case bitc::ATTR_KIND_INACCESSIBLEMEM_ONLY: 12977d523365SDimitry Andric return Attribute::InaccessibleMemOnly; 12987d523365SDimitry Andric case bitc::ATTR_KIND_INACCESSIBLEMEM_OR_ARGMEMONLY: 12997d523365SDimitry Andric return Attribute::InaccessibleMemOrArgMemOnly; 1300f785676fSDimitry Andric case bitc::ATTR_KIND_INLINE_HINT: 1301f785676fSDimitry Andric return Attribute::InlineHint; 1302f785676fSDimitry Andric case bitc::ATTR_KIND_IN_REG: 1303f785676fSDimitry Andric return Attribute::InReg; 130491bc56edSDimitry Andric case bitc::ATTR_KIND_JUMP_TABLE: 130591bc56edSDimitry Andric return Attribute::JumpTable; 1306f785676fSDimitry Andric case bitc::ATTR_KIND_MIN_SIZE: 1307f785676fSDimitry Andric return Attribute::MinSize; 1308f785676fSDimitry Andric case bitc::ATTR_KIND_NAKED: 1309f785676fSDimitry Andric return Attribute::Naked; 1310f785676fSDimitry Andric case bitc::ATTR_KIND_NEST: 1311f785676fSDimitry Andric return Attribute::Nest; 1312f785676fSDimitry Andric case bitc::ATTR_KIND_NO_ALIAS: 1313f785676fSDimitry Andric return Attribute::NoAlias; 1314f785676fSDimitry Andric case bitc::ATTR_KIND_NO_BUILTIN: 1315f785676fSDimitry Andric return Attribute::NoBuiltin; 1316f785676fSDimitry Andric case bitc::ATTR_KIND_NO_CAPTURE: 1317f785676fSDimitry Andric return Attribute::NoCapture; 1318f785676fSDimitry Andric case bitc::ATTR_KIND_NO_DUPLICATE: 1319f785676fSDimitry Andric return Attribute::NoDuplicate; 1320f785676fSDimitry Andric case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT: 1321f785676fSDimitry Andric return Attribute::NoImplicitFloat; 1322f785676fSDimitry Andric case bitc::ATTR_KIND_NO_INLINE: 1323f785676fSDimitry Andric return Attribute::NoInline; 13247d523365SDimitry Andric case bitc::ATTR_KIND_NO_RECURSE: 13257d523365SDimitry Andric return Attribute::NoRecurse; 1326f785676fSDimitry Andric case bitc::ATTR_KIND_NON_LAZY_BIND: 1327f785676fSDimitry Andric return Attribute::NonLazyBind; 132891bc56edSDimitry Andric case bitc::ATTR_KIND_NON_NULL: 132991bc56edSDimitry Andric return Attribute::NonNull; 133091bc56edSDimitry Andric case bitc::ATTR_KIND_DEREFERENCEABLE: 133191bc56edSDimitry Andric return Attribute::Dereferenceable; 1332ff0cc061SDimitry Andric case bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL: 1333ff0cc061SDimitry Andric return Attribute::DereferenceableOrNull; 13343ca95b02SDimitry Andric case bitc::ATTR_KIND_ALLOC_SIZE: 13353ca95b02SDimitry Andric return Attribute::AllocSize; 1336f785676fSDimitry Andric case bitc::ATTR_KIND_NO_RED_ZONE: 1337f785676fSDimitry Andric return Attribute::NoRedZone; 1338f785676fSDimitry Andric case bitc::ATTR_KIND_NO_RETURN: 1339f785676fSDimitry Andric return Attribute::NoReturn; 1340f785676fSDimitry Andric case bitc::ATTR_KIND_NO_UNWIND: 1341f785676fSDimitry Andric return Attribute::NoUnwind; 1342f785676fSDimitry Andric case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE: 1343f785676fSDimitry Andric return Attribute::OptimizeForSize; 1344f785676fSDimitry Andric case bitc::ATTR_KIND_OPTIMIZE_NONE: 1345f785676fSDimitry Andric return Attribute::OptimizeNone; 1346f785676fSDimitry Andric case bitc::ATTR_KIND_READ_NONE: 1347f785676fSDimitry Andric return Attribute::ReadNone; 1348f785676fSDimitry Andric case bitc::ATTR_KIND_READ_ONLY: 1349f785676fSDimitry Andric return Attribute::ReadOnly; 1350f785676fSDimitry Andric case bitc::ATTR_KIND_RETURNED: 1351f785676fSDimitry Andric return Attribute::Returned; 1352f785676fSDimitry Andric case bitc::ATTR_KIND_RETURNS_TWICE: 1353f785676fSDimitry Andric return Attribute::ReturnsTwice; 1354f785676fSDimitry Andric case bitc::ATTR_KIND_S_EXT: 1355f785676fSDimitry Andric return Attribute::SExt; 1356f37b6182SDimitry Andric case bitc::ATTR_KIND_SPECULATABLE: 1357f37b6182SDimitry Andric return Attribute::Speculatable; 1358f785676fSDimitry Andric case bitc::ATTR_KIND_STACK_ALIGNMENT: 1359f785676fSDimitry Andric return Attribute::StackAlignment; 1360f785676fSDimitry Andric case bitc::ATTR_KIND_STACK_PROTECT: 1361f785676fSDimitry Andric return Attribute::StackProtect; 1362f785676fSDimitry Andric case bitc::ATTR_KIND_STACK_PROTECT_REQ: 1363f785676fSDimitry Andric return Attribute::StackProtectReq; 1364f785676fSDimitry Andric case bitc::ATTR_KIND_STACK_PROTECT_STRONG: 1365f785676fSDimitry Andric return Attribute::StackProtectStrong; 13668f0fd8f6SDimitry Andric case bitc::ATTR_KIND_SAFESTACK: 13678f0fd8f6SDimitry Andric return Attribute::SafeStack; 13682cab237bSDimitry Andric case bitc::ATTR_KIND_STRICT_FP: 13692cab237bSDimitry Andric return Attribute::StrictFP; 1370f785676fSDimitry Andric case bitc::ATTR_KIND_STRUCT_RET: 1371f785676fSDimitry Andric return Attribute::StructRet; 1372f785676fSDimitry Andric case bitc::ATTR_KIND_SANITIZE_ADDRESS: 1373f785676fSDimitry Andric return Attribute::SanitizeAddress; 13742cab237bSDimitry Andric case bitc::ATTR_KIND_SANITIZE_HWADDRESS: 13752cab237bSDimitry Andric return Attribute::SanitizeHWAddress; 1376f785676fSDimitry Andric case bitc::ATTR_KIND_SANITIZE_THREAD: 1377f785676fSDimitry Andric return Attribute::SanitizeThread; 1378f785676fSDimitry Andric case bitc::ATTR_KIND_SANITIZE_MEMORY: 1379f785676fSDimitry Andric return Attribute::SanitizeMemory; 13803ca95b02SDimitry Andric case bitc::ATTR_KIND_SWIFT_ERROR: 13813ca95b02SDimitry Andric return Attribute::SwiftError; 13823ca95b02SDimitry Andric case bitc::ATTR_KIND_SWIFT_SELF: 13833ca95b02SDimitry Andric return Attribute::SwiftSelf; 1384f785676fSDimitry Andric case bitc::ATTR_KIND_UW_TABLE: 1385f785676fSDimitry Andric return Attribute::UWTable; 13863ca95b02SDimitry Andric case bitc::ATTR_KIND_WRITEONLY: 13873ca95b02SDimitry Andric return Attribute::WriteOnly; 1388f785676fSDimitry Andric case bitc::ATTR_KIND_Z_EXT: 1389f785676fSDimitry Andric return Attribute::ZExt; 1390f785676fSDimitry Andric } 1391f785676fSDimitry Andric } 1392f785676fSDimitry Andric 1393d88c1a5aSDimitry Andric Error BitcodeReader::parseAlignmentValue(uint64_t Exponent, 1394ff0cc061SDimitry Andric unsigned &Alignment) { 1395ff0cc061SDimitry Andric // Note: Alignment in bitcode files is incremented by 1, so that zero 1396ff0cc061SDimitry Andric // can be used for default alignment. 1397ff0cc061SDimitry Andric if (Exponent > Value::MaxAlignmentExponent + 1) 13988f0fd8f6SDimitry Andric return error("Invalid alignment value"); 1399ff0cc061SDimitry Andric Alignment = (1 << static_cast<unsigned>(Exponent)) >> 1; 1400d88c1a5aSDimitry Andric return Error::success(); 1401ff0cc061SDimitry Andric } 1402ff0cc061SDimitry Andric 1403d88c1a5aSDimitry Andric Error BitcodeReader::parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind) { 14048f0fd8f6SDimitry Andric *Kind = getAttrFromCode(Code); 1405f785676fSDimitry Andric if (*Kind == Attribute::None) 1406d88c1a5aSDimitry Andric return error("Unknown attribute kind (" + Twine(Code) + ")"); 1407d88c1a5aSDimitry Andric return Error::success(); 1408f785676fSDimitry Andric } 1409f785676fSDimitry Andric 1410d88c1a5aSDimitry Andric Error BitcodeReader::parseAttributeGroupBlock() { 1411139f7f9bSDimitry Andric if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID)) 14128f0fd8f6SDimitry Andric return error("Invalid record"); 1413139f7f9bSDimitry Andric 1414139f7f9bSDimitry Andric if (!MAttributeGroups.empty()) 14158f0fd8f6SDimitry Andric return error("Invalid multiple blocks"); 1416139f7f9bSDimitry Andric 1417139f7f9bSDimitry Andric SmallVector<uint64_t, 64> Record; 1418139f7f9bSDimitry Andric 1419139f7f9bSDimitry Andric // Read all the records. 1420d88c1a5aSDimitry Andric while (true) { 1421139f7f9bSDimitry Andric BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 1422139f7f9bSDimitry Andric 1423139f7f9bSDimitry Andric switch (Entry.Kind) { 1424139f7f9bSDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already. 1425139f7f9bSDimitry Andric case BitstreamEntry::Error: 14268f0fd8f6SDimitry Andric return error("Malformed block"); 1427139f7f9bSDimitry Andric case BitstreamEntry::EndBlock: 1428d88c1a5aSDimitry Andric return Error::success(); 1429139f7f9bSDimitry Andric case BitstreamEntry::Record: 1430139f7f9bSDimitry Andric // The interesting case. 1431139f7f9bSDimitry Andric break; 1432139f7f9bSDimitry Andric } 1433139f7f9bSDimitry Andric 1434139f7f9bSDimitry Andric // Read a record. 1435139f7f9bSDimitry Andric Record.clear(); 1436139f7f9bSDimitry Andric switch (Stream.readRecord(Entry.ID, Record)) { 1437139f7f9bSDimitry Andric default: // Default behavior: ignore. 1438139f7f9bSDimitry Andric break; 1439139f7f9bSDimitry Andric case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...] 1440139f7f9bSDimitry Andric if (Record.size() < 3) 14418f0fd8f6SDimitry Andric return error("Invalid record"); 1442139f7f9bSDimitry Andric 1443139f7f9bSDimitry Andric uint64_t GrpID = Record[0]; 1444139f7f9bSDimitry Andric uint64_t Idx = Record[1]; // Index of the object this attribute refers to. 1445139f7f9bSDimitry Andric 1446139f7f9bSDimitry Andric AttrBuilder B; 1447139f7f9bSDimitry Andric for (unsigned i = 2, e = Record.size(); i != e; ++i) { 1448139f7f9bSDimitry Andric if (Record[i] == 0) { // Enum attribute 1449f785676fSDimitry Andric Attribute::AttrKind Kind; 1450d88c1a5aSDimitry Andric if (Error Err = parseAttrKind(Record[++i], &Kind)) 1451d88c1a5aSDimitry Andric return Err; 1452f785676fSDimitry Andric 1453f785676fSDimitry Andric B.addAttribute(Kind); 145491bc56edSDimitry Andric } else if (Record[i] == 1) { // Integer attribute 1455f785676fSDimitry Andric Attribute::AttrKind Kind; 1456d88c1a5aSDimitry Andric if (Error Err = parseAttrKind(Record[++i], &Kind)) 1457d88c1a5aSDimitry Andric return Err; 1458f785676fSDimitry Andric if (Kind == Attribute::Alignment) 1459139f7f9bSDimitry Andric B.addAlignmentAttr(Record[++i]); 146091bc56edSDimitry Andric else if (Kind == Attribute::StackAlignment) 1461139f7f9bSDimitry Andric B.addStackAlignmentAttr(Record[++i]); 146291bc56edSDimitry Andric else if (Kind == Attribute::Dereferenceable) 146391bc56edSDimitry Andric B.addDereferenceableAttr(Record[++i]); 1464ff0cc061SDimitry Andric else if (Kind == Attribute::DereferenceableOrNull) 1465ff0cc061SDimitry Andric B.addDereferenceableOrNullAttr(Record[++i]); 14663ca95b02SDimitry Andric else if (Kind == Attribute::AllocSize) 14673ca95b02SDimitry Andric B.addAllocSizeAttrFromRawRepr(Record[++i]); 1468139f7f9bSDimitry Andric } else { // String attribute 1469139f7f9bSDimitry Andric assert((Record[i] == 3 || Record[i] == 4) && 1470139f7f9bSDimitry Andric "Invalid attribute group entry"); 1471139f7f9bSDimitry Andric bool HasValue = (Record[i++] == 4); 1472139f7f9bSDimitry Andric SmallString<64> KindStr; 1473139f7f9bSDimitry Andric SmallString<64> ValStr; 1474139f7f9bSDimitry Andric 1475139f7f9bSDimitry Andric while (Record[i] != 0 && i != e) 1476139f7f9bSDimitry Andric KindStr += Record[i++]; 1477139f7f9bSDimitry Andric assert(Record[i] == 0 && "Kind string not null terminated"); 1478139f7f9bSDimitry Andric 1479139f7f9bSDimitry Andric if (HasValue) { 1480139f7f9bSDimitry Andric // Has a value associated with it. 1481139f7f9bSDimitry Andric ++i; // Skip the '0' that terminates the "kind" string. 1482139f7f9bSDimitry Andric while (Record[i] != 0 && i != e) 1483139f7f9bSDimitry Andric ValStr += Record[i++]; 1484139f7f9bSDimitry Andric assert(Record[i] == 0 && "Value string not null terminated"); 1485139f7f9bSDimitry Andric } 1486139f7f9bSDimitry Andric 1487139f7f9bSDimitry Andric B.addAttribute(KindStr.str(), ValStr.str()); 1488139f7f9bSDimitry Andric } 1489139f7f9bSDimitry Andric } 1490139f7f9bSDimitry Andric 14917a7e6055SDimitry Andric MAttributeGroups[GrpID] = AttributeList::get(Context, Idx, B); 1492139f7f9bSDimitry Andric break; 1493139f7f9bSDimitry Andric } 1494f22ef01cSRoman Divacky } 1495f22ef01cSRoman Divacky } 1496f22ef01cSRoman Divacky } 1497f22ef01cSRoman Divacky 1498d88c1a5aSDimitry Andric Error BitcodeReader::parseTypeTable() { 149917a519f9SDimitry Andric if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW)) 15008f0fd8f6SDimitry Andric return error("Invalid record"); 1501f22ef01cSRoman Divacky 15028f0fd8f6SDimitry Andric return parseTypeTableBody(); 150317a519f9SDimitry Andric } 150417a519f9SDimitry Andric 1505d88c1a5aSDimitry Andric Error BitcodeReader::parseTypeTableBody() { 1506f22ef01cSRoman Divacky if (!TypeList.empty()) 15078f0fd8f6SDimitry Andric return error("Invalid multiple blocks"); 1508f22ef01cSRoman Divacky 1509f22ef01cSRoman Divacky SmallVector<uint64_t, 64> Record; 1510f22ef01cSRoman Divacky unsigned NumRecords = 0; 1511f22ef01cSRoman Divacky 151217a519f9SDimitry Andric SmallString<64> TypeName; 151317a519f9SDimitry Andric 1514f22ef01cSRoman Divacky // Read all the records for this type table. 1515d88c1a5aSDimitry Andric while (true) { 1516139f7f9bSDimitry Andric BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 1517139f7f9bSDimitry Andric 1518139f7f9bSDimitry Andric switch (Entry.Kind) { 1519139f7f9bSDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already. 1520139f7f9bSDimitry Andric case BitstreamEntry::Error: 15218f0fd8f6SDimitry Andric return error("Malformed block"); 1522139f7f9bSDimitry Andric case BitstreamEntry::EndBlock: 1523f22ef01cSRoman Divacky if (NumRecords != TypeList.size()) 15248f0fd8f6SDimitry Andric return error("Malformed block"); 1525d88c1a5aSDimitry Andric return Error::success(); 1526139f7f9bSDimitry Andric case BitstreamEntry::Record: 1527139f7f9bSDimitry Andric // The interesting case. 1528139f7f9bSDimitry Andric break; 1529f22ef01cSRoman Divacky } 1530f22ef01cSRoman Divacky 1531f22ef01cSRoman Divacky // Read a record. 1532f22ef01cSRoman Divacky Record.clear(); 153391bc56edSDimitry Andric Type *ResultTy = nullptr; 1534139f7f9bSDimitry Andric switch (Stream.readRecord(Entry.ID, Record)) { 1535f785676fSDimitry Andric default: 15368f0fd8f6SDimitry Andric return error("Invalid value"); 1537f22ef01cSRoman Divacky case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries] 1538f22ef01cSRoman Divacky // TYPE_CODE_NUMENTRY contains a count of the number of types in the 1539f22ef01cSRoman Divacky // type list. This allows us to reserve space. 1540f22ef01cSRoman Divacky if (Record.size() < 1) 15418f0fd8f6SDimitry Andric return error("Invalid record"); 154217a519f9SDimitry Andric TypeList.resize(Record[0]); 1543f22ef01cSRoman Divacky continue; 1544f22ef01cSRoman Divacky case bitc::TYPE_CODE_VOID: // VOID 1545f22ef01cSRoman Divacky ResultTy = Type::getVoidTy(Context); 1546f22ef01cSRoman Divacky break; 1547dff0c46cSDimitry Andric case bitc::TYPE_CODE_HALF: // HALF 1548dff0c46cSDimitry Andric ResultTy = Type::getHalfTy(Context); 1549dff0c46cSDimitry Andric break; 1550f22ef01cSRoman Divacky case bitc::TYPE_CODE_FLOAT: // FLOAT 1551f22ef01cSRoman Divacky ResultTy = Type::getFloatTy(Context); 1552f22ef01cSRoman Divacky break; 1553f22ef01cSRoman Divacky case bitc::TYPE_CODE_DOUBLE: // DOUBLE 1554f22ef01cSRoman Divacky ResultTy = Type::getDoubleTy(Context); 1555f22ef01cSRoman Divacky break; 1556f22ef01cSRoman Divacky case bitc::TYPE_CODE_X86_FP80: // X86_FP80 1557f22ef01cSRoman Divacky ResultTy = Type::getX86_FP80Ty(Context); 1558f22ef01cSRoman Divacky break; 1559f22ef01cSRoman Divacky case bitc::TYPE_CODE_FP128: // FP128 1560f22ef01cSRoman Divacky ResultTy = Type::getFP128Ty(Context); 1561f22ef01cSRoman Divacky break; 1562f22ef01cSRoman Divacky case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128 1563f22ef01cSRoman Divacky ResultTy = Type::getPPC_FP128Ty(Context); 1564f22ef01cSRoman Divacky break; 1565f22ef01cSRoman Divacky case bitc::TYPE_CODE_LABEL: // LABEL 1566f22ef01cSRoman Divacky ResultTy = Type::getLabelTy(Context); 1567f22ef01cSRoman Divacky break; 1568f22ef01cSRoman Divacky case bitc::TYPE_CODE_METADATA: // METADATA 1569f22ef01cSRoman Divacky ResultTy = Type::getMetadataTy(Context); 1570f22ef01cSRoman Divacky break; 15712754fe60SDimitry Andric case bitc::TYPE_CODE_X86_MMX: // X86_MMX 15722754fe60SDimitry Andric ResultTy = Type::getX86_MMXTy(Context); 15732754fe60SDimitry Andric break; 15747d523365SDimitry Andric case bitc::TYPE_CODE_TOKEN: // TOKEN 15757d523365SDimitry Andric ResultTy = Type::getTokenTy(Context); 15767d523365SDimitry Andric break; 1577ff0cc061SDimitry Andric case bitc::TYPE_CODE_INTEGER: { // INTEGER: [width] 1578f22ef01cSRoman Divacky if (Record.size() < 1) 15798f0fd8f6SDimitry Andric return error("Invalid record"); 1580f22ef01cSRoman Divacky 1581ff0cc061SDimitry Andric uint64_t NumBits = Record[0]; 1582ff0cc061SDimitry Andric if (NumBits < IntegerType::MIN_INT_BITS || 1583ff0cc061SDimitry Andric NumBits > IntegerType::MAX_INT_BITS) 15848f0fd8f6SDimitry Andric return error("Bitwidth for integer type out of range"); 1585ff0cc061SDimitry Andric ResultTy = IntegerType::get(Context, NumBits); 1586f22ef01cSRoman Divacky break; 1587ff0cc061SDimitry Andric } 1588f22ef01cSRoman Divacky case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or 1589f22ef01cSRoman Divacky // [pointee type, address space] 1590f22ef01cSRoman Divacky if (Record.size() < 1) 15918f0fd8f6SDimitry Andric return error("Invalid record"); 1592f22ef01cSRoman Divacky unsigned AddressSpace = 0; 1593f22ef01cSRoman Divacky if (Record.size() == 2) 1594f22ef01cSRoman Divacky AddressSpace = Record[1]; 159517a519f9SDimitry Andric ResultTy = getTypeByID(Record[0]); 1596ff0cc061SDimitry Andric if (!ResultTy || 1597ff0cc061SDimitry Andric !PointerType::isValidElementType(ResultTy)) 15988f0fd8f6SDimitry Andric return error("Invalid type"); 159917a519f9SDimitry Andric ResultTy = PointerType::get(ResultTy, AddressSpace); 1600f22ef01cSRoman Divacky break; 1601f22ef01cSRoman Divacky } 1602dff0c46cSDimitry Andric case bitc::TYPE_CODE_FUNCTION_OLD: { 16037ae0e2c9SDimitry Andric // FIXME: attrid is dead, remove it in LLVM 4.0 1604f22ef01cSRoman Divacky // FUNCTION: [vararg, attrid, retty, paramty x N] 1605f22ef01cSRoman Divacky if (Record.size() < 3) 16068f0fd8f6SDimitry Andric return error("Invalid record"); 1607dff0c46cSDimitry Andric SmallVector<Type*, 8> ArgTys; 160817a519f9SDimitry Andric for (unsigned i = 3, e = Record.size(); i != e; ++i) { 160917a519f9SDimitry Andric if (Type *T = getTypeByID(Record[i])) 161017a519f9SDimitry Andric ArgTys.push_back(T); 161117a519f9SDimitry Andric else 1612f22ef01cSRoman Divacky break; 1613f22ef01cSRoman Divacky } 161417a519f9SDimitry Andric 161517a519f9SDimitry Andric ResultTy = getTypeByID(Record[2]); 161691bc56edSDimitry Andric if (!ResultTy || ArgTys.size() < Record.size()-3) 16178f0fd8f6SDimitry Andric return error("Invalid type"); 161817a519f9SDimitry Andric 161917a519f9SDimitry Andric ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]); 162017a519f9SDimitry Andric break; 162117a519f9SDimitry Andric } 1622dff0c46cSDimitry Andric case bitc::TYPE_CODE_FUNCTION: { 1623dff0c46cSDimitry Andric // FUNCTION: [vararg, retty, paramty x N] 1624dff0c46cSDimitry Andric if (Record.size() < 2) 16258f0fd8f6SDimitry Andric return error("Invalid record"); 1626dff0c46cSDimitry Andric SmallVector<Type*, 8> ArgTys; 1627dff0c46cSDimitry Andric for (unsigned i = 2, e = Record.size(); i != e; ++i) { 1628ff0cc061SDimitry Andric if (Type *T = getTypeByID(Record[i])) { 1629ff0cc061SDimitry Andric if (!FunctionType::isValidArgumentType(T)) 16308f0fd8f6SDimitry Andric return error("Invalid function argument type"); 1631dff0c46cSDimitry Andric ArgTys.push_back(T); 1632ff0cc061SDimitry Andric } 1633dff0c46cSDimitry Andric else 1634dff0c46cSDimitry Andric break; 1635dff0c46cSDimitry Andric } 1636dff0c46cSDimitry Andric 1637dff0c46cSDimitry Andric ResultTy = getTypeByID(Record[1]); 163891bc56edSDimitry Andric if (!ResultTy || ArgTys.size() < Record.size()-2) 16398f0fd8f6SDimitry Andric return error("Invalid type"); 1640dff0c46cSDimitry Andric 1641dff0c46cSDimitry Andric ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]); 1642dff0c46cSDimitry Andric break; 1643dff0c46cSDimitry Andric } 164417a519f9SDimitry Andric case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N] 1645f22ef01cSRoman Divacky if (Record.size() < 1) 16468f0fd8f6SDimitry Andric return error("Invalid record"); 1647dff0c46cSDimitry 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 type"); 1656f22ef01cSRoman Divacky ResultTy = StructType::get(Context, EltTys, Record[0]); 1657f22ef01cSRoman Divacky break; 1658f22ef01cSRoman Divacky } 165917a519f9SDimitry Andric case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N] 16608f0fd8f6SDimitry Andric if (convertToString(Record, 0, TypeName)) 16618f0fd8f6SDimitry Andric return error("Invalid record"); 166217a519f9SDimitry Andric continue; 166317a519f9SDimitry Andric 166417a519f9SDimitry Andric case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N] 166517a519f9SDimitry Andric if (Record.size() < 1) 16668f0fd8f6SDimitry Andric return error("Invalid record"); 166717a519f9SDimitry Andric 166817a519f9SDimitry Andric if (NumRecords >= TypeList.size()) 16698f0fd8f6SDimitry Andric return error("Invalid TYPE table"); 167017a519f9SDimitry Andric 167117a519f9SDimitry Andric // Check to see if this was forward referenced, if so fill in the temp. 167217a519f9SDimitry Andric StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]); 167317a519f9SDimitry Andric if (Res) { 167417a519f9SDimitry Andric Res->setName(TypeName); 167591bc56edSDimitry Andric TypeList[NumRecords] = nullptr; 167617a519f9SDimitry Andric } else // Otherwise, create a new struct. 167739d628a0SDimitry Andric Res = createIdentifiedStructType(Context, TypeName); 167817a519f9SDimitry Andric TypeName.clear(); 167917a519f9SDimitry Andric 168017a519f9SDimitry Andric SmallVector<Type*, 8> EltTys; 168117a519f9SDimitry Andric for (unsigned i = 1, e = Record.size(); i != e; ++i) { 168217a519f9SDimitry Andric if (Type *T = getTypeByID(Record[i])) 168317a519f9SDimitry Andric EltTys.push_back(T); 168417a519f9SDimitry Andric else 168517a519f9SDimitry Andric break; 168617a519f9SDimitry Andric } 168717a519f9SDimitry Andric if (EltTys.size() != Record.size()-1) 16888f0fd8f6SDimitry Andric return error("Invalid record"); 168917a519f9SDimitry Andric Res->setBody(EltTys, Record[0]); 169017a519f9SDimitry Andric ResultTy = Res; 169117a519f9SDimitry Andric break; 169217a519f9SDimitry Andric } 169317a519f9SDimitry Andric case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: [] 169417a519f9SDimitry Andric if (Record.size() != 1) 16958f0fd8f6SDimitry Andric return error("Invalid record"); 169617a519f9SDimitry Andric 169717a519f9SDimitry Andric if (NumRecords >= TypeList.size()) 16988f0fd8f6SDimitry Andric return error("Invalid TYPE table"); 169917a519f9SDimitry Andric 170017a519f9SDimitry Andric // Check to see if this was forward referenced, if so fill in the temp. 170117a519f9SDimitry Andric StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]); 170217a519f9SDimitry Andric if (Res) { 170317a519f9SDimitry Andric Res->setName(TypeName); 170491bc56edSDimitry Andric TypeList[NumRecords] = nullptr; 170517a519f9SDimitry Andric } else // Otherwise, create a new struct with no body. 170639d628a0SDimitry Andric Res = createIdentifiedStructType(Context, TypeName); 170717a519f9SDimitry Andric TypeName.clear(); 170817a519f9SDimitry Andric ResultTy = Res; 170917a519f9SDimitry Andric break; 171017a519f9SDimitry Andric } 1711f22ef01cSRoman Divacky case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty] 1712f22ef01cSRoman Divacky if (Record.size() < 2) 17138f0fd8f6SDimitry Andric return error("Invalid record"); 1714ff0cc061SDimitry Andric ResultTy = getTypeByID(Record[1]); 1715ff0cc061SDimitry Andric if (!ResultTy || !ArrayType::isValidElementType(ResultTy)) 17168f0fd8f6SDimitry Andric return error("Invalid type"); 1717ff0cc061SDimitry Andric ResultTy = ArrayType::get(ResultTy, Record[0]); 1718f22ef01cSRoman Divacky break; 1719f22ef01cSRoman Divacky case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty] 1720f22ef01cSRoman Divacky if (Record.size() < 2) 17218f0fd8f6SDimitry Andric return error("Invalid record"); 172297bc6c73SDimitry Andric if (Record[0] == 0) 17238f0fd8f6SDimitry Andric return error("Invalid vector length"); 1724ff0cc061SDimitry Andric ResultTy = getTypeByID(Record[1]); 1725ff0cc061SDimitry Andric if (!ResultTy || !StructType::isValidElementType(ResultTy)) 17268f0fd8f6SDimitry Andric return error("Invalid type"); 1727ff0cc061SDimitry Andric ResultTy = VectorType::get(ResultTy, Record[0]); 1728f22ef01cSRoman Divacky break; 1729f22ef01cSRoman Divacky } 1730f22ef01cSRoman Divacky 173117a519f9SDimitry Andric if (NumRecords >= TypeList.size()) 17328f0fd8f6SDimitry Andric return error("Invalid TYPE table"); 1733ff0cc061SDimitry Andric if (TypeList[NumRecords]) 17348f0fd8f6SDimitry Andric return error( 1735ff0cc061SDimitry Andric "Invalid TYPE table: Only named structs can be forward referenced"); 173617a519f9SDimitry Andric assert(ResultTy && "Didn't read a type?"); 173717a519f9SDimitry Andric TypeList[NumRecords++] = ResultTy; 1738f22ef01cSRoman Divacky } 1739f22ef01cSRoman Divacky } 174017a519f9SDimitry Andric 1741d88c1a5aSDimitry Andric Error BitcodeReader::parseOperandBundleTags() { 17427d523365SDimitry Andric if (Stream.EnterSubBlock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID)) 17437d523365SDimitry Andric return error("Invalid record"); 17447d523365SDimitry Andric 17457d523365SDimitry Andric if (!BundleTags.empty()) 17467d523365SDimitry Andric return error("Invalid multiple blocks"); 17477d523365SDimitry Andric 17487d523365SDimitry Andric SmallVector<uint64_t, 64> Record; 17497d523365SDimitry Andric 1750d88c1a5aSDimitry Andric while (true) { 17517d523365SDimitry Andric BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 17527d523365SDimitry Andric 17537d523365SDimitry Andric switch (Entry.Kind) { 17547d523365SDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already. 17557d523365SDimitry Andric case BitstreamEntry::Error: 17567d523365SDimitry Andric return error("Malformed block"); 17577d523365SDimitry Andric case BitstreamEntry::EndBlock: 1758d88c1a5aSDimitry Andric return Error::success(); 17597d523365SDimitry Andric case BitstreamEntry::Record: 17607d523365SDimitry Andric // The interesting case. 17617d523365SDimitry Andric break; 17627d523365SDimitry Andric } 17637d523365SDimitry Andric 17647d523365SDimitry Andric // Tags are implicitly mapped to integers by their order. 17657d523365SDimitry Andric 17667d523365SDimitry Andric if (Stream.readRecord(Entry.ID, Record) != bitc::OPERAND_BUNDLE_TAG) 17677d523365SDimitry Andric return error("Invalid record"); 17687d523365SDimitry Andric 17697d523365SDimitry Andric // OPERAND_BUNDLE_TAG: [strchr x N] 17707d523365SDimitry Andric BundleTags.emplace_back(); 17717d523365SDimitry Andric if (convertToString(Record, 0, BundleTags.back())) 17727d523365SDimitry Andric return error("Invalid record"); 17737d523365SDimitry Andric Record.clear(); 17747d523365SDimitry Andric } 17757d523365SDimitry Andric } 17767d523365SDimitry Andric 1777c4394386SDimitry Andric Error BitcodeReader::parseSyncScopeNames() { 1778c4394386SDimitry Andric if (Stream.EnterSubBlock(bitc::SYNC_SCOPE_NAMES_BLOCK_ID)) 1779c4394386SDimitry Andric return error("Invalid record"); 1780c4394386SDimitry Andric 1781c4394386SDimitry Andric if (!SSIDs.empty()) 1782c4394386SDimitry Andric return error("Invalid multiple synchronization scope names blocks"); 1783c4394386SDimitry Andric 1784c4394386SDimitry Andric SmallVector<uint64_t, 64> Record; 1785c4394386SDimitry Andric while (true) { 1786c4394386SDimitry Andric BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 1787c4394386SDimitry Andric switch (Entry.Kind) { 1788c4394386SDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already. 1789c4394386SDimitry Andric case BitstreamEntry::Error: 1790c4394386SDimitry Andric return error("Malformed block"); 1791c4394386SDimitry Andric case BitstreamEntry::EndBlock: 1792c4394386SDimitry Andric if (SSIDs.empty()) 1793c4394386SDimitry Andric return error("Invalid empty synchronization scope names block"); 1794c4394386SDimitry Andric return Error::success(); 1795c4394386SDimitry Andric case BitstreamEntry::Record: 1796c4394386SDimitry Andric // The interesting case. 1797c4394386SDimitry Andric break; 1798c4394386SDimitry Andric } 1799c4394386SDimitry Andric 1800c4394386SDimitry Andric // Synchronization scope names are implicitly mapped to synchronization 1801c4394386SDimitry Andric // scope IDs by their order. 1802c4394386SDimitry Andric 1803c4394386SDimitry Andric if (Stream.readRecord(Entry.ID, Record) != bitc::SYNC_SCOPE_NAME) 1804c4394386SDimitry Andric return error("Invalid record"); 1805c4394386SDimitry Andric 1806c4394386SDimitry Andric SmallString<16> SSN; 1807c4394386SDimitry Andric if (convertToString(Record, 0, SSN)) 1808c4394386SDimitry Andric return error("Invalid record"); 1809c4394386SDimitry Andric 1810c4394386SDimitry Andric SSIDs.push_back(Context.getOrInsertSyncScopeID(SSN)); 1811c4394386SDimitry Andric Record.clear(); 1812c4394386SDimitry Andric } 1813c4394386SDimitry Andric } 1814c4394386SDimitry Andric 18157d523365SDimitry Andric /// Associate a value with its name from the given index in the provided record. 1816d88c1a5aSDimitry Andric Expected<Value *> BitcodeReader::recordValue(SmallVectorImpl<uint64_t> &Record, 18177d523365SDimitry Andric unsigned NameIndex, Triple &TT) { 18187d523365SDimitry Andric SmallString<128> ValueName; 18197d523365SDimitry Andric if (convertToString(Record, NameIndex, ValueName)) 18207d523365SDimitry Andric return error("Invalid record"); 18217d523365SDimitry Andric unsigned ValueID = Record[0]; 18227d523365SDimitry Andric if (ValueID >= ValueList.size() || !ValueList[ValueID]) 18237d523365SDimitry Andric return error("Invalid record"); 18247d523365SDimitry Andric Value *V = ValueList[ValueID]; 18257d523365SDimitry Andric 18267d523365SDimitry Andric StringRef NameStr(ValueName.data(), ValueName.size()); 18277d523365SDimitry Andric if (NameStr.find_first_of(0) != StringRef::npos) 18287d523365SDimitry Andric return error("Invalid value name"); 18297d523365SDimitry Andric V->setName(NameStr); 18307d523365SDimitry Andric auto *GO = dyn_cast<GlobalObject>(V); 18317d523365SDimitry Andric if (GO) { 18327d523365SDimitry Andric if (GO->getComdat() == reinterpret_cast<Comdat *>(1)) { 18332cab237bSDimitry Andric if (TT.supportsCOMDAT()) 18347d523365SDimitry Andric GO->setComdat(TheModule->getOrInsertComdat(V->getName())); 18352cab237bSDimitry Andric else 18362cab237bSDimitry Andric GO->setComdat(nullptr); 18377d523365SDimitry Andric } 18387d523365SDimitry Andric } 18397d523365SDimitry Andric return V; 18407d523365SDimitry Andric } 18417d523365SDimitry Andric 18423ca95b02SDimitry Andric /// Helper to note and return the current location, and jump to the given 18433ca95b02SDimitry Andric /// offset. 18443ca95b02SDimitry Andric static uint64_t jumpToValueSymbolTable(uint64_t Offset, 18453ca95b02SDimitry Andric BitstreamCursor &Stream) { 18467d523365SDimitry Andric // Save the current parsing location so we can jump back at the end 18477d523365SDimitry Andric // of the VST read. 18483ca95b02SDimitry Andric uint64_t CurrentBit = Stream.GetCurrentBitNo(); 18497d523365SDimitry Andric Stream.JumpToBit(Offset * 32); 18507d523365SDimitry Andric #ifndef NDEBUG 18517d523365SDimitry Andric // Do some checking if we are in debug mode. 18527d523365SDimitry Andric BitstreamEntry Entry = Stream.advance(); 18537d523365SDimitry Andric assert(Entry.Kind == BitstreamEntry::SubBlock); 18547d523365SDimitry Andric assert(Entry.ID == bitc::VALUE_SYMTAB_BLOCK_ID); 18557d523365SDimitry Andric #else 18567d523365SDimitry Andric // In NDEBUG mode ignore the output so we don't get an unused variable 18577d523365SDimitry Andric // warning. 18587d523365SDimitry Andric Stream.advance(); 18597d523365SDimitry Andric #endif 18603ca95b02SDimitry Andric return CurrentBit; 18617d523365SDimitry Andric } 18627d523365SDimitry Andric 18636bc11b14SDimitry Andric void BitcodeReader::setDeferredFunctionInfo(unsigned FuncBitcodeOffsetDelta, 18646bc11b14SDimitry Andric Function *F, 18656bc11b14SDimitry Andric ArrayRef<uint64_t> Record) { 18666bc11b14SDimitry Andric // Note that we subtract 1 here because the offset is relative to one word 18676bc11b14SDimitry Andric // before the start of the identification or module block, which was 18686bc11b14SDimitry Andric // historically always the start of the regular bitcode header. 18696bc11b14SDimitry Andric uint64_t FuncWordOffset = Record[1] - 1; 18706bc11b14SDimitry Andric uint64_t FuncBitOffset = FuncWordOffset * 32; 18716bc11b14SDimitry Andric DeferredFunctionInfo[F] = FuncBitOffset + FuncBitcodeOffsetDelta; 18726bc11b14SDimitry Andric // Set the LastFunctionBlockBit to point to the last function block. 18736bc11b14SDimitry Andric // Later when parsing is resumed after function materialization, 18746bc11b14SDimitry Andric // we can simply skip that last function block. 18756bc11b14SDimitry Andric if (FuncBitOffset > LastFunctionBlockBit) 18766bc11b14SDimitry Andric LastFunctionBlockBit = FuncBitOffset; 18776bc11b14SDimitry Andric } 18786bc11b14SDimitry Andric 18796bc11b14SDimitry Andric /// Read a new-style GlobalValue symbol table. 18806bc11b14SDimitry Andric Error BitcodeReader::parseGlobalValueSymbolTable() { 18816bc11b14SDimitry Andric unsigned FuncBitcodeOffsetDelta = 18826bc11b14SDimitry Andric Stream.getAbbrevIDWidth() + bitc::BlockIDWidth; 18836bc11b14SDimitry Andric 18846bc11b14SDimitry Andric if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID)) 18856bc11b14SDimitry Andric return error("Invalid record"); 18866bc11b14SDimitry Andric 18876bc11b14SDimitry Andric SmallVector<uint64_t, 64> Record; 18886bc11b14SDimitry Andric while (true) { 18896bc11b14SDimitry Andric BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 18906bc11b14SDimitry Andric 18916bc11b14SDimitry Andric switch (Entry.Kind) { 18926bc11b14SDimitry Andric case BitstreamEntry::SubBlock: 18936bc11b14SDimitry Andric case BitstreamEntry::Error: 18946bc11b14SDimitry Andric return error("Malformed block"); 18956bc11b14SDimitry Andric case BitstreamEntry::EndBlock: 18966bc11b14SDimitry Andric return Error::success(); 18976bc11b14SDimitry Andric case BitstreamEntry::Record: 18986bc11b14SDimitry Andric break; 18996bc11b14SDimitry Andric } 19006bc11b14SDimitry Andric 19016bc11b14SDimitry Andric Record.clear(); 19026bc11b14SDimitry Andric switch (Stream.readRecord(Entry.ID, Record)) { 19036bc11b14SDimitry Andric case bitc::VST_CODE_FNENTRY: // [valueid, offset] 19046bc11b14SDimitry Andric setDeferredFunctionInfo(FuncBitcodeOffsetDelta, 19056bc11b14SDimitry Andric cast<Function>(ValueList[Record[0]]), Record); 19066bc11b14SDimitry Andric break; 19076bc11b14SDimitry Andric } 19086bc11b14SDimitry Andric } 19096bc11b14SDimitry Andric } 19106bc11b14SDimitry Andric 19113ca95b02SDimitry Andric /// Parse the value symbol table at either the current parsing location or 19123ca95b02SDimitry Andric /// at the given bit offset if provided. 1913d88c1a5aSDimitry Andric Error BitcodeReader::parseValueSymbolTable(uint64_t Offset) { 19143ca95b02SDimitry Andric uint64_t CurrentBit; 19153ca95b02SDimitry Andric // Pass in the Offset to distinguish between calling for the module-level 19163ca95b02SDimitry Andric // VST (where we want to jump to the VST offset) and the function-level 19173ca95b02SDimitry Andric // VST (where we don't). 19186bc11b14SDimitry Andric if (Offset > 0) { 19193ca95b02SDimitry Andric CurrentBit = jumpToValueSymbolTable(Offset, Stream); 19206bc11b14SDimitry Andric // If this module uses a string table, read this as a module-level VST. 19216bc11b14SDimitry Andric if (UseStrtab) { 19226bc11b14SDimitry Andric if (Error Err = parseGlobalValueSymbolTable()) 19236bc11b14SDimitry Andric return Err; 19246bc11b14SDimitry Andric Stream.JumpToBit(CurrentBit); 19256bc11b14SDimitry Andric return Error::success(); 19266bc11b14SDimitry Andric } 19276bc11b14SDimitry Andric // Otherwise, the VST will be in a similar format to a function-level VST, 19286bc11b14SDimitry Andric // and will contain symbol names. 19296bc11b14SDimitry Andric } 19303ca95b02SDimitry Andric 19317d523365SDimitry Andric // Compute the delta between the bitcode indices in the VST (the word offset 19327d523365SDimitry Andric // to the word-aligned ENTER_SUBBLOCK for the function block, and that 19337d523365SDimitry Andric // expected by the lazy reader. The reader's EnterSubBlock expects to have 19347d523365SDimitry Andric // already read the ENTER_SUBBLOCK code (size getAbbrevIDWidth) and BlockID 19357d523365SDimitry Andric // (size BlockIDWidth). Note that we access the stream's AbbrevID width here 19367d523365SDimitry Andric // just before entering the VST subblock because: 1) the EnterSubBlock 19377d523365SDimitry Andric // changes the AbbrevID width; 2) the VST block is nested within the same 19387d523365SDimitry Andric // outer MODULE_BLOCK as the FUNCTION_BLOCKs and therefore have the same 19397d523365SDimitry Andric // AbbrevID width before calling EnterSubBlock; and 3) when we want to 19407d523365SDimitry Andric // jump to the FUNCTION_BLOCK using this offset later, we don't want 19417d523365SDimitry Andric // to rely on the stream's AbbrevID width being that of the MODULE_BLOCK. 19427d523365SDimitry Andric unsigned FuncBitcodeOffsetDelta = 19437d523365SDimitry Andric Stream.getAbbrevIDWidth() + bitc::BlockIDWidth; 19447d523365SDimitry Andric 1945f22ef01cSRoman Divacky if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID)) 19468f0fd8f6SDimitry Andric return error("Invalid record"); 1947f22ef01cSRoman Divacky 1948f22ef01cSRoman Divacky SmallVector<uint64_t, 64> Record; 1949f22ef01cSRoman Divacky 1950ff0cc061SDimitry Andric Triple TT(TheModule->getTargetTriple()); 1951ff0cc061SDimitry Andric 1952f22ef01cSRoman Divacky // Read all the records for this value table. 1953f22ef01cSRoman Divacky SmallString<128> ValueName; 1954d88c1a5aSDimitry Andric 1955d88c1a5aSDimitry Andric while (true) { 1956139f7f9bSDimitry Andric BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 1957f22ef01cSRoman Divacky 1958139f7f9bSDimitry Andric switch (Entry.Kind) { 1959139f7f9bSDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already. 1960139f7f9bSDimitry Andric case BitstreamEntry::Error: 19618f0fd8f6SDimitry Andric return error("Malformed block"); 1962139f7f9bSDimitry Andric case BitstreamEntry::EndBlock: 19637d523365SDimitry Andric if (Offset > 0) 19647d523365SDimitry Andric Stream.JumpToBit(CurrentBit); 1965d88c1a5aSDimitry Andric return Error::success(); 1966139f7f9bSDimitry Andric case BitstreamEntry::Record: 1967139f7f9bSDimitry Andric // The interesting case. 1968139f7f9bSDimitry Andric break; 1969f22ef01cSRoman Divacky } 1970f22ef01cSRoman Divacky 1971f22ef01cSRoman Divacky // Read a record. 1972f22ef01cSRoman Divacky Record.clear(); 1973139f7f9bSDimitry Andric switch (Stream.readRecord(Entry.ID, Record)) { 1974f22ef01cSRoman Divacky default: // Default behavior: unknown type. 1975f22ef01cSRoman Divacky break; 19763ca95b02SDimitry Andric case bitc::VST_CODE_ENTRY: { // VST_CODE_ENTRY: [valueid, namechar x N] 1977d88c1a5aSDimitry Andric Expected<Value *> ValOrErr = recordValue(Record, 1, TT); 1978d88c1a5aSDimitry Andric if (Error Err = ValOrErr.takeError()) 1979d88c1a5aSDimitry Andric return Err; 19807d523365SDimitry Andric ValOrErr.get(); 19817d523365SDimitry Andric break; 19827d523365SDimitry Andric } 19837d523365SDimitry Andric case bitc::VST_CODE_FNENTRY: { 19843ca95b02SDimitry Andric // VST_CODE_FNENTRY: [valueid, offset, namechar x N] 1985d88c1a5aSDimitry Andric Expected<Value *> ValOrErr = recordValue(Record, 2, TT); 1986d88c1a5aSDimitry Andric if (Error Err = ValOrErr.takeError()) 1987d88c1a5aSDimitry Andric return Err; 19887d523365SDimitry Andric Value *V = ValOrErr.get(); 1989f22ef01cSRoman Divacky 19907a7e6055SDimitry Andric // Ignore function offsets emitted for aliases of functions in older 19917a7e6055SDimitry Andric // versions of LLVM. 19926bc11b14SDimitry Andric if (auto *F = dyn_cast<Function>(V)) 19936bc11b14SDimitry Andric setDeferredFunctionInfo(FuncBitcodeOffsetDelta, F, Record); 1994f22ef01cSRoman Divacky break; 1995f22ef01cSRoman Divacky } 1996f22ef01cSRoman Divacky case bitc::VST_CODE_BBENTRY: { 19978f0fd8f6SDimitry Andric if (convertToString(Record, 1, ValueName)) 19988f0fd8f6SDimitry Andric return error("Invalid record"); 1999f22ef01cSRoman Divacky BasicBlock *BB = getBasicBlock(Record[0]); 200091bc56edSDimitry Andric if (!BB) 20018f0fd8f6SDimitry Andric return error("Invalid record"); 2002f22ef01cSRoman Divacky 2003f22ef01cSRoman Divacky BB->setName(StringRef(ValueName.data(), ValueName.size())); 2004f22ef01cSRoman Divacky ValueName.clear(); 2005f22ef01cSRoman Divacky break; 2006f22ef01cSRoman Divacky } 2007f22ef01cSRoman Divacky } 2008f22ef01cSRoman Divacky } 2009f22ef01cSRoman Divacky } 2010f22ef01cSRoman Divacky 20118f0fd8f6SDimitry Andric /// Decode a signed value stored with the sign bit in the LSB for dense VBR 20128f0fd8f6SDimitry Andric /// encoding. 20133861d79fSDimitry Andric uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) { 2014f22ef01cSRoman Divacky if ((V & 1) == 0) 2015f22ef01cSRoman Divacky return V >> 1; 2016f22ef01cSRoman Divacky if (V != 1) 2017f22ef01cSRoman Divacky return -(V >> 1); 2018f22ef01cSRoman Divacky // There is no such thing as -0 with integers. "-0" really means MININT. 2019f22ef01cSRoman Divacky return 1ULL << 63; 2020f22ef01cSRoman Divacky } 2021f22ef01cSRoman Divacky 20228f0fd8f6SDimitry Andric /// Resolve all of the initializers for global values and aliases that we can. 2023d88c1a5aSDimitry Andric Error BitcodeReader::resolveGlobalAndIndirectSymbolInits() { 2024f22ef01cSRoman Divacky std::vector<std::pair<GlobalVariable *, unsigned>> GlobalInitWorklist; 20253ca95b02SDimitry Andric std::vector<std::pair<GlobalIndirectSymbol *, unsigned>> 20263ca95b02SDimitry Andric IndirectSymbolInitWorklist; 2027f785676fSDimitry Andric std::vector<std::pair<Function *, unsigned>> FunctionPrefixWorklist; 202839d628a0SDimitry Andric std::vector<std::pair<Function *, unsigned>> FunctionPrologueWorklist; 20298f0fd8f6SDimitry Andric std::vector<std::pair<Function *, unsigned>> FunctionPersonalityFnWorklist; 2030f22ef01cSRoman Divacky 2031f22ef01cSRoman Divacky GlobalInitWorklist.swap(GlobalInits); 20323ca95b02SDimitry Andric IndirectSymbolInitWorklist.swap(IndirectSymbolInits); 2033f785676fSDimitry Andric FunctionPrefixWorklist.swap(FunctionPrefixes); 203439d628a0SDimitry Andric FunctionPrologueWorklist.swap(FunctionPrologues); 20358f0fd8f6SDimitry Andric FunctionPersonalityFnWorklist.swap(FunctionPersonalityFns); 2036f22ef01cSRoman Divacky 2037f22ef01cSRoman Divacky while (!GlobalInitWorklist.empty()) { 2038f22ef01cSRoman Divacky unsigned ValID = GlobalInitWorklist.back().second; 2039f22ef01cSRoman Divacky if (ValID >= ValueList.size()) { 2040f22ef01cSRoman Divacky // Not ready to resolve this yet, it requires something later in the file. 2041f22ef01cSRoman Divacky GlobalInits.push_back(GlobalInitWorklist.back()); 2042f22ef01cSRoman Divacky } else { 204391bc56edSDimitry Andric if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID])) 2044f22ef01cSRoman Divacky GlobalInitWorklist.back().first->setInitializer(C); 2045f22ef01cSRoman Divacky else 20468f0fd8f6SDimitry Andric return error("Expected a constant"); 2047f22ef01cSRoman Divacky } 2048f22ef01cSRoman Divacky GlobalInitWorklist.pop_back(); 2049f22ef01cSRoman Divacky } 2050f22ef01cSRoman Divacky 20513ca95b02SDimitry Andric while (!IndirectSymbolInitWorklist.empty()) { 20523ca95b02SDimitry Andric unsigned ValID = IndirectSymbolInitWorklist.back().second; 2053f22ef01cSRoman Divacky if (ValID >= ValueList.size()) { 20543ca95b02SDimitry Andric IndirectSymbolInits.push_back(IndirectSymbolInitWorklist.back()); 2055f22ef01cSRoman Divacky } else { 205697bc6c73SDimitry Andric Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]); 205797bc6c73SDimitry Andric if (!C) 20588f0fd8f6SDimitry Andric return error("Expected a constant"); 20593ca95b02SDimitry Andric GlobalIndirectSymbol *GIS = IndirectSymbolInitWorklist.back().first; 20603ca95b02SDimitry Andric if (isa<GlobalAlias>(GIS) && C->getType() != GIS->getType()) 20618f0fd8f6SDimitry Andric return error("Alias and aliasee types don't match"); 20623ca95b02SDimitry Andric GIS->setIndirectSymbol(C); 2063f22ef01cSRoman Divacky } 20643ca95b02SDimitry Andric IndirectSymbolInitWorklist.pop_back(); 2065f22ef01cSRoman Divacky } 2066f785676fSDimitry Andric 2067f785676fSDimitry Andric while (!FunctionPrefixWorklist.empty()) { 2068f785676fSDimitry Andric unsigned ValID = FunctionPrefixWorklist.back().second; 2069f785676fSDimitry Andric if (ValID >= ValueList.size()) { 2070f785676fSDimitry Andric FunctionPrefixes.push_back(FunctionPrefixWorklist.back()); 2071f785676fSDimitry Andric } else { 207291bc56edSDimitry Andric if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID])) 2073f785676fSDimitry Andric FunctionPrefixWorklist.back().first->setPrefixData(C); 2074f785676fSDimitry Andric else 20758f0fd8f6SDimitry Andric return error("Expected a constant"); 2076f785676fSDimitry Andric } 2077f785676fSDimitry Andric FunctionPrefixWorklist.pop_back(); 2078f785676fSDimitry Andric } 2079f785676fSDimitry Andric 208039d628a0SDimitry Andric while (!FunctionPrologueWorklist.empty()) { 208139d628a0SDimitry Andric unsigned ValID = FunctionPrologueWorklist.back().second; 208239d628a0SDimitry Andric if (ValID >= ValueList.size()) { 208339d628a0SDimitry Andric FunctionPrologues.push_back(FunctionPrologueWorklist.back()); 208439d628a0SDimitry Andric } else { 208539d628a0SDimitry Andric if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID])) 208639d628a0SDimitry Andric FunctionPrologueWorklist.back().first->setPrologueData(C); 208739d628a0SDimitry Andric else 20888f0fd8f6SDimitry Andric return error("Expected a constant"); 208939d628a0SDimitry Andric } 209039d628a0SDimitry Andric FunctionPrologueWorklist.pop_back(); 209139d628a0SDimitry Andric } 209239d628a0SDimitry Andric 20938f0fd8f6SDimitry Andric while (!FunctionPersonalityFnWorklist.empty()) { 20948f0fd8f6SDimitry Andric unsigned ValID = FunctionPersonalityFnWorklist.back().second; 20958f0fd8f6SDimitry Andric if (ValID >= ValueList.size()) { 20968f0fd8f6SDimitry Andric FunctionPersonalityFns.push_back(FunctionPersonalityFnWorklist.back()); 20978f0fd8f6SDimitry Andric } else { 20988f0fd8f6SDimitry Andric if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID])) 20998f0fd8f6SDimitry Andric FunctionPersonalityFnWorklist.back().first->setPersonalityFn(C); 21008f0fd8f6SDimitry Andric else 21018f0fd8f6SDimitry Andric return error("Expected a constant"); 21028f0fd8f6SDimitry Andric } 21038f0fd8f6SDimitry Andric FunctionPersonalityFnWorklist.pop_back(); 21048f0fd8f6SDimitry Andric } 21058f0fd8f6SDimitry Andric 2106d88c1a5aSDimitry Andric return Error::success(); 2107f22ef01cSRoman Divacky } 2108f22ef01cSRoman Divacky 21098f0fd8f6SDimitry Andric static APInt readWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) { 21107ae0e2c9SDimitry Andric SmallVector<uint64_t, 8> Words(Vals.size()); 2111d88c1a5aSDimitry Andric transform(Vals, Words.begin(), 21123861d79fSDimitry Andric BitcodeReader::decodeSignRotatedValue); 21137ae0e2c9SDimitry Andric 21147ae0e2c9SDimitry Andric return APInt(TypeBits, Words); 21157ae0e2c9SDimitry Andric } 21167ae0e2c9SDimitry Andric 2117d88c1a5aSDimitry Andric Error BitcodeReader::parseConstants() { 2118f22ef01cSRoman Divacky if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID)) 21198f0fd8f6SDimitry Andric return error("Invalid record"); 2120f22ef01cSRoman Divacky 2121f22ef01cSRoman Divacky SmallVector<uint64_t, 64> Record; 2122f22ef01cSRoman Divacky 2123f22ef01cSRoman Divacky // Read all the records for this value table. 21246122f3e6SDimitry Andric Type *CurTy = Type::getInt32Ty(Context); 2125f22ef01cSRoman Divacky unsigned NextCstNo = ValueList.size(); 2126d88c1a5aSDimitry Andric 2127d88c1a5aSDimitry Andric while (true) { 2128139f7f9bSDimitry Andric BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 2129139f7f9bSDimitry Andric 2130139f7f9bSDimitry Andric switch (Entry.Kind) { 2131139f7f9bSDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already. 2132139f7f9bSDimitry Andric case BitstreamEntry::Error: 21338f0fd8f6SDimitry Andric return error("Malformed block"); 2134139f7f9bSDimitry Andric case BitstreamEntry::EndBlock: 2135139f7f9bSDimitry Andric if (NextCstNo != ValueList.size()) 21363ca95b02SDimitry Andric return error("Invalid constant reference"); 2137139f7f9bSDimitry Andric 2138139f7f9bSDimitry Andric // Once all the constants have been read, go through and resolve forward 2139139f7f9bSDimitry Andric // references. 21408f0fd8f6SDimitry Andric ValueList.resolveConstantForwardRefs(); 2141d88c1a5aSDimitry Andric return Error::success(); 2142139f7f9bSDimitry Andric case BitstreamEntry::Record: 2143139f7f9bSDimitry Andric // The interesting case. 2144f22ef01cSRoman Divacky break; 2145f22ef01cSRoman Divacky } 2146f22ef01cSRoman Divacky 2147f22ef01cSRoman Divacky // Read a record. 2148f22ef01cSRoman Divacky Record.clear(); 21493ca95b02SDimitry Andric Type *VoidType = Type::getVoidTy(Context); 215091bc56edSDimitry Andric Value *V = nullptr; 2151139f7f9bSDimitry Andric unsigned BitCode = Stream.readRecord(Entry.ID, Record); 2152f22ef01cSRoman Divacky switch (BitCode) { 2153f22ef01cSRoman Divacky default: // Default behavior: unknown constant 2154f22ef01cSRoman Divacky case bitc::CST_CODE_UNDEF: // UNDEF 2155f22ef01cSRoman Divacky V = UndefValue::get(CurTy); 2156f22ef01cSRoman Divacky break; 2157f22ef01cSRoman Divacky case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid] 2158f22ef01cSRoman Divacky if (Record.empty()) 21598f0fd8f6SDimitry Andric return error("Invalid record"); 216091bc56edSDimitry Andric if (Record[0] >= TypeList.size() || !TypeList[Record[0]]) 21618f0fd8f6SDimitry Andric return error("Invalid record"); 21623ca95b02SDimitry Andric if (TypeList[Record[0]] == VoidType) 21633ca95b02SDimitry Andric return error("Invalid constant type"); 2164f22ef01cSRoman Divacky CurTy = TypeList[Record[0]]; 2165f22ef01cSRoman Divacky continue; // Skip the ValueList manipulation. 2166f22ef01cSRoman Divacky case bitc::CST_CODE_NULL: // NULL 2167f22ef01cSRoman Divacky V = Constant::getNullValue(CurTy); 2168f22ef01cSRoman Divacky break; 2169f22ef01cSRoman Divacky case bitc::CST_CODE_INTEGER: // INTEGER: [intval] 2170f22ef01cSRoman Divacky if (!CurTy->isIntegerTy() || Record.empty()) 21718f0fd8f6SDimitry Andric return error("Invalid record"); 21723861d79fSDimitry Andric V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0])); 2173f22ef01cSRoman Divacky break; 2174f22ef01cSRoman Divacky case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval] 2175f22ef01cSRoman Divacky if (!CurTy->isIntegerTy() || Record.empty()) 21768f0fd8f6SDimitry Andric return error("Invalid record"); 2177f22ef01cSRoman Divacky 21788f0fd8f6SDimitry Andric APInt VInt = 21798f0fd8f6SDimitry Andric readWideAPInt(Record, cast<IntegerType>(CurTy)->getBitWidth()); 21807ae0e2c9SDimitry Andric V = ConstantInt::get(Context, VInt); 21817ae0e2c9SDimitry Andric 2182f22ef01cSRoman Divacky break; 2183f22ef01cSRoman Divacky } 2184f22ef01cSRoman Divacky case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval] 2185f22ef01cSRoman Divacky if (Record.empty()) 21868f0fd8f6SDimitry Andric return error("Invalid record"); 2187dff0c46cSDimitry Andric if (CurTy->isHalfTy()) 2188d88c1a5aSDimitry Andric V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf(), 2189139f7f9bSDimitry Andric APInt(16, (uint16_t)Record[0]))); 2190dff0c46cSDimitry Andric else if (CurTy->isFloatTy()) 2191d88c1a5aSDimitry Andric V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle(), 2192139f7f9bSDimitry Andric APInt(32, (uint32_t)Record[0]))); 2193f22ef01cSRoman Divacky else if (CurTy->isDoubleTy()) 2194d88c1a5aSDimitry Andric V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble(), 2195139f7f9bSDimitry Andric APInt(64, Record[0]))); 2196f22ef01cSRoman Divacky else if (CurTy->isX86_FP80Ty()) { 2197f22ef01cSRoman Divacky // Bits are not stored the same way as a normal i80 APInt, compensate. 2198f22ef01cSRoman Divacky uint64_t Rearrange[2]; 2199f22ef01cSRoman Divacky Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16); 2200f22ef01cSRoman Divacky Rearrange[1] = Record[0] >> 48; 2201d88c1a5aSDimitry Andric V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended(), 2202139f7f9bSDimitry Andric APInt(80, Rearrange))); 2203f22ef01cSRoman Divacky } else if (CurTy->isFP128Ty()) 2204d88c1a5aSDimitry Andric V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad(), 2205139f7f9bSDimitry Andric APInt(128, Record))); 2206f22ef01cSRoman Divacky else if (CurTy->isPPC_FP128Ty()) 2207d88c1a5aSDimitry Andric V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble(), 2208139f7f9bSDimitry Andric APInt(128, Record))); 2209f22ef01cSRoman Divacky else 2210f22ef01cSRoman Divacky V = UndefValue::get(CurTy); 2211f22ef01cSRoman Divacky break; 2212f22ef01cSRoman Divacky } 2213f22ef01cSRoman Divacky 2214f22ef01cSRoman Divacky case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number] 2215f22ef01cSRoman Divacky if (Record.empty()) 22168f0fd8f6SDimitry Andric return error("Invalid record"); 2217f22ef01cSRoman Divacky 2218f22ef01cSRoman Divacky unsigned Size = Record.size(); 2219dff0c46cSDimitry Andric SmallVector<Constant*, 16> Elts; 2220f22ef01cSRoman Divacky 22216122f3e6SDimitry Andric if (StructType *STy = dyn_cast<StructType>(CurTy)) { 2222f22ef01cSRoman Divacky for (unsigned i = 0; i != Size; ++i) 2223f22ef01cSRoman Divacky Elts.push_back(ValueList.getConstantFwdRef(Record[i], 2224f22ef01cSRoman Divacky STy->getElementType(i))); 2225f22ef01cSRoman Divacky V = ConstantStruct::get(STy, Elts); 22266122f3e6SDimitry Andric } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) { 22276122f3e6SDimitry Andric Type *EltTy = ATy->getElementType(); 2228f22ef01cSRoman Divacky for (unsigned i = 0; i != Size; ++i) 2229f22ef01cSRoman Divacky Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy)); 2230f22ef01cSRoman Divacky V = ConstantArray::get(ATy, Elts); 22316122f3e6SDimitry Andric } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) { 22326122f3e6SDimitry Andric Type *EltTy = VTy->getElementType(); 2233f22ef01cSRoman Divacky for (unsigned i = 0; i != Size; ++i) 2234f22ef01cSRoman Divacky Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy)); 2235f22ef01cSRoman Divacky V = ConstantVector::get(Elts); 2236f22ef01cSRoman Divacky } else { 2237f22ef01cSRoman Divacky V = UndefValue::get(CurTy); 2238f22ef01cSRoman Divacky } 2239f22ef01cSRoman Divacky break; 2240f22ef01cSRoman Divacky } 2241dff0c46cSDimitry Andric case bitc::CST_CODE_STRING: // STRING: [values] 2242f22ef01cSRoman Divacky case bitc::CST_CODE_CSTRING: { // CSTRING: [values] 2243f22ef01cSRoman Divacky if (Record.empty()) 22448f0fd8f6SDimitry Andric return error("Invalid record"); 2245f22ef01cSRoman Divacky 22467ae0e2c9SDimitry Andric SmallString<16> Elts(Record.begin(), Record.end()); 2247dff0c46cSDimitry Andric V = ConstantDataArray::getString(Context, Elts, 2248dff0c46cSDimitry Andric BitCode == bitc::CST_CODE_CSTRING); 2249f22ef01cSRoman Divacky break; 2250f22ef01cSRoman Divacky } 2251dff0c46cSDimitry Andric case bitc::CST_CODE_DATA: {// DATA: [n x value] 2252dff0c46cSDimitry Andric if (Record.empty()) 22538f0fd8f6SDimitry Andric return error("Invalid record"); 2254dff0c46cSDimitry Andric 2255dff0c46cSDimitry Andric Type *EltTy = cast<SequentialType>(CurTy)->getElementType(); 2256dff0c46cSDimitry Andric if (EltTy->isIntegerTy(8)) { 2257dff0c46cSDimitry Andric SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end()); 2258dff0c46cSDimitry Andric if (isa<VectorType>(CurTy)) 2259dff0c46cSDimitry Andric V = ConstantDataVector::get(Context, Elts); 2260dff0c46cSDimitry Andric else 2261dff0c46cSDimitry Andric V = ConstantDataArray::get(Context, Elts); 2262dff0c46cSDimitry Andric } else if (EltTy->isIntegerTy(16)) { 2263dff0c46cSDimitry Andric SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end()); 2264dff0c46cSDimitry Andric if (isa<VectorType>(CurTy)) 2265dff0c46cSDimitry Andric V = ConstantDataVector::get(Context, Elts); 2266dff0c46cSDimitry Andric else 2267dff0c46cSDimitry Andric V = ConstantDataArray::get(Context, Elts); 2268dff0c46cSDimitry Andric } else if (EltTy->isIntegerTy(32)) { 2269dff0c46cSDimitry Andric SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end()); 2270dff0c46cSDimitry Andric if (isa<VectorType>(CurTy)) 2271dff0c46cSDimitry Andric V = ConstantDataVector::get(Context, Elts); 2272dff0c46cSDimitry Andric else 2273dff0c46cSDimitry Andric V = ConstantDataArray::get(Context, Elts); 2274dff0c46cSDimitry Andric } else if (EltTy->isIntegerTy(64)) { 2275dff0c46cSDimitry Andric SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end()); 2276dff0c46cSDimitry Andric if (isa<VectorType>(CurTy)) 2277dff0c46cSDimitry Andric V = ConstantDataVector::get(Context, Elts); 2278dff0c46cSDimitry Andric else 2279dff0c46cSDimitry Andric V = ConstantDataArray::get(Context, Elts); 2280444ed5c5SDimitry Andric } else if (EltTy->isHalfTy()) { 2281444ed5c5SDimitry Andric SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end()); 2282444ed5c5SDimitry Andric if (isa<VectorType>(CurTy)) 2283444ed5c5SDimitry Andric V = ConstantDataVector::getFP(Context, Elts); 2284444ed5c5SDimitry Andric else 2285444ed5c5SDimitry Andric V = ConstantDataArray::getFP(Context, Elts); 2286dff0c46cSDimitry Andric } else if (EltTy->isFloatTy()) { 2287444ed5c5SDimitry Andric SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end()); 2288dff0c46cSDimitry Andric if (isa<VectorType>(CurTy)) 2289444ed5c5SDimitry Andric V = ConstantDataVector::getFP(Context, Elts); 2290dff0c46cSDimitry Andric else 2291444ed5c5SDimitry Andric V = ConstantDataArray::getFP(Context, Elts); 2292dff0c46cSDimitry Andric } else if (EltTy->isDoubleTy()) { 2293444ed5c5SDimitry Andric SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end()); 2294dff0c46cSDimitry Andric if (isa<VectorType>(CurTy)) 2295444ed5c5SDimitry Andric V = ConstantDataVector::getFP(Context, Elts); 2296dff0c46cSDimitry Andric else 2297444ed5c5SDimitry Andric V = ConstantDataArray::getFP(Context, Elts); 2298dff0c46cSDimitry Andric } else { 22998f0fd8f6SDimitry Andric return error("Invalid type for value"); 2300dff0c46cSDimitry Andric } 2301dff0c46cSDimitry Andric break; 2302dff0c46cSDimitry Andric } 2303f22ef01cSRoman Divacky case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval] 2304f785676fSDimitry Andric if (Record.size() < 3) 23058f0fd8f6SDimitry Andric return error("Invalid record"); 23068f0fd8f6SDimitry Andric int Opc = getDecodedBinaryOpcode(Record[0], CurTy); 2307f22ef01cSRoman Divacky if (Opc < 0) { 2308f22ef01cSRoman Divacky V = UndefValue::get(CurTy); // Unknown binop. 2309f22ef01cSRoman Divacky } else { 2310f22ef01cSRoman Divacky Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy); 2311f22ef01cSRoman Divacky Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy); 2312f22ef01cSRoman Divacky unsigned Flags = 0; 2313f22ef01cSRoman Divacky if (Record.size() >= 4) { 2314f22ef01cSRoman Divacky if (Opc == Instruction::Add || 2315f22ef01cSRoman Divacky Opc == Instruction::Sub || 23162754fe60SDimitry Andric Opc == Instruction::Mul || 23172754fe60SDimitry Andric Opc == Instruction::Shl) { 2318f22ef01cSRoman Divacky if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP)) 2319f22ef01cSRoman Divacky Flags |= OverflowingBinaryOperator::NoSignedWrap; 2320f22ef01cSRoman Divacky if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP)) 2321f22ef01cSRoman Divacky Flags |= OverflowingBinaryOperator::NoUnsignedWrap; 23222754fe60SDimitry Andric } else if (Opc == Instruction::SDiv || 23232754fe60SDimitry Andric Opc == Instruction::UDiv || 23242754fe60SDimitry Andric Opc == Instruction::LShr || 23252754fe60SDimitry Andric Opc == Instruction::AShr) { 23262754fe60SDimitry Andric if (Record[3] & (1 << bitc::PEO_EXACT)) 2327f22ef01cSRoman Divacky Flags |= SDivOperator::IsExact; 2328f22ef01cSRoman Divacky } 2329f22ef01cSRoman Divacky } 2330f22ef01cSRoman Divacky V = ConstantExpr::get(Opc, LHS, RHS, Flags); 2331f22ef01cSRoman Divacky } 2332f22ef01cSRoman Divacky break; 2333f22ef01cSRoman Divacky } 2334f22ef01cSRoman Divacky case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval] 2335f785676fSDimitry Andric if (Record.size() < 3) 23368f0fd8f6SDimitry Andric return error("Invalid record"); 23378f0fd8f6SDimitry Andric int Opc = getDecodedCastOpcode(Record[0]); 2338f22ef01cSRoman Divacky if (Opc < 0) { 2339f22ef01cSRoman Divacky V = UndefValue::get(CurTy); // Unknown cast. 2340f22ef01cSRoman Divacky } else { 23416122f3e6SDimitry Andric Type *OpTy = getTypeByID(Record[1]); 2342f785676fSDimitry Andric if (!OpTy) 23438f0fd8f6SDimitry Andric return error("Invalid record"); 2344f22ef01cSRoman Divacky Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy); 2345f785676fSDimitry Andric V = UpgradeBitCastExpr(Opc, Op, CurTy); 2346f785676fSDimitry Andric if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy); 2347f22ef01cSRoman Divacky } 2348f22ef01cSRoman Divacky break; 2349f22ef01cSRoman Divacky } 2350d88c1a5aSDimitry Andric case bitc::CST_CODE_CE_INBOUNDS_GEP: // [ty, n x operands] 2351d88c1a5aSDimitry Andric case bitc::CST_CODE_CE_GEP: // [ty, n x operands] 2352d88c1a5aSDimitry Andric case bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX: { // [ty, flags, n x 2353d88c1a5aSDimitry Andric // operands] 2354ff0cc061SDimitry Andric unsigned OpNum = 0; 2355ff0cc061SDimitry Andric Type *PointeeType = nullptr; 2356d88c1a5aSDimitry Andric if (BitCode == bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX || 2357d88c1a5aSDimitry Andric Record.size() % 2) 2358ff0cc061SDimitry Andric PointeeType = getTypeByID(Record[OpNum++]); 2359d88c1a5aSDimitry Andric 2360d88c1a5aSDimitry Andric bool InBounds = false; 2361d88c1a5aSDimitry Andric Optional<unsigned> InRangeIndex; 2362d88c1a5aSDimitry Andric if (BitCode == bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX) { 2363d88c1a5aSDimitry Andric uint64_t Op = Record[OpNum++]; 2364d88c1a5aSDimitry Andric InBounds = Op & 1; 2365d88c1a5aSDimitry Andric InRangeIndex = Op >> 1; 2366d88c1a5aSDimitry Andric } else if (BitCode == bitc::CST_CODE_CE_INBOUNDS_GEP) 2367d88c1a5aSDimitry Andric InBounds = true; 2368d88c1a5aSDimitry Andric 2369f22ef01cSRoman Divacky SmallVector<Constant*, 16> Elts; 2370ff0cc061SDimitry Andric while (OpNum != Record.size()) { 2371ff0cc061SDimitry Andric Type *ElTy = getTypeByID(Record[OpNum++]); 2372f785676fSDimitry Andric if (!ElTy) 23738f0fd8f6SDimitry Andric return error("Invalid record"); 2374ff0cc061SDimitry Andric Elts.push_back(ValueList.getConstantFwdRef(Record[OpNum++], ElTy)); 2375f22ef01cSRoman Divacky } 2376ff0cc061SDimitry Andric 2377ff0cc061SDimitry Andric if (PointeeType && 2378ff0cc061SDimitry Andric PointeeType != 2379d88c1a5aSDimitry Andric cast<PointerType>(Elts[0]->getType()->getScalarType()) 2380ff0cc061SDimitry Andric ->getElementType()) 23818f0fd8f6SDimitry Andric return error("Explicit gep operator type does not match pointee type " 2382ff0cc061SDimitry Andric "of pointer operand"); 2383ff0cc061SDimitry Andric 23843ca95b02SDimitry Andric if (Elts.size() < 1) 23853ca95b02SDimitry Andric return error("Invalid gep with no operands"); 23863ca95b02SDimitry Andric 23876122f3e6SDimitry Andric ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end()); 2388ff0cc061SDimitry Andric V = ConstantExpr::getGetElementPtr(PointeeType, Elts[0], Indices, 2389d88c1a5aSDimitry Andric InBounds, InRangeIndex); 2390f22ef01cSRoman Divacky break; 2391f22ef01cSRoman Divacky } 2392f785676fSDimitry Andric case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#] 2393f785676fSDimitry Andric if (Record.size() < 3) 23948f0fd8f6SDimitry Andric return error("Invalid record"); 2395f785676fSDimitry Andric 2396f785676fSDimitry Andric Type *SelectorTy = Type::getInt1Ty(Context); 2397f785676fSDimitry Andric 23987d523365SDimitry Andric // The selector might be an i1 or an <n x i1> 23997d523365SDimitry Andric // Get the type from the ValueList before getting a forward ref. 2400f785676fSDimitry Andric if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) 24017d523365SDimitry Andric if (Value *V = ValueList[Record[0]]) 24027d523365SDimitry Andric if (SelectorTy != V->getType()) 24037d523365SDimitry Andric SelectorTy = VectorType::get(SelectorTy, VTy->getNumElements()); 2404f785676fSDimitry Andric 2405f785676fSDimitry Andric V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0], 2406f785676fSDimitry Andric SelectorTy), 2407f22ef01cSRoman Divacky ValueList.getConstantFwdRef(Record[1],CurTy), 2408f22ef01cSRoman Divacky ValueList.getConstantFwdRef(Record[2],CurTy)); 2409f22ef01cSRoman Divacky break; 2410f785676fSDimitry Andric } 241191bc56edSDimitry Andric case bitc::CST_CODE_CE_EXTRACTELT 241291bc56edSDimitry Andric : { // CE_EXTRACTELT: [opty, opval, opty, opval] 2413f785676fSDimitry Andric if (Record.size() < 3) 24148f0fd8f6SDimitry Andric return error("Invalid record"); 24156122f3e6SDimitry Andric VectorType *OpTy = 2416f22ef01cSRoman Divacky dyn_cast_or_null<VectorType>(getTypeByID(Record[0])); 241791bc56edSDimitry Andric if (!OpTy) 24188f0fd8f6SDimitry Andric return error("Invalid record"); 2419f22ef01cSRoman Divacky Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy); 242091bc56edSDimitry Andric Constant *Op1 = nullptr; 242191bc56edSDimitry Andric if (Record.size() == 4) { 242291bc56edSDimitry Andric Type *IdxTy = getTypeByID(Record[2]); 242391bc56edSDimitry Andric if (!IdxTy) 24248f0fd8f6SDimitry Andric return error("Invalid record"); 242591bc56edSDimitry Andric Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy); 242691bc56edSDimitry Andric } else // TODO: Remove with llvm 4.0 242791bc56edSDimitry Andric Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context)); 242891bc56edSDimitry Andric if (!Op1) 24298f0fd8f6SDimitry Andric return error("Invalid record"); 2430f22ef01cSRoman Divacky V = ConstantExpr::getExtractElement(Op0, Op1); 2431f22ef01cSRoman Divacky break; 2432f22ef01cSRoman Divacky } 243391bc56edSDimitry Andric case bitc::CST_CODE_CE_INSERTELT 243491bc56edSDimitry Andric : { // CE_INSERTELT: [opval, opval, opty, opval] 24356122f3e6SDimitry Andric VectorType *OpTy = dyn_cast<VectorType>(CurTy); 243691bc56edSDimitry Andric if (Record.size() < 3 || !OpTy) 24378f0fd8f6SDimitry Andric return error("Invalid record"); 2438f22ef01cSRoman Divacky Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy); 2439f22ef01cSRoman Divacky Constant *Op1 = ValueList.getConstantFwdRef(Record[1], 2440f22ef01cSRoman Divacky OpTy->getElementType()); 244191bc56edSDimitry Andric Constant *Op2 = nullptr; 244291bc56edSDimitry Andric if (Record.size() == 4) { 244391bc56edSDimitry Andric Type *IdxTy = getTypeByID(Record[2]); 244491bc56edSDimitry Andric if (!IdxTy) 24458f0fd8f6SDimitry Andric return error("Invalid record"); 244691bc56edSDimitry Andric Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy); 244791bc56edSDimitry Andric } else // TODO: Remove with llvm 4.0 244891bc56edSDimitry Andric Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context)); 244991bc56edSDimitry Andric if (!Op2) 24508f0fd8f6SDimitry Andric return error("Invalid record"); 2451f22ef01cSRoman Divacky V = ConstantExpr::getInsertElement(Op0, Op1, Op2); 2452f22ef01cSRoman Divacky break; 2453f22ef01cSRoman Divacky } 2454f22ef01cSRoman Divacky case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval] 24556122f3e6SDimitry Andric VectorType *OpTy = dyn_cast<VectorType>(CurTy); 245691bc56edSDimitry Andric if (Record.size() < 3 || !OpTy) 24578f0fd8f6SDimitry Andric return error("Invalid record"); 2458f22ef01cSRoman Divacky Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy); 2459f22ef01cSRoman Divacky Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy); 24606122f3e6SDimitry Andric Type *ShufTy = VectorType::get(Type::getInt32Ty(Context), 2461f22ef01cSRoman Divacky OpTy->getNumElements()); 2462f22ef01cSRoman Divacky Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy); 2463f22ef01cSRoman Divacky V = ConstantExpr::getShuffleVector(Op0, Op1, Op2); 2464f22ef01cSRoman Divacky break; 2465f22ef01cSRoman Divacky } 2466f22ef01cSRoman Divacky case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval] 24676122f3e6SDimitry Andric VectorType *RTy = dyn_cast<VectorType>(CurTy); 24686122f3e6SDimitry Andric VectorType *OpTy = 24692754fe60SDimitry Andric dyn_cast_or_null<VectorType>(getTypeByID(Record[0])); 247091bc56edSDimitry Andric if (Record.size() < 4 || !RTy || !OpTy) 24718f0fd8f6SDimitry Andric return error("Invalid record"); 2472f22ef01cSRoman Divacky Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy); 2473f22ef01cSRoman Divacky Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy); 24746122f3e6SDimitry Andric Type *ShufTy = VectorType::get(Type::getInt32Ty(Context), 2475f22ef01cSRoman Divacky RTy->getNumElements()); 2476f22ef01cSRoman Divacky Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy); 2477f22ef01cSRoman Divacky V = ConstantExpr::getShuffleVector(Op0, Op1, Op2); 2478f22ef01cSRoman Divacky break; 2479f22ef01cSRoman Divacky } 2480f22ef01cSRoman Divacky case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred] 2481f785676fSDimitry Andric if (Record.size() < 4) 24828f0fd8f6SDimitry Andric return error("Invalid record"); 24836122f3e6SDimitry Andric Type *OpTy = getTypeByID(Record[0]); 248491bc56edSDimitry Andric if (!OpTy) 24858f0fd8f6SDimitry Andric return error("Invalid record"); 2486f22ef01cSRoman Divacky Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy); 2487f22ef01cSRoman Divacky Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy); 2488f22ef01cSRoman Divacky 2489f22ef01cSRoman Divacky if (OpTy->isFPOrFPVectorTy()) 2490f22ef01cSRoman Divacky V = ConstantExpr::getFCmp(Record[3], Op0, Op1); 2491f22ef01cSRoman Divacky else 2492f22ef01cSRoman Divacky V = ConstantExpr::getICmp(Record[3], Op0, Op1); 2493f22ef01cSRoman Divacky break; 2494f22ef01cSRoman Divacky } 24953861d79fSDimitry Andric // This maintains backward compatibility, pre-asm dialect keywords. 24963861d79fSDimitry Andric // FIXME: Remove with the 4.0 release. 24973861d79fSDimitry Andric case bitc::CST_CODE_INLINEASM_OLD: { 2498f785676fSDimitry Andric if (Record.size() < 2) 24998f0fd8f6SDimitry Andric return error("Invalid record"); 2500f22ef01cSRoman Divacky std::string AsmStr, ConstrStr; 2501f22ef01cSRoman Divacky bool HasSideEffects = Record[0] & 1; 2502f22ef01cSRoman Divacky bool IsAlignStack = Record[0] >> 1; 2503f22ef01cSRoman Divacky unsigned AsmStrSize = Record[1]; 2504f22ef01cSRoman Divacky if (2+AsmStrSize >= Record.size()) 25058f0fd8f6SDimitry Andric return error("Invalid record"); 2506f22ef01cSRoman Divacky unsigned ConstStrSize = Record[2+AsmStrSize]; 2507f22ef01cSRoman Divacky if (3+AsmStrSize+ConstStrSize > Record.size()) 25088f0fd8f6SDimitry Andric return error("Invalid record"); 2509f22ef01cSRoman Divacky 2510f22ef01cSRoman Divacky for (unsigned i = 0; i != AsmStrSize; ++i) 2511f22ef01cSRoman Divacky AsmStr += (char)Record[2+i]; 2512f22ef01cSRoman Divacky for (unsigned i = 0; i != ConstStrSize; ++i) 2513f22ef01cSRoman Divacky ConstrStr += (char)Record[3+AsmStrSize+i]; 25146122f3e6SDimitry Andric PointerType *PTy = cast<PointerType>(CurTy); 2515f22ef01cSRoman Divacky V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()), 2516f22ef01cSRoman Divacky AsmStr, ConstrStr, HasSideEffects, IsAlignStack); 2517f22ef01cSRoman Divacky break; 2518f22ef01cSRoman Divacky } 25193861d79fSDimitry Andric // This version adds support for the asm dialect keywords (e.g., 25203861d79fSDimitry Andric // inteldialect). 25213861d79fSDimitry Andric case bitc::CST_CODE_INLINEASM: { 2522f785676fSDimitry Andric if (Record.size() < 2) 25238f0fd8f6SDimitry Andric return error("Invalid record"); 25243861d79fSDimitry Andric std::string AsmStr, ConstrStr; 25253861d79fSDimitry Andric bool HasSideEffects = Record[0] & 1; 25263861d79fSDimitry Andric bool IsAlignStack = (Record[0] >> 1) & 1; 25273861d79fSDimitry Andric unsigned AsmDialect = Record[0] >> 2; 25283861d79fSDimitry Andric unsigned AsmStrSize = Record[1]; 25293861d79fSDimitry Andric if (2+AsmStrSize >= Record.size()) 25308f0fd8f6SDimitry Andric return error("Invalid record"); 25313861d79fSDimitry Andric unsigned ConstStrSize = Record[2+AsmStrSize]; 25323861d79fSDimitry Andric if (3+AsmStrSize+ConstStrSize > Record.size()) 25338f0fd8f6SDimitry Andric return error("Invalid record"); 25343861d79fSDimitry Andric 25353861d79fSDimitry Andric for (unsigned i = 0; i != AsmStrSize; ++i) 25363861d79fSDimitry Andric AsmStr += (char)Record[2+i]; 25373861d79fSDimitry Andric for (unsigned i = 0; i != ConstStrSize; ++i) 25383861d79fSDimitry Andric ConstrStr += (char)Record[3+AsmStrSize+i]; 25393861d79fSDimitry Andric PointerType *PTy = cast<PointerType>(CurTy); 25403861d79fSDimitry Andric V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()), 25413861d79fSDimitry Andric AsmStr, ConstrStr, HasSideEffects, IsAlignStack, 25423861d79fSDimitry Andric InlineAsm::AsmDialect(AsmDialect)); 25433861d79fSDimitry Andric break; 25443861d79fSDimitry Andric } 2545f22ef01cSRoman Divacky case bitc::CST_CODE_BLOCKADDRESS:{ 2546f785676fSDimitry Andric if (Record.size() < 3) 25478f0fd8f6SDimitry Andric return error("Invalid record"); 25486122f3e6SDimitry Andric Type *FnTy = getTypeByID(Record[0]); 254991bc56edSDimitry Andric if (!FnTy) 25508f0fd8f6SDimitry Andric return error("Invalid record"); 2551f22ef01cSRoman Divacky Function *Fn = 2552f22ef01cSRoman Divacky dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy)); 255391bc56edSDimitry Andric if (!Fn) 25548f0fd8f6SDimitry Andric return error("Invalid record"); 255539d628a0SDimitry Andric 25563861d79fSDimitry Andric // If the function is already parsed we can insert the block address right 25573861d79fSDimitry Andric // away. 255839d628a0SDimitry Andric BasicBlock *BB; 255939d628a0SDimitry Andric unsigned BBID = Record[2]; 256039d628a0SDimitry Andric if (!BBID) 256139d628a0SDimitry Andric // Invalid reference to entry block. 25628f0fd8f6SDimitry Andric return error("Invalid ID"); 25633861d79fSDimitry Andric if (!Fn->empty()) { 25643861d79fSDimitry Andric Function::iterator BBI = Fn->begin(), BBE = Fn->end(); 256539d628a0SDimitry Andric for (size_t I = 0, E = BBID; I != E; ++I) { 25663861d79fSDimitry Andric if (BBI == BBE) 25678f0fd8f6SDimitry Andric return error("Invalid ID"); 25683861d79fSDimitry Andric ++BBI; 25693861d79fSDimitry Andric } 25707d523365SDimitry Andric BB = &*BBI; 25713861d79fSDimitry Andric } else { 25723861d79fSDimitry Andric // Otherwise insert a placeholder and remember it so it can be inserted 25733861d79fSDimitry Andric // when the function is parsed. 257439d628a0SDimitry Andric auto &FwdBBs = BasicBlockFwdRefs[Fn]; 257539d628a0SDimitry Andric if (FwdBBs.empty()) 257639d628a0SDimitry Andric BasicBlockFwdRefQueue.push_back(Fn); 257739d628a0SDimitry Andric if (FwdBBs.size() < BBID + 1) 257839d628a0SDimitry Andric FwdBBs.resize(BBID + 1); 257939d628a0SDimitry Andric if (!FwdBBs[BBID]) 258039d628a0SDimitry Andric FwdBBs[BBID] = BasicBlock::Create(Context); 258139d628a0SDimitry Andric BB = FwdBBs[BBID]; 25823861d79fSDimitry Andric } 258339d628a0SDimitry Andric V = BlockAddress::get(Fn, BB); 2584f22ef01cSRoman Divacky break; 2585f22ef01cSRoman Divacky } 2586f22ef01cSRoman Divacky } 2587f22ef01cSRoman Divacky 25888f0fd8f6SDimitry Andric ValueList.assignValue(V, NextCstNo); 2589f22ef01cSRoman Divacky ++NextCstNo; 2590f22ef01cSRoman Divacky } 2591f22ef01cSRoman Divacky } 2592f22ef01cSRoman Divacky 2593d88c1a5aSDimitry Andric Error BitcodeReader::parseUseLists() { 2594dff0c46cSDimitry Andric if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID)) 25958f0fd8f6SDimitry Andric return error("Invalid record"); 2596dff0c46cSDimitry Andric 2597dff0c46cSDimitry Andric // Read all the records. 259839d628a0SDimitry Andric SmallVector<uint64_t, 64> Record; 2599d88c1a5aSDimitry Andric 2600d88c1a5aSDimitry Andric while (true) { 2601139f7f9bSDimitry Andric BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 2602139f7f9bSDimitry Andric 2603139f7f9bSDimitry Andric switch (Entry.Kind) { 2604139f7f9bSDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already. 2605139f7f9bSDimitry Andric case BitstreamEntry::Error: 26068f0fd8f6SDimitry Andric return error("Malformed block"); 2607139f7f9bSDimitry Andric case BitstreamEntry::EndBlock: 2608d88c1a5aSDimitry Andric return Error::success(); 2609139f7f9bSDimitry Andric case BitstreamEntry::Record: 2610139f7f9bSDimitry Andric // The interesting case. 2611139f7f9bSDimitry Andric break; 2612dff0c46cSDimitry Andric } 2613dff0c46cSDimitry Andric 2614dff0c46cSDimitry Andric // Read a use list record. 2615dff0c46cSDimitry Andric Record.clear(); 261639d628a0SDimitry Andric bool IsBB = false; 2617139f7f9bSDimitry Andric switch (Stream.readRecord(Entry.ID, Record)) { 2618dff0c46cSDimitry Andric default: // Default behavior: unknown type. 2619dff0c46cSDimitry Andric break; 262039d628a0SDimitry Andric case bitc::USELIST_CODE_BB: 262139d628a0SDimitry Andric IsBB = true; 2622d88c1a5aSDimitry Andric LLVM_FALLTHROUGH; 262339d628a0SDimitry Andric case bitc::USELIST_CODE_DEFAULT: { 2624dff0c46cSDimitry Andric unsigned RecordLength = Record.size(); 262539d628a0SDimitry Andric if (RecordLength < 3) 262639d628a0SDimitry Andric // Records should have at least an ID and two indexes. 26278f0fd8f6SDimitry Andric return error("Invalid record"); 262839d628a0SDimitry Andric unsigned ID = Record.back(); 262939d628a0SDimitry Andric Record.pop_back(); 263039d628a0SDimitry Andric 263139d628a0SDimitry Andric Value *V; 263239d628a0SDimitry Andric if (IsBB) { 263339d628a0SDimitry Andric assert(ID < FunctionBBs.size() && "Basic block not found"); 263439d628a0SDimitry Andric V = FunctionBBs[ID]; 263539d628a0SDimitry Andric } else 263639d628a0SDimitry Andric V = ValueList[ID]; 263739d628a0SDimitry Andric unsigned NumUses = 0; 263839d628a0SDimitry Andric SmallDenseMap<const Use *, unsigned, 16> Order; 26397d523365SDimitry Andric for (const Use &U : V->materialized_uses()) { 264039d628a0SDimitry Andric if (++NumUses > Record.size()) 264139d628a0SDimitry Andric break; 264239d628a0SDimitry Andric Order[&U] = Record[NumUses - 1]; 264339d628a0SDimitry Andric } 264439d628a0SDimitry Andric if (Order.size() != Record.size() || NumUses > Record.size()) 264539d628a0SDimitry Andric // Mismatches can happen if the functions are being materialized lazily 264639d628a0SDimitry Andric // (out-of-order), or a value has been upgraded. 264739d628a0SDimitry Andric break; 264839d628a0SDimitry Andric 264939d628a0SDimitry Andric V->sortUseList([&](const Use &L, const Use &R) { 265039d628a0SDimitry Andric return Order.lookup(&L) < Order.lookup(&R); 265139d628a0SDimitry Andric }); 2652dff0c46cSDimitry Andric break; 2653dff0c46cSDimitry Andric } 2654dff0c46cSDimitry Andric } 2655dff0c46cSDimitry Andric } 2656dff0c46cSDimitry Andric } 2657dff0c46cSDimitry Andric 2658ff0cc061SDimitry Andric /// When we see the block for metadata, remember where it is and then skip it. 2659ff0cc061SDimitry Andric /// This lets us lazily deserialize the metadata. 2660d88c1a5aSDimitry Andric Error BitcodeReader::rememberAndSkipMetadata() { 2661ff0cc061SDimitry Andric // Save the current stream state. 2662ff0cc061SDimitry Andric uint64_t CurBit = Stream.GetCurrentBitNo(); 2663ff0cc061SDimitry Andric DeferredMetadataInfo.push_back(CurBit); 2664ff0cc061SDimitry Andric 2665ff0cc061SDimitry Andric // Skip over the block for now. 2666ff0cc061SDimitry Andric if (Stream.SkipBlock()) 26678f0fd8f6SDimitry Andric return error("Invalid record"); 2668d88c1a5aSDimitry Andric return Error::success(); 2669ff0cc061SDimitry Andric } 2670ff0cc061SDimitry Andric 2671d88c1a5aSDimitry Andric Error BitcodeReader::materializeMetadata() { 2672ff0cc061SDimitry Andric for (uint64_t BitPos : DeferredMetadataInfo) { 2673ff0cc061SDimitry Andric // Move the bit stream to the saved position. 2674ff0cc061SDimitry Andric Stream.JumpToBit(BitPos); 2675d88c1a5aSDimitry Andric if (Error Err = MDLoader->parseModuleMetadata()) 2676d88c1a5aSDimitry Andric return Err; 2677ff0cc061SDimitry Andric } 267824d58133SDimitry Andric 267924d58133SDimitry Andric // Upgrade "Linker Options" module flag to "llvm.linker.options" module-level 268024d58133SDimitry Andric // metadata. 268124d58133SDimitry Andric if (Metadata *Val = TheModule->getModuleFlag("Linker Options")) { 268224d58133SDimitry Andric NamedMDNode *LinkerOpts = 268324d58133SDimitry Andric TheModule->getOrInsertNamedMetadata("llvm.linker.options"); 268424d58133SDimitry Andric for (const MDOperand &MDOptions : cast<MDNode>(Val)->operands()) 268524d58133SDimitry Andric LinkerOpts->addOperand(cast<MDNode>(MDOptions)); 268624d58133SDimitry Andric } 268724d58133SDimitry Andric 2688ff0cc061SDimitry Andric DeferredMetadataInfo.clear(); 2689d88c1a5aSDimitry Andric return Error::success(); 2690ff0cc061SDimitry Andric } 2691ff0cc061SDimitry Andric 2692ff0cc061SDimitry Andric void BitcodeReader::setStripDebugInfo() { StripDebugInfo = true; } 2693ff0cc061SDimitry Andric 26948f0fd8f6SDimitry Andric /// When we see the block for a function body, remember where it is and then 26958f0fd8f6SDimitry Andric /// skip it. This lets us lazily deserialize the functions. 2696d88c1a5aSDimitry Andric Error BitcodeReader::rememberAndSkipFunctionBody() { 2697f22ef01cSRoman Divacky // Get the function we are talking about. 2698f22ef01cSRoman Divacky if (FunctionsWithBodies.empty()) 26998f0fd8f6SDimitry Andric return error("Insufficient function protos"); 2700f22ef01cSRoman Divacky 2701f22ef01cSRoman Divacky Function *Fn = FunctionsWithBodies.back(); 2702f22ef01cSRoman Divacky FunctionsWithBodies.pop_back(); 2703f22ef01cSRoman Divacky 2704f22ef01cSRoman Divacky // Save the current stream state. 2705f22ef01cSRoman Divacky uint64_t CurBit = Stream.GetCurrentBitNo(); 27067d523365SDimitry Andric assert( 27077d523365SDimitry Andric (DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo[Fn] == CurBit) && 27087d523365SDimitry Andric "Mismatch between VST and scanned function offsets"); 2709f22ef01cSRoman Divacky DeferredFunctionInfo[Fn] = CurBit; 2710f22ef01cSRoman Divacky 2711f22ef01cSRoman Divacky // Skip over the function block for now. 2712f22ef01cSRoman Divacky if (Stream.SkipBlock()) 27138f0fd8f6SDimitry Andric return error("Invalid record"); 2714d88c1a5aSDimitry Andric return Error::success(); 2715f22ef01cSRoman Divacky } 2716f22ef01cSRoman Divacky 2717d88c1a5aSDimitry Andric Error BitcodeReader::globalCleanup() { 2718f22ef01cSRoman Divacky // Patch the initializers for globals and aliases up. 2719d88c1a5aSDimitry Andric if (Error Err = resolveGlobalAndIndirectSymbolInits()) 2720d88c1a5aSDimitry Andric return Err; 27213ca95b02SDimitry Andric if (!GlobalInits.empty() || !IndirectSymbolInits.empty()) 27228f0fd8f6SDimitry Andric return error("Malformed global initializer set"); 2723f22ef01cSRoman Divacky 2724f22ef01cSRoman Divacky // Look for intrinsic functions which need to be upgraded at some point 27258f0fd8f6SDimitry Andric for (Function &F : *TheModule) { 27266bc11b14SDimitry Andric MDLoader->upgradeDebugIntrinsics(F); 2727f22ef01cSRoman Divacky Function *NewFn; 27288f0fd8f6SDimitry Andric if (UpgradeIntrinsicFunction(&F, NewFn)) 27293dac3a9bSDimitry Andric UpgradedIntrinsics[&F] = NewFn; 27303ca95b02SDimitry Andric else if (auto Remangled = Intrinsic::remangleIntrinsicFunction(&F)) 27313ca95b02SDimitry Andric // Some types could be renamed during loading if several modules are 27323ca95b02SDimitry Andric // loaded in the same LLVMContext (LTO scenario). In this case we should 27333ca95b02SDimitry Andric // remangle intrinsics names as well. 27343ca95b02SDimitry Andric RemangledIntrinsics[&F] = Remangled.getValue(); 2735f22ef01cSRoman Divacky } 2736f22ef01cSRoman Divacky 2737e580952dSDimitry Andric // Look for global variables which need to be renamed. 27388f0fd8f6SDimitry Andric for (GlobalVariable &GV : TheModule->globals()) 27398f0fd8f6SDimitry Andric UpgradeGlobalVariable(&GV); 274091bc56edSDimitry Andric 2741f22ef01cSRoman Divacky // Force deallocation of memory for these vectors to favor the client that 2742f22ef01cSRoman Divacky // want lazy deserialization. 2743f22ef01cSRoman Divacky std::vector<std::pair<GlobalVariable *, unsigned>>().swap(GlobalInits); 27443ca95b02SDimitry Andric std::vector<std::pair<GlobalIndirectSymbol *, unsigned>>().swap( 27453ca95b02SDimitry Andric IndirectSymbolInits); 2746d88c1a5aSDimitry Andric return Error::success(); 2747f22ef01cSRoman Divacky } 2748f22ef01cSRoman Divacky 27497d523365SDimitry Andric /// Support for lazy parsing of function bodies. This is required if we 27507d523365SDimitry Andric /// either have an old bitcode file without a VST forward declaration record, 27517d523365SDimitry Andric /// or if we have an anonymous function being materialized, since anonymous 27527d523365SDimitry Andric /// functions do not have a name and are therefore not in the VST. 2753d88c1a5aSDimitry Andric Error BitcodeReader::rememberAndSkipFunctionBodies() { 2754dff0c46cSDimitry Andric Stream.JumpToBit(NextUnreadBit); 27557d523365SDimitry Andric 27567d523365SDimitry Andric if (Stream.AtEndOfStream()) 27577d523365SDimitry Andric return error("Could not find function in stream"); 27587d523365SDimitry Andric 27597d523365SDimitry Andric if (!SeenFirstFunctionBody) 27607d523365SDimitry Andric return error("Trying to materialize functions before seeing function blocks"); 27617d523365SDimitry Andric 27627d523365SDimitry Andric // An old bitcode file with the symbol table at the end would have 27637d523365SDimitry Andric // finished the parse greedily. 27647d523365SDimitry Andric assert(SeenValueSymbolTable); 27657d523365SDimitry Andric 27667d523365SDimitry Andric SmallVector<uint64_t, 64> Record; 27677d523365SDimitry Andric 2768d88c1a5aSDimitry Andric while (true) { 27697d523365SDimitry Andric BitstreamEntry Entry = Stream.advance(); 27707d523365SDimitry Andric switch (Entry.Kind) { 27717d523365SDimitry Andric default: 27727d523365SDimitry Andric return error("Expect SubBlock"); 27737d523365SDimitry Andric case BitstreamEntry::SubBlock: 27747d523365SDimitry Andric switch (Entry.ID) { 27757d523365SDimitry Andric default: 27767d523365SDimitry Andric return error("Expect function block"); 27777d523365SDimitry Andric case bitc::FUNCTION_BLOCK_ID: 2778d88c1a5aSDimitry Andric if (Error Err = rememberAndSkipFunctionBody()) 2779d88c1a5aSDimitry Andric return Err; 27807d523365SDimitry Andric NextUnreadBit = Stream.GetCurrentBitNo(); 2781d88c1a5aSDimitry Andric return Error::success(); 27827d523365SDimitry Andric } 27837d523365SDimitry Andric } 27847d523365SDimitry Andric } 27857d523365SDimitry Andric } 27867d523365SDimitry Andric 2787d88c1a5aSDimitry Andric bool BitcodeReaderBase::readBlockInfo() { 2788d88c1a5aSDimitry Andric Optional<BitstreamBlockInfo> NewBlockInfo = Stream.ReadBlockInfoBlock(); 2789d88c1a5aSDimitry Andric if (!NewBlockInfo) 2790d88c1a5aSDimitry Andric return true; 2791d88c1a5aSDimitry Andric BlockInfo = std::move(*NewBlockInfo); 2792d88c1a5aSDimitry Andric return false; 27937d523365SDimitry Andric } 27947d523365SDimitry Andric 27957a7e6055SDimitry Andric Error BitcodeReader::parseComdatRecord(ArrayRef<uint64_t> Record) { 27966bc11b14SDimitry Andric // v1: [selection_kind, name] 27976bc11b14SDimitry Andric // v2: [strtab_offset, strtab_size, selection_kind] 27986bc11b14SDimitry Andric StringRef Name; 27996bc11b14SDimitry Andric std::tie(Name, Record) = readNameFromStrtab(Record); 28006bc11b14SDimitry Andric 28012cab237bSDimitry Andric if (Record.empty()) 28027a7e6055SDimitry Andric return error("Invalid record"); 28037a7e6055SDimitry Andric Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]); 28046bc11b14SDimitry Andric std::string OldFormatName; 28056bc11b14SDimitry Andric if (!UseStrtab) { 28066bc11b14SDimitry Andric if (Record.size() < 2) 28076bc11b14SDimitry Andric return error("Invalid record"); 28087a7e6055SDimitry Andric unsigned ComdatNameSize = Record[1]; 28096bc11b14SDimitry Andric OldFormatName.reserve(ComdatNameSize); 28107a7e6055SDimitry Andric for (unsigned i = 0; i != ComdatNameSize; ++i) 28116bc11b14SDimitry Andric OldFormatName += (char)Record[2 + i]; 28126bc11b14SDimitry Andric Name = OldFormatName; 28136bc11b14SDimitry Andric } 28147a7e6055SDimitry Andric Comdat *C = TheModule->getOrInsertComdat(Name); 28157a7e6055SDimitry Andric C->setSelectionKind(SK); 28167a7e6055SDimitry Andric ComdatList.push_back(C); 28177a7e6055SDimitry Andric return Error::success(); 28187a7e6055SDimitry Andric } 28197a7e6055SDimitry Andric 28207a7e6055SDimitry Andric Error BitcodeReader::parseGlobalVarRecord(ArrayRef<uint64_t> Record) { 28216bc11b14SDimitry Andric // v1: [pointer type, isconst, initid, linkage, alignment, section, 28227a7e6055SDimitry Andric // visibility, threadlocal, unnamed_addr, externally_initialized, 28232cab237bSDimitry Andric // dllstorageclass, comdat, attributes, preemption specifier] (name in VST) 28246bc11b14SDimitry Andric // v2: [strtab_offset, strtab_size, v1] 28256bc11b14SDimitry Andric StringRef Name; 28266bc11b14SDimitry Andric std::tie(Name, Record) = readNameFromStrtab(Record); 28276bc11b14SDimitry Andric 28287a7e6055SDimitry Andric if (Record.size() < 6) 28297a7e6055SDimitry Andric return error("Invalid record"); 28307a7e6055SDimitry Andric Type *Ty = getTypeByID(Record[0]); 28317a7e6055SDimitry Andric if (!Ty) 28327a7e6055SDimitry Andric return error("Invalid record"); 28337a7e6055SDimitry Andric bool isConstant = Record[1] & 1; 28347a7e6055SDimitry Andric bool explicitType = Record[1] & 2; 28357a7e6055SDimitry Andric unsigned AddressSpace; 28367a7e6055SDimitry Andric if (explicitType) { 28377a7e6055SDimitry Andric AddressSpace = Record[1] >> 2; 28387a7e6055SDimitry Andric } else { 28397a7e6055SDimitry Andric if (!Ty->isPointerTy()) 28407a7e6055SDimitry Andric return error("Invalid type for value"); 28417a7e6055SDimitry Andric AddressSpace = cast<PointerType>(Ty)->getAddressSpace(); 28427a7e6055SDimitry Andric Ty = cast<PointerType>(Ty)->getElementType(); 28437a7e6055SDimitry Andric } 28447a7e6055SDimitry Andric 28457a7e6055SDimitry Andric uint64_t RawLinkage = Record[3]; 28467a7e6055SDimitry Andric GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage); 28477a7e6055SDimitry Andric unsigned Alignment; 28487a7e6055SDimitry Andric if (Error Err = parseAlignmentValue(Record[4], Alignment)) 28497a7e6055SDimitry Andric return Err; 28507a7e6055SDimitry Andric std::string Section; 28517a7e6055SDimitry Andric if (Record[5]) { 28527a7e6055SDimitry Andric if (Record[5] - 1 >= SectionTable.size()) 28537a7e6055SDimitry Andric return error("Invalid ID"); 28547a7e6055SDimitry Andric Section = SectionTable[Record[5] - 1]; 28557a7e6055SDimitry Andric } 28567a7e6055SDimitry Andric GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility; 28577a7e6055SDimitry Andric // Local linkage must have default visibility. 28587a7e6055SDimitry Andric if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage)) 28597a7e6055SDimitry Andric // FIXME: Change to an error if non-default in 4.0. 28607a7e6055SDimitry Andric Visibility = getDecodedVisibility(Record[6]); 28617a7e6055SDimitry Andric 28627a7e6055SDimitry Andric GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal; 28637a7e6055SDimitry Andric if (Record.size() > 7) 28647a7e6055SDimitry Andric TLM = getDecodedThreadLocalMode(Record[7]); 28657a7e6055SDimitry Andric 28667a7e6055SDimitry Andric GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None; 28677a7e6055SDimitry Andric if (Record.size() > 8) 28687a7e6055SDimitry Andric UnnamedAddr = getDecodedUnnamedAddrType(Record[8]); 28697a7e6055SDimitry Andric 28707a7e6055SDimitry Andric bool ExternallyInitialized = false; 28717a7e6055SDimitry Andric if (Record.size() > 9) 28727a7e6055SDimitry Andric ExternallyInitialized = Record[9]; 28737a7e6055SDimitry Andric 28747a7e6055SDimitry Andric GlobalVariable *NewGV = 28756bc11b14SDimitry Andric new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, Name, 28767a7e6055SDimitry Andric nullptr, TLM, AddressSpace, ExternallyInitialized); 28777a7e6055SDimitry Andric NewGV->setAlignment(Alignment); 28787a7e6055SDimitry Andric if (!Section.empty()) 28797a7e6055SDimitry Andric NewGV->setSection(Section); 28807a7e6055SDimitry Andric NewGV->setVisibility(Visibility); 28817a7e6055SDimitry Andric NewGV->setUnnamedAddr(UnnamedAddr); 28827a7e6055SDimitry Andric 28837a7e6055SDimitry Andric if (Record.size() > 10) 28847a7e6055SDimitry Andric NewGV->setDLLStorageClass(getDecodedDLLStorageClass(Record[10])); 28857a7e6055SDimitry Andric else 28867a7e6055SDimitry Andric upgradeDLLImportExportLinkage(NewGV, RawLinkage); 28877a7e6055SDimitry Andric 28887a7e6055SDimitry Andric ValueList.push_back(NewGV); 28897a7e6055SDimitry Andric 28907a7e6055SDimitry Andric // Remember which value to use for the global initializer. 28917a7e6055SDimitry Andric if (unsigned InitID = Record[2]) 28927a7e6055SDimitry Andric GlobalInits.push_back(std::make_pair(NewGV, InitID - 1)); 28937a7e6055SDimitry Andric 28947a7e6055SDimitry Andric if (Record.size() > 11) { 28957a7e6055SDimitry Andric if (unsigned ComdatID = Record[11]) { 28967a7e6055SDimitry Andric if (ComdatID > ComdatList.size()) 28977a7e6055SDimitry Andric return error("Invalid global variable comdat ID"); 28987a7e6055SDimitry Andric NewGV->setComdat(ComdatList[ComdatID - 1]); 28997a7e6055SDimitry Andric } 29007a7e6055SDimitry Andric } else if (hasImplicitComdat(RawLinkage)) { 29017a7e6055SDimitry Andric NewGV->setComdat(reinterpret_cast<Comdat *>(1)); 29027a7e6055SDimitry Andric } 29035517e702SDimitry Andric 29045517e702SDimitry Andric if (Record.size() > 12) { 29055517e702SDimitry Andric auto AS = getAttributes(Record[12]).getFnAttributes(); 29065517e702SDimitry Andric NewGV->setAttributes(AS); 29075517e702SDimitry Andric } 29082cab237bSDimitry Andric 29092cab237bSDimitry Andric if (Record.size() > 13) { 29102cab237bSDimitry Andric NewGV->setDSOLocal(getDecodedDSOLocal(Record[13])); 29112cab237bSDimitry Andric } 29122cab237bSDimitry Andric 29137a7e6055SDimitry Andric return Error::success(); 29147a7e6055SDimitry Andric } 29157a7e6055SDimitry Andric 29167a7e6055SDimitry Andric Error BitcodeReader::parseFunctionRecord(ArrayRef<uint64_t> Record) { 29176bc11b14SDimitry Andric // v1: [type, callingconv, isproto, linkage, paramattr, alignment, section, 29187a7e6055SDimitry Andric // visibility, gc, unnamed_addr, prologuedata, dllstorageclass, comdat, 29192cab237bSDimitry Andric // prefixdata, personalityfn, preemption specifier] (name in VST) 29206bc11b14SDimitry Andric // v2: [strtab_offset, strtab_size, v1] 29216bc11b14SDimitry Andric StringRef Name; 29226bc11b14SDimitry Andric std::tie(Name, Record) = readNameFromStrtab(Record); 29236bc11b14SDimitry Andric 29247a7e6055SDimitry Andric if (Record.size() < 8) 29257a7e6055SDimitry Andric return error("Invalid record"); 29267a7e6055SDimitry Andric Type *Ty = getTypeByID(Record[0]); 29277a7e6055SDimitry Andric if (!Ty) 29287a7e6055SDimitry Andric return error("Invalid record"); 29297a7e6055SDimitry Andric if (auto *PTy = dyn_cast<PointerType>(Ty)) 29307a7e6055SDimitry Andric Ty = PTy->getElementType(); 29317a7e6055SDimitry Andric auto *FTy = dyn_cast<FunctionType>(Ty); 29327a7e6055SDimitry Andric if (!FTy) 29337a7e6055SDimitry Andric return error("Invalid type for value"); 29347a7e6055SDimitry Andric auto CC = static_cast<CallingConv::ID>(Record[1]); 29357a7e6055SDimitry Andric if (CC & ~CallingConv::MaxID) 29367a7e6055SDimitry Andric return error("Invalid calling convention ID"); 29377a7e6055SDimitry Andric 29387a7e6055SDimitry Andric Function *Func = 29396bc11b14SDimitry Andric Function::Create(FTy, GlobalValue::ExternalLinkage, Name, TheModule); 29407a7e6055SDimitry Andric 29417a7e6055SDimitry Andric Func->setCallingConv(CC); 29427a7e6055SDimitry Andric bool isProto = Record[2]; 29437a7e6055SDimitry Andric uint64_t RawLinkage = Record[3]; 29447a7e6055SDimitry Andric Func->setLinkage(getDecodedLinkage(RawLinkage)); 29457a7e6055SDimitry Andric Func->setAttributes(getAttributes(Record[4])); 29467a7e6055SDimitry Andric 29477a7e6055SDimitry Andric unsigned Alignment; 29487a7e6055SDimitry Andric if (Error Err = parseAlignmentValue(Record[5], Alignment)) 29497a7e6055SDimitry Andric return Err; 29507a7e6055SDimitry Andric Func->setAlignment(Alignment); 29517a7e6055SDimitry Andric if (Record[6]) { 29527a7e6055SDimitry Andric if (Record[6] - 1 >= SectionTable.size()) 29537a7e6055SDimitry Andric return error("Invalid ID"); 29547a7e6055SDimitry Andric Func->setSection(SectionTable[Record[6] - 1]); 29557a7e6055SDimitry Andric } 29567a7e6055SDimitry Andric // Local linkage must have default visibility. 29577a7e6055SDimitry Andric if (!Func->hasLocalLinkage()) 29587a7e6055SDimitry Andric // FIXME: Change to an error if non-default in 4.0. 29597a7e6055SDimitry Andric Func->setVisibility(getDecodedVisibility(Record[7])); 29607a7e6055SDimitry Andric if (Record.size() > 8 && Record[8]) { 29617a7e6055SDimitry Andric if (Record[8] - 1 >= GCTable.size()) 29627a7e6055SDimitry Andric return error("Invalid ID"); 29637a7e6055SDimitry Andric Func->setGC(GCTable[Record[8] - 1]); 29647a7e6055SDimitry Andric } 29657a7e6055SDimitry Andric GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None; 29667a7e6055SDimitry Andric if (Record.size() > 9) 29677a7e6055SDimitry Andric UnnamedAddr = getDecodedUnnamedAddrType(Record[9]); 29687a7e6055SDimitry Andric Func->setUnnamedAddr(UnnamedAddr); 29697a7e6055SDimitry Andric if (Record.size() > 10 && Record[10] != 0) 29707a7e6055SDimitry Andric FunctionPrologues.push_back(std::make_pair(Func, Record[10] - 1)); 29717a7e6055SDimitry Andric 29727a7e6055SDimitry Andric if (Record.size() > 11) 29737a7e6055SDimitry Andric Func->setDLLStorageClass(getDecodedDLLStorageClass(Record[11])); 29747a7e6055SDimitry Andric else 29757a7e6055SDimitry Andric upgradeDLLImportExportLinkage(Func, RawLinkage); 29767a7e6055SDimitry Andric 29777a7e6055SDimitry Andric if (Record.size() > 12) { 29787a7e6055SDimitry Andric if (unsigned ComdatID = Record[12]) { 29797a7e6055SDimitry Andric if (ComdatID > ComdatList.size()) 29807a7e6055SDimitry Andric return error("Invalid function comdat ID"); 29817a7e6055SDimitry Andric Func->setComdat(ComdatList[ComdatID - 1]); 29827a7e6055SDimitry Andric } 29837a7e6055SDimitry Andric } else if (hasImplicitComdat(RawLinkage)) { 29847a7e6055SDimitry Andric Func->setComdat(reinterpret_cast<Comdat *>(1)); 29857a7e6055SDimitry Andric } 29867a7e6055SDimitry Andric 29877a7e6055SDimitry Andric if (Record.size() > 13 && Record[13] != 0) 29887a7e6055SDimitry Andric FunctionPrefixes.push_back(std::make_pair(Func, Record[13] - 1)); 29897a7e6055SDimitry Andric 29907a7e6055SDimitry Andric if (Record.size() > 14 && Record[14] != 0) 29917a7e6055SDimitry Andric FunctionPersonalityFns.push_back(std::make_pair(Func, Record[14] - 1)); 29927a7e6055SDimitry Andric 29932cab237bSDimitry Andric if (Record.size() > 15) { 29942cab237bSDimitry Andric Func->setDSOLocal(getDecodedDSOLocal(Record[15])); 29952cab237bSDimitry Andric } 29962cab237bSDimitry Andric 29977a7e6055SDimitry Andric ValueList.push_back(Func); 29987a7e6055SDimitry Andric 29997a7e6055SDimitry Andric // If this is a function with a body, remember the prototype we are 30007a7e6055SDimitry Andric // creating now, so that we can match up the body with them later. 30017a7e6055SDimitry Andric if (!isProto) { 30027a7e6055SDimitry Andric Func->setIsMaterializable(true); 30037a7e6055SDimitry Andric FunctionsWithBodies.push_back(Func); 30047a7e6055SDimitry Andric DeferredFunctionInfo[Func] = 0; 30057a7e6055SDimitry Andric } 30067a7e6055SDimitry Andric return Error::success(); 30077a7e6055SDimitry Andric } 30087a7e6055SDimitry Andric 30097a7e6055SDimitry Andric Error BitcodeReader::parseGlobalIndirectSymbolRecord( 30107a7e6055SDimitry Andric unsigned BitCode, ArrayRef<uint64_t> Record) { 30116bc11b14SDimitry Andric // v1 ALIAS_OLD: [alias type, aliasee val#, linkage] (name in VST) 30126bc11b14SDimitry Andric // v1 ALIAS: [alias type, addrspace, aliasee val#, linkage, visibility, 30132cab237bSDimitry Andric // dllstorageclass, threadlocal, unnamed_addr, 30142cab237bSDimitry Andric // preemption specifier] (name in VST) 30156bc11b14SDimitry Andric // v1 IFUNC: [alias type, addrspace, aliasee val#, linkage, 30162cab237bSDimitry Andric // visibility, dllstorageclass, threadlocal, unnamed_addr, 30172cab237bSDimitry Andric // preemption specifier] (name in VST) 30186bc11b14SDimitry Andric // v2: [strtab_offset, strtab_size, v1] 30196bc11b14SDimitry Andric StringRef Name; 30206bc11b14SDimitry Andric std::tie(Name, Record) = readNameFromStrtab(Record); 30216bc11b14SDimitry Andric 30227a7e6055SDimitry Andric bool NewRecord = BitCode != bitc::MODULE_CODE_ALIAS_OLD; 30237a7e6055SDimitry Andric if (Record.size() < (3 + (unsigned)NewRecord)) 30247a7e6055SDimitry Andric return error("Invalid record"); 30257a7e6055SDimitry Andric unsigned OpNum = 0; 30267a7e6055SDimitry Andric Type *Ty = getTypeByID(Record[OpNum++]); 30277a7e6055SDimitry Andric if (!Ty) 30287a7e6055SDimitry Andric return error("Invalid record"); 30297a7e6055SDimitry Andric 30307a7e6055SDimitry Andric unsigned AddrSpace; 30317a7e6055SDimitry Andric if (!NewRecord) { 30327a7e6055SDimitry Andric auto *PTy = dyn_cast<PointerType>(Ty); 30337a7e6055SDimitry Andric if (!PTy) 30347a7e6055SDimitry Andric return error("Invalid type for value"); 30357a7e6055SDimitry Andric Ty = PTy->getElementType(); 30367a7e6055SDimitry Andric AddrSpace = PTy->getAddressSpace(); 30377a7e6055SDimitry Andric } else { 30387a7e6055SDimitry Andric AddrSpace = Record[OpNum++]; 30397a7e6055SDimitry Andric } 30407a7e6055SDimitry Andric 30417a7e6055SDimitry Andric auto Val = Record[OpNum++]; 30427a7e6055SDimitry Andric auto Linkage = Record[OpNum++]; 30437a7e6055SDimitry Andric GlobalIndirectSymbol *NewGA; 30447a7e6055SDimitry Andric if (BitCode == bitc::MODULE_CODE_ALIAS || 30457a7e6055SDimitry Andric BitCode == bitc::MODULE_CODE_ALIAS_OLD) 30466bc11b14SDimitry Andric NewGA = GlobalAlias::create(Ty, AddrSpace, getDecodedLinkage(Linkage), Name, 30477a7e6055SDimitry Andric TheModule); 30487a7e6055SDimitry Andric else 30496bc11b14SDimitry Andric NewGA = GlobalIFunc::create(Ty, AddrSpace, getDecodedLinkage(Linkage), Name, 30507a7e6055SDimitry Andric nullptr, TheModule); 30517a7e6055SDimitry Andric // Old bitcode files didn't have visibility field. 30527a7e6055SDimitry Andric // Local linkage must have default visibility. 30537a7e6055SDimitry Andric if (OpNum != Record.size()) { 30547a7e6055SDimitry Andric auto VisInd = OpNum++; 30557a7e6055SDimitry Andric if (!NewGA->hasLocalLinkage()) 30567a7e6055SDimitry Andric // FIXME: Change to an error if non-default in 4.0. 30577a7e6055SDimitry Andric NewGA->setVisibility(getDecodedVisibility(Record[VisInd])); 30587a7e6055SDimitry Andric } 30597a7e6055SDimitry Andric if (OpNum != Record.size()) 30607a7e6055SDimitry Andric NewGA->setDLLStorageClass(getDecodedDLLStorageClass(Record[OpNum++])); 30617a7e6055SDimitry Andric else 30627a7e6055SDimitry Andric upgradeDLLImportExportLinkage(NewGA, Linkage); 30637a7e6055SDimitry Andric if (OpNum != Record.size()) 30647a7e6055SDimitry Andric NewGA->setThreadLocalMode(getDecodedThreadLocalMode(Record[OpNum++])); 30657a7e6055SDimitry Andric if (OpNum != Record.size()) 30667a7e6055SDimitry Andric NewGA->setUnnamedAddr(getDecodedUnnamedAddrType(Record[OpNum++])); 30672cab237bSDimitry Andric if (OpNum != Record.size()) 30682cab237bSDimitry Andric NewGA->setDSOLocal(getDecodedDSOLocal(Record[OpNum++])); 30697a7e6055SDimitry Andric ValueList.push_back(NewGA); 30707a7e6055SDimitry Andric IndirectSymbolInits.push_back(std::make_pair(NewGA, Val)); 30717a7e6055SDimitry Andric return Error::success(); 30727a7e6055SDimitry Andric } 30737a7e6055SDimitry Andric 3074d88c1a5aSDimitry Andric Error BitcodeReader::parseModule(uint64_t ResumeBit, 30757d523365SDimitry Andric bool ShouldLazyLoadMetadata) { 30767d523365SDimitry Andric if (ResumeBit) 30777d523365SDimitry Andric Stream.JumpToBit(ResumeBit); 3078dff0c46cSDimitry Andric else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID)) 30798f0fd8f6SDimitry Andric return error("Invalid record"); 3080dff0c46cSDimitry Andric 3081dff0c46cSDimitry Andric SmallVector<uint64_t, 64> Record; 3082dff0c46cSDimitry Andric 3083dff0c46cSDimitry Andric // Read all the records for this module. 3084d88c1a5aSDimitry Andric while (true) { 3085139f7f9bSDimitry Andric BitstreamEntry Entry = Stream.advance(); 3086dff0c46cSDimitry Andric 3087139f7f9bSDimitry Andric switch (Entry.Kind) { 3088139f7f9bSDimitry Andric case BitstreamEntry::Error: 30898f0fd8f6SDimitry Andric return error("Malformed block"); 3090139f7f9bSDimitry Andric case BitstreamEntry::EndBlock: 30918f0fd8f6SDimitry Andric return globalCleanup(); 3092dff0c46cSDimitry Andric 3093139f7f9bSDimitry Andric case BitstreamEntry::SubBlock: 3094139f7f9bSDimitry Andric switch (Entry.ID) { 3095f22ef01cSRoman Divacky default: // Skip unknown content. 3096f22ef01cSRoman Divacky if (Stream.SkipBlock()) 30978f0fd8f6SDimitry Andric return error("Invalid record"); 3098f22ef01cSRoman Divacky break; 3099f22ef01cSRoman Divacky case bitc::BLOCKINFO_BLOCK_ID: 3100d88c1a5aSDimitry Andric if (readBlockInfo()) 31018f0fd8f6SDimitry Andric return error("Malformed block"); 3102f22ef01cSRoman Divacky break; 3103f22ef01cSRoman Divacky case bitc::PARAMATTR_BLOCK_ID: 3104d88c1a5aSDimitry Andric if (Error Err = parseAttributeBlock()) 3105d88c1a5aSDimitry Andric return Err; 3106f22ef01cSRoman Divacky break; 3107139f7f9bSDimitry Andric case bitc::PARAMATTR_GROUP_BLOCK_ID: 3108d88c1a5aSDimitry Andric if (Error Err = parseAttributeGroupBlock()) 3109d88c1a5aSDimitry Andric return Err; 3110139f7f9bSDimitry Andric break; 311117a519f9SDimitry Andric case bitc::TYPE_BLOCK_ID_NEW: 3112d88c1a5aSDimitry Andric if (Error Err = parseTypeTable()) 3113d88c1a5aSDimitry Andric return Err; 3114f22ef01cSRoman Divacky break; 3115f22ef01cSRoman Divacky case bitc::VALUE_SYMTAB_BLOCK_ID: 31167d523365SDimitry Andric if (!SeenValueSymbolTable) { 31177d523365SDimitry Andric // Either this is an old form VST without function index and an 31187d523365SDimitry Andric // associated VST forward declaration record (which would have caused 31197d523365SDimitry Andric // the VST to be jumped to and parsed before it was encountered 31207d523365SDimitry Andric // normally in the stream), or there were no function blocks to 31217d523365SDimitry Andric // trigger an earlier parsing of the VST. 31227d523365SDimitry Andric assert(VSTOffset == 0 || FunctionsWithBodies.empty()); 3123d88c1a5aSDimitry Andric if (Error Err = parseValueSymbolTable()) 3124d88c1a5aSDimitry Andric return Err; 3125dff0c46cSDimitry Andric SeenValueSymbolTable = true; 31267d523365SDimitry Andric } else { 31277d523365SDimitry Andric // We must have had a VST forward declaration record, which caused 31287d523365SDimitry Andric // the parser to jump to and parse the VST earlier. 31297d523365SDimitry Andric assert(VSTOffset > 0); 31307d523365SDimitry Andric if (Stream.SkipBlock()) 31317d523365SDimitry Andric return error("Invalid record"); 31327d523365SDimitry Andric } 3133f22ef01cSRoman Divacky break; 3134f22ef01cSRoman Divacky case bitc::CONSTANTS_BLOCK_ID: 3135d88c1a5aSDimitry Andric if (Error Err = parseConstants()) 3136d88c1a5aSDimitry Andric return Err; 3137d88c1a5aSDimitry Andric if (Error Err = resolveGlobalAndIndirectSymbolInits()) 3138d88c1a5aSDimitry Andric return Err; 3139f22ef01cSRoman Divacky break; 3140f22ef01cSRoman Divacky case bitc::METADATA_BLOCK_ID: 3141d88c1a5aSDimitry Andric if (ShouldLazyLoadMetadata) { 3142d88c1a5aSDimitry Andric if (Error Err = rememberAndSkipMetadata()) 3143d88c1a5aSDimitry Andric return Err; 3144ff0cc061SDimitry Andric break; 3145ff0cc061SDimitry Andric } 3146ff0cc061SDimitry Andric assert(DeferredMetadataInfo.empty() && "Unexpected deferred metadata"); 3147d88c1a5aSDimitry Andric if (Error Err = MDLoader->parseModuleMetadata()) 3148d88c1a5aSDimitry Andric return Err; 31497d523365SDimitry Andric break; 31507d523365SDimitry Andric case bitc::METADATA_KIND_BLOCK_ID: 3151d88c1a5aSDimitry Andric if (Error Err = MDLoader->parseMetadataKinds()) 3152d88c1a5aSDimitry Andric return Err; 3153f22ef01cSRoman Divacky break; 3154f22ef01cSRoman Divacky case bitc::FUNCTION_BLOCK_ID: 3155f22ef01cSRoman Divacky // If this is the first function body we've seen, reverse the 3156f22ef01cSRoman Divacky // FunctionsWithBodies list. 3157dff0c46cSDimitry Andric if (!SeenFirstFunctionBody) { 3158f22ef01cSRoman Divacky std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end()); 3159d88c1a5aSDimitry Andric if (Error Err = globalCleanup()) 3160d88c1a5aSDimitry Andric return Err; 3161dff0c46cSDimitry Andric SeenFirstFunctionBody = true; 3162f22ef01cSRoman Divacky } 3163f22ef01cSRoman Divacky 31647d523365SDimitry Andric if (VSTOffset > 0) { 31657d523365SDimitry Andric // If we have a VST forward declaration record, make sure we 31667d523365SDimitry Andric // parse the VST now if we haven't already. It is needed to 31677d523365SDimitry Andric // set up the DeferredFunctionInfo vector for lazy reading. 31687d523365SDimitry Andric if (!SeenValueSymbolTable) { 3169d88c1a5aSDimitry Andric if (Error Err = BitcodeReader::parseValueSymbolTable(VSTOffset)) 3170d88c1a5aSDimitry Andric return Err; 31717d523365SDimitry Andric SeenValueSymbolTable = true; 31727d523365SDimitry Andric // Fall through so that we record the NextUnreadBit below. 31737d523365SDimitry Andric // This is necessary in case we have an anonymous function that 31747d523365SDimitry Andric // is later materialized. Since it will not have a VST entry we 31757d523365SDimitry Andric // need to fall back to the lazy parse to find its offset. 31767d523365SDimitry Andric } else { 31777d523365SDimitry Andric // If we have a VST forward declaration record, but have already 31787d523365SDimitry Andric // parsed the VST (just above, when the first function body was 31797d523365SDimitry Andric // encountered here), then we are resuming the parse after 31807d523365SDimitry Andric // materializing functions. The ResumeBit points to the 31817d523365SDimitry Andric // start of the last function block recorded in the 31827d523365SDimitry Andric // DeferredFunctionInfo map. Skip it. 31837d523365SDimitry Andric if (Stream.SkipBlock()) 31847d523365SDimitry Andric return error("Invalid record"); 31857d523365SDimitry Andric continue; 31867d523365SDimitry Andric } 31877d523365SDimitry Andric } 31887d523365SDimitry Andric 31897d523365SDimitry Andric // Support older bitcode files that did not have the function 31907d523365SDimitry Andric // index in the VST, nor a VST forward declaration record, as 31917d523365SDimitry Andric // well as anonymous functions that do not have VST entries. 31927d523365SDimitry Andric // Build the DeferredFunctionInfo vector on the fly. 3193d88c1a5aSDimitry Andric if (Error Err = rememberAndSkipFunctionBody()) 3194d88c1a5aSDimitry Andric return Err; 31957d523365SDimitry Andric 31963dac3a9bSDimitry Andric // Suspend parsing when we reach the function bodies. Subsequent 31973dac3a9bSDimitry Andric // materialization calls will resume it when necessary. If the bitcode 31983dac3a9bSDimitry Andric // file is old, the symbol table will be at the end instead and will not 31993dac3a9bSDimitry Andric // have been seen yet. In this case, just finish the parse now. 32003dac3a9bSDimitry Andric if (SeenValueSymbolTable) { 3201dff0c46cSDimitry Andric NextUnreadBit = Stream.GetCurrentBitNo(); 3202d88c1a5aSDimitry Andric // After the VST has been parsed, we need to make sure intrinsic name 3203d88c1a5aSDimitry Andric // are auto-upgraded. 3204d88c1a5aSDimitry Andric return globalCleanup(); 3205dff0c46cSDimitry Andric } 3206dff0c46cSDimitry Andric break; 3207dff0c46cSDimitry Andric case bitc::USELIST_BLOCK_ID: 3208d88c1a5aSDimitry Andric if (Error Err = parseUseLists()) 3209d88c1a5aSDimitry Andric return Err; 3210f22ef01cSRoman Divacky break; 32117d523365SDimitry Andric case bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID: 3212d88c1a5aSDimitry Andric if (Error Err = parseOperandBundleTags()) 3213d88c1a5aSDimitry Andric return Err; 32147d523365SDimitry Andric break; 3215c4394386SDimitry Andric case bitc::SYNC_SCOPE_NAMES_BLOCK_ID: 3216c4394386SDimitry Andric if (Error Err = parseSyncScopeNames()) 3217c4394386SDimitry Andric return Err; 3218c4394386SDimitry Andric break; 3219f22ef01cSRoman Divacky } 3220f22ef01cSRoman Divacky continue; 3221139f7f9bSDimitry Andric 3222139f7f9bSDimitry Andric case BitstreamEntry::Record: 3223139f7f9bSDimitry Andric // The interesting case. 3224139f7f9bSDimitry Andric break; 3225f22ef01cSRoman Divacky } 3226f22ef01cSRoman Divacky 3227f22ef01cSRoman Divacky // Read a record. 32287d523365SDimitry Andric auto BitCode = Stream.readRecord(Entry.ID, Record); 32297d523365SDimitry Andric switch (BitCode) { 3230f22ef01cSRoman Divacky default: break; // Default behavior, ignore unknown content. 32317a7e6055SDimitry Andric case bitc::MODULE_CODE_VERSION: { 32327a7e6055SDimitry Andric Expected<unsigned> VersionOrErr = parseVersionRecord(Record); 32337a7e6055SDimitry Andric if (!VersionOrErr) 32347a7e6055SDimitry Andric return VersionOrErr.takeError(); 32357a7e6055SDimitry Andric UseRelativeIDs = *VersionOrErr >= 1; 32363861d79fSDimitry Andric break; 32373861d79fSDimitry Andric } 3238f22ef01cSRoman Divacky case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N] 3239f22ef01cSRoman Divacky std::string S; 32408f0fd8f6SDimitry Andric if (convertToString(Record, 0, S)) 32418f0fd8f6SDimitry Andric return error("Invalid record"); 3242f22ef01cSRoman Divacky TheModule->setTargetTriple(S); 3243f22ef01cSRoman Divacky break; 3244f22ef01cSRoman Divacky } 3245f22ef01cSRoman Divacky case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N] 3246f22ef01cSRoman Divacky std::string S; 32478f0fd8f6SDimitry Andric if (convertToString(Record, 0, S)) 32488f0fd8f6SDimitry Andric return error("Invalid record"); 3249f22ef01cSRoman Divacky TheModule->setDataLayout(S); 3250f22ef01cSRoman Divacky break; 3251f22ef01cSRoman Divacky } 3252f22ef01cSRoman Divacky case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N] 3253f22ef01cSRoman Divacky std::string S; 32548f0fd8f6SDimitry Andric if (convertToString(Record, 0, S)) 32558f0fd8f6SDimitry Andric return error("Invalid record"); 3256f22ef01cSRoman Divacky TheModule->setModuleInlineAsm(S); 3257f22ef01cSRoman Divacky break; 3258f22ef01cSRoman Divacky } 3259f22ef01cSRoman Divacky case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N] 3260139f7f9bSDimitry Andric // FIXME: Remove in 4.0. 3261f22ef01cSRoman Divacky std::string S; 32628f0fd8f6SDimitry Andric if (convertToString(Record, 0, S)) 32638f0fd8f6SDimitry Andric return error("Invalid record"); 3264139f7f9bSDimitry Andric // Ignore value. 3265f22ef01cSRoman Divacky break; 3266f22ef01cSRoman Divacky } 3267f22ef01cSRoman Divacky case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N] 3268f22ef01cSRoman Divacky std::string S; 32698f0fd8f6SDimitry Andric if (convertToString(Record, 0, S)) 32708f0fd8f6SDimitry Andric return error("Invalid record"); 3271f22ef01cSRoman Divacky SectionTable.push_back(S); 3272f22ef01cSRoman Divacky break; 3273f22ef01cSRoman Divacky } 3274f22ef01cSRoman Divacky case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N] 3275f22ef01cSRoman Divacky std::string S; 32768f0fd8f6SDimitry Andric if (convertToString(Record, 0, S)) 32778f0fd8f6SDimitry Andric return error("Invalid record"); 3278f22ef01cSRoman Divacky GCTable.push_back(S); 3279f22ef01cSRoman Divacky break; 3280f22ef01cSRoman Divacky } 32812cab237bSDimitry Andric case bitc::MODULE_CODE_COMDAT: 32827a7e6055SDimitry Andric if (Error Err = parseComdatRecord(Record)) 32837a7e6055SDimitry Andric return Err; 328491bc56edSDimitry Andric break; 32852cab237bSDimitry Andric case bitc::MODULE_CODE_GLOBALVAR: 32867a7e6055SDimitry Andric if (Error Err = parseGlobalVarRecord(Record)) 3287d88c1a5aSDimitry Andric return Err; 3288f22ef01cSRoman Divacky break; 32892cab237bSDimitry Andric case bitc::MODULE_CODE_FUNCTION: 32907a7e6055SDimitry Andric if (Error Err = parseFunctionRecord(Record)) 3291d88c1a5aSDimitry Andric return Err; 3292f22ef01cSRoman Divacky break; 32933ca95b02SDimitry Andric case bitc::MODULE_CODE_IFUNC: 32947d523365SDimitry Andric case bitc::MODULE_CODE_ALIAS: 32952cab237bSDimitry Andric case bitc::MODULE_CODE_ALIAS_OLD: 32967a7e6055SDimitry Andric if (Error Err = parseGlobalIndirectSymbolRecord(BitCode, Record)) 32977a7e6055SDimitry Andric return Err; 3298f22ef01cSRoman Divacky break; 32997d523365SDimitry Andric /// MODULE_CODE_VSTOFFSET: [offset] 33007d523365SDimitry Andric case bitc::MODULE_CODE_VSTOFFSET: 33017d523365SDimitry Andric if (Record.size() < 1) 33027d523365SDimitry Andric return error("Invalid record"); 3303d88c1a5aSDimitry Andric // Note that we subtract 1 here because the offset is relative to one word 3304d88c1a5aSDimitry Andric // before the start of the identification or module block, which was 3305d88c1a5aSDimitry Andric // historically always the start of the regular bitcode header. 3306d88c1a5aSDimitry Andric VSTOffset = Record[0] - 1; 33077d523365SDimitry Andric break; 33083ca95b02SDimitry Andric /// MODULE_CODE_SOURCE_FILENAME: [namechar x N] 33093ca95b02SDimitry Andric case bitc::MODULE_CODE_SOURCE_FILENAME: 33103ca95b02SDimitry Andric SmallString<128> ValueName; 33113ca95b02SDimitry Andric if (convertToString(Record, 0, ValueName)) 33127d523365SDimitry Andric return error("Invalid record"); 33133ca95b02SDimitry Andric TheModule->setSourceFileName(ValueName); 33147d523365SDimitry Andric break; 3315f22ef01cSRoman Divacky } 3316f22ef01cSRoman Divacky Record.clear(); 3317f22ef01cSRoman Divacky } 3318f22ef01cSRoman Divacky } 3319f22ef01cSRoman Divacky 3320d88c1a5aSDimitry Andric Error BitcodeReader::parseBitcodeInto(Module *M, bool ShouldLazyLoadMetadata, 3321d88c1a5aSDimitry Andric bool IsImporting) { 33228f0fd8f6SDimitry Andric TheModule = M; 3323d88c1a5aSDimitry Andric MDLoader = MetadataLoader(Stream, *M, ValueList, IsImporting, 3324d88c1a5aSDimitry Andric [&](unsigned ID) { return getTypeByID(ID); }); 33257d523365SDimitry Andric return parseModule(0, ShouldLazyLoadMetadata); 3326f22ef01cSRoman Divacky } 3327f22ef01cSRoman Divacky 3328d88c1a5aSDimitry Andric Error BitcodeReader::typeCheckLoadStoreInst(Type *ValType, Type *PtrType) { 3329ff0cc061SDimitry Andric if (!isa<PointerType>(PtrType)) 3330d88c1a5aSDimitry Andric return error("Load/Store operand is not a pointer type"); 3331ff0cc061SDimitry Andric Type *ElemType = cast<PointerType>(PtrType)->getElementType(); 3332ff0cc061SDimitry Andric 3333ff0cc061SDimitry Andric if (ValType && ValType != ElemType) 3334d88c1a5aSDimitry Andric return error("Explicit load/store type does not match pointee " 33357d523365SDimitry Andric "type of pointer operand"); 3336ff0cc061SDimitry Andric if (!PointerType::isLoadableOrStorableType(ElemType)) 3337d88c1a5aSDimitry Andric return error("Cannot load/store from pointer"); 3338d88c1a5aSDimitry Andric return Error::success(); 3339ff0cc061SDimitry Andric } 3340ff0cc061SDimitry Andric 33418f0fd8f6SDimitry Andric /// Lazily parse the specified function body block. 3342d88c1a5aSDimitry Andric Error BitcodeReader::parseFunctionBody(Function *F) { 3343f22ef01cSRoman Divacky if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID)) 33448f0fd8f6SDimitry Andric return error("Invalid record"); 3345f22ef01cSRoman Divacky 33463ca95b02SDimitry Andric // Unexpected unresolved metadata when parsing function. 3347d88c1a5aSDimitry Andric if (MDLoader->hasFwdRefs()) 33483ca95b02SDimitry Andric return error("Invalid function metadata: incoming forward references"); 33493ca95b02SDimitry Andric 3350f22ef01cSRoman Divacky InstructionList.clear(); 3351f22ef01cSRoman Divacky unsigned ModuleValueListSize = ValueList.size(); 3352d88c1a5aSDimitry Andric unsigned ModuleMDLoaderSize = MDLoader->size(); 3353f22ef01cSRoman Divacky 3354f22ef01cSRoman Divacky // Add all the function arguments to the value table. 33557d523365SDimitry Andric for (Argument &I : F->args()) 33567d523365SDimitry Andric ValueList.push_back(&I); 3357f22ef01cSRoman Divacky 3358f22ef01cSRoman Divacky unsigned NextValueNo = ValueList.size(); 335991bc56edSDimitry Andric BasicBlock *CurBB = nullptr; 3360f22ef01cSRoman Divacky unsigned CurBBNo = 0; 3361f22ef01cSRoman Divacky 3362f22ef01cSRoman Divacky DebugLoc LastLoc; 336339d628a0SDimitry Andric auto getLastInstruction = [&]() -> Instruction * { 336439d628a0SDimitry Andric if (CurBB && !CurBB->empty()) 336539d628a0SDimitry Andric return &CurBB->back(); 336639d628a0SDimitry Andric else if (CurBBNo && FunctionBBs[CurBBNo - 1] && 336739d628a0SDimitry Andric !FunctionBBs[CurBBNo - 1]->empty()) 336839d628a0SDimitry Andric return &FunctionBBs[CurBBNo - 1]->back(); 336939d628a0SDimitry Andric return nullptr; 337039d628a0SDimitry Andric }; 3371f22ef01cSRoman Divacky 33727d523365SDimitry Andric std::vector<OperandBundleDef> OperandBundles; 33737d523365SDimitry Andric 3374f22ef01cSRoman Divacky // Read all the records. 3375f22ef01cSRoman Divacky SmallVector<uint64_t, 64> Record; 3376d88c1a5aSDimitry Andric 3377d88c1a5aSDimitry Andric while (true) { 3378139f7f9bSDimitry Andric BitstreamEntry Entry = Stream.advance(); 3379f22ef01cSRoman Divacky 3380139f7f9bSDimitry Andric switch (Entry.Kind) { 3381139f7f9bSDimitry Andric case BitstreamEntry::Error: 33828f0fd8f6SDimitry Andric return error("Malformed block"); 3383139f7f9bSDimitry Andric case BitstreamEntry::EndBlock: 3384139f7f9bSDimitry Andric goto OutOfRecordLoop; 3385139f7f9bSDimitry Andric 3386139f7f9bSDimitry Andric case BitstreamEntry::SubBlock: 3387139f7f9bSDimitry Andric switch (Entry.ID) { 3388f22ef01cSRoman Divacky default: // Skip unknown content. 3389f22ef01cSRoman Divacky if (Stream.SkipBlock()) 33908f0fd8f6SDimitry Andric return error("Invalid record"); 3391f22ef01cSRoman Divacky break; 3392f22ef01cSRoman Divacky case bitc::CONSTANTS_BLOCK_ID: 3393d88c1a5aSDimitry Andric if (Error Err = parseConstants()) 3394d88c1a5aSDimitry Andric return Err; 3395f22ef01cSRoman Divacky NextValueNo = ValueList.size(); 3396f22ef01cSRoman Divacky break; 3397f22ef01cSRoman Divacky case bitc::VALUE_SYMTAB_BLOCK_ID: 3398d88c1a5aSDimitry Andric if (Error Err = parseValueSymbolTable()) 3399d88c1a5aSDimitry Andric return Err; 3400f22ef01cSRoman Divacky break; 3401f22ef01cSRoman Divacky case bitc::METADATA_ATTACHMENT_ID: 3402d88c1a5aSDimitry Andric if (Error Err = MDLoader->parseMetadataAttachment(*F, InstructionList)) 3403d88c1a5aSDimitry Andric return Err; 3404f22ef01cSRoman Divacky break; 3405f22ef01cSRoman Divacky case bitc::METADATA_BLOCK_ID: 3406d88c1a5aSDimitry Andric assert(DeferredMetadataInfo.empty() && 3407d88c1a5aSDimitry Andric "Must read all module-level metadata before function-level"); 3408d88c1a5aSDimitry Andric if (Error Err = MDLoader->parseFunctionMetadata()) 3409d88c1a5aSDimitry Andric return Err; 3410f22ef01cSRoman Divacky break; 341139d628a0SDimitry Andric case bitc::USELIST_BLOCK_ID: 3412d88c1a5aSDimitry Andric if (Error Err = parseUseLists()) 3413d88c1a5aSDimitry Andric return Err; 341439d628a0SDimitry Andric break; 3415f22ef01cSRoman Divacky } 3416f22ef01cSRoman Divacky continue; 3417f22ef01cSRoman Divacky 3418139f7f9bSDimitry Andric case BitstreamEntry::Record: 3419139f7f9bSDimitry Andric // The interesting case. 3420139f7f9bSDimitry Andric break; 3421f22ef01cSRoman Divacky } 3422f22ef01cSRoman Divacky 3423f22ef01cSRoman Divacky // Read a record. 3424f22ef01cSRoman Divacky Record.clear(); 342591bc56edSDimitry Andric Instruction *I = nullptr; 3426139f7f9bSDimitry Andric unsigned BitCode = Stream.readRecord(Entry.ID, Record); 3427f22ef01cSRoman Divacky switch (BitCode) { 3428f22ef01cSRoman Divacky default: // Default behavior: reject 34298f0fd8f6SDimitry Andric return error("Invalid value"); 343039d628a0SDimitry Andric case bitc::FUNC_CODE_DECLAREBLOCKS: { // DECLAREBLOCKS: [nblocks] 3431f22ef01cSRoman Divacky if (Record.size() < 1 || Record[0] == 0) 34328f0fd8f6SDimitry Andric return error("Invalid record"); 3433f22ef01cSRoman Divacky // Create all the basic blocks for the function. 3434f22ef01cSRoman Divacky FunctionBBs.resize(Record[0]); 343539d628a0SDimitry Andric 343639d628a0SDimitry Andric // See if anything took the address of blocks in this function. 343739d628a0SDimitry Andric auto BBFRI = BasicBlockFwdRefs.find(F); 343839d628a0SDimitry Andric if (BBFRI == BasicBlockFwdRefs.end()) { 3439f22ef01cSRoman Divacky for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i) 3440f22ef01cSRoman Divacky FunctionBBs[i] = BasicBlock::Create(Context, "", F); 344139d628a0SDimitry Andric } else { 344239d628a0SDimitry Andric auto &BBRefs = BBFRI->second; 344339d628a0SDimitry Andric // Check for invalid basic block references. 344439d628a0SDimitry Andric if (BBRefs.size() > FunctionBBs.size()) 34458f0fd8f6SDimitry Andric return error("Invalid ID"); 344639d628a0SDimitry Andric assert(!BBRefs.empty() && "Unexpected empty array"); 344739d628a0SDimitry Andric assert(!BBRefs.front() && "Invalid reference to entry block"); 344839d628a0SDimitry Andric for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E; 344939d628a0SDimitry Andric ++I) 345039d628a0SDimitry Andric if (I < RE && BBRefs[I]) { 345139d628a0SDimitry Andric BBRefs[I]->insertInto(F); 345239d628a0SDimitry Andric FunctionBBs[I] = BBRefs[I]; 345339d628a0SDimitry Andric } else { 345439d628a0SDimitry Andric FunctionBBs[I] = BasicBlock::Create(Context, "", F); 345539d628a0SDimitry Andric } 345639d628a0SDimitry Andric 345739d628a0SDimitry Andric // Erase from the table. 345839d628a0SDimitry Andric BasicBlockFwdRefs.erase(BBFRI); 345939d628a0SDimitry Andric } 346039d628a0SDimitry Andric 3461f22ef01cSRoman Divacky CurBB = FunctionBBs[0]; 3462f22ef01cSRoman Divacky continue; 346339d628a0SDimitry Andric } 3464f22ef01cSRoman Divacky 3465f22ef01cSRoman Divacky case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN 3466f22ef01cSRoman Divacky // This record indicates that the last instruction is at the same 3467f22ef01cSRoman Divacky // location as the previous instruction with a location. 346839d628a0SDimitry Andric I = getLastInstruction(); 3469f22ef01cSRoman Divacky 347091bc56edSDimitry Andric if (!I) 34718f0fd8f6SDimitry Andric return error("Invalid record"); 3472f22ef01cSRoman Divacky I->setDebugLoc(LastLoc); 347391bc56edSDimitry Andric I = nullptr; 3474f22ef01cSRoman Divacky continue; 3475f22ef01cSRoman Divacky 347617a519f9SDimitry Andric case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia] 347739d628a0SDimitry Andric I = getLastInstruction(); 347891bc56edSDimitry Andric if (!I || Record.size() < 4) 34798f0fd8f6SDimitry Andric return error("Invalid record"); 3480f22ef01cSRoman Divacky 3481f22ef01cSRoman Divacky unsigned Line = Record[0], Col = Record[1]; 3482f22ef01cSRoman Divacky unsigned ScopeID = Record[2], IAID = Record[3]; 3483f22ef01cSRoman Divacky 348491bc56edSDimitry Andric MDNode *Scope = nullptr, *IA = nullptr; 34853ca95b02SDimitry Andric if (ScopeID) { 3486d88c1a5aSDimitry Andric Scope = MDLoader->getMDNodeFwdRefOrNull(ScopeID - 1); 34873ca95b02SDimitry Andric if (!Scope) 34883ca95b02SDimitry Andric return error("Invalid record"); 34893ca95b02SDimitry Andric } 34903ca95b02SDimitry Andric if (IAID) { 3491d88c1a5aSDimitry Andric IA = MDLoader->getMDNodeFwdRefOrNull(IAID - 1); 34923ca95b02SDimitry Andric if (!IA) 34933ca95b02SDimitry Andric return error("Invalid record"); 34943ca95b02SDimitry Andric } 3495f22ef01cSRoman Divacky LastLoc = DebugLoc::get(Line, Col, Scope, IA); 3496f22ef01cSRoman Divacky I->setDebugLoc(LastLoc); 349791bc56edSDimitry Andric I = nullptr; 3498f22ef01cSRoman Divacky continue; 3499f22ef01cSRoman Divacky } 3500f22ef01cSRoman Divacky 3501f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode] 3502f22ef01cSRoman Divacky unsigned OpNum = 0; 3503f22ef01cSRoman Divacky Value *LHS, *RHS; 3504f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, LHS) || 35053861d79fSDimitry Andric popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) || 3506f22ef01cSRoman Divacky OpNum+1 > Record.size()) 35078f0fd8f6SDimitry Andric return error("Invalid record"); 3508f22ef01cSRoman Divacky 35098f0fd8f6SDimitry Andric int Opc = getDecodedBinaryOpcode(Record[OpNum++], LHS->getType()); 3510f785676fSDimitry Andric if (Opc == -1) 35118f0fd8f6SDimitry Andric return error("Invalid record"); 3512f22ef01cSRoman Divacky I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS); 3513f22ef01cSRoman Divacky InstructionList.push_back(I); 3514f22ef01cSRoman Divacky if (OpNum < Record.size()) { 3515f22ef01cSRoman Divacky if (Opc == Instruction::Add || 3516f22ef01cSRoman Divacky Opc == Instruction::Sub || 35172754fe60SDimitry Andric Opc == Instruction::Mul || 35182754fe60SDimitry Andric Opc == Instruction::Shl) { 3519f22ef01cSRoman Divacky if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP)) 3520f22ef01cSRoman Divacky cast<BinaryOperator>(I)->setHasNoSignedWrap(true); 3521f22ef01cSRoman Divacky if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP)) 3522f22ef01cSRoman Divacky cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true); 35232754fe60SDimitry Andric } else if (Opc == Instruction::SDiv || 35242754fe60SDimitry Andric Opc == Instruction::UDiv || 35252754fe60SDimitry Andric Opc == Instruction::LShr || 35262754fe60SDimitry Andric Opc == Instruction::AShr) { 35272754fe60SDimitry Andric if (Record[OpNum] & (1 << bitc::PEO_EXACT)) 3528f22ef01cSRoman Divacky cast<BinaryOperator>(I)->setIsExact(true); 3529139f7f9bSDimitry Andric } else if (isa<FPMathOperator>(I)) { 3530875ed548SDimitry Andric FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]); 3531139f7f9bSDimitry Andric if (FMF.any()) 3532139f7f9bSDimitry Andric I->setFastMathFlags(FMF); 3533f22ef01cSRoman Divacky } 3534139f7f9bSDimitry Andric 3535f22ef01cSRoman Divacky } 3536f22ef01cSRoman Divacky break; 3537f22ef01cSRoman Divacky } 3538f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc] 3539f22ef01cSRoman Divacky unsigned OpNum = 0; 3540f22ef01cSRoman Divacky Value *Op; 3541f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, Op) || 3542f22ef01cSRoman Divacky OpNum+2 != Record.size()) 35438f0fd8f6SDimitry Andric return error("Invalid record"); 3544f22ef01cSRoman Divacky 35456122f3e6SDimitry Andric Type *ResTy = getTypeByID(Record[OpNum]); 35468f0fd8f6SDimitry Andric int Opc = getDecodedCastOpcode(Record[OpNum + 1]); 354791bc56edSDimitry Andric if (Opc == -1 || !ResTy) 35488f0fd8f6SDimitry Andric return error("Invalid record"); 354991bc56edSDimitry Andric Instruction *Temp = nullptr; 3550f785676fSDimitry Andric if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) { 3551f785676fSDimitry Andric if (Temp) { 3552f785676fSDimitry Andric InstructionList.push_back(Temp); 3553f785676fSDimitry Andric CurBB->getInstList().push_back(Temp); 3554f785676fSDimitry Andric } 3555f785676fSDimitry Andric } else { 35567d523365SDimitry Andric auto CastOp = (Instruction::CastOps)Opc; 35577d523365SDimitry Andric if (!CastInst::castIsValid(CastOp, Op, ResTy)) 35587d523365SDimitry Andric return error("Invalid cast"); 35597d523365SDimitry Andric I = CastInst::Create(CastOp, Op, ResTy); 3560f785676fSDimitry Andric } 3561f22ef01cSRoman Divacky InstructionList.push_back(I); 3562f22ef01cSRoman Divacky break; 3563f22ef01cSRoman Divacky } 3564ff0cc061SDimitry Andric case bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD: 3565ff0cc061SDimitry Andric case bitc::FUNC_CODE_INST_GEP_OLD: 3566ff0cc061SDimitry Andric case bitc::FUNC_CODE_INST_GEP: { // GEP: type, [n x operands] 3567f22ef01cSRoman Divacky unsigned OpNum = 0; 3568ff0cc061SDimitry Andric 3569ff0cc061SDimitry Andric Type *Ty; 3570ff0cc061SDimitry Andric bool InBounds; 3571ff0cc061SDimitry Andric 3572ff0cc061SDimitry Andric if (BitCode == bitc::FUNC_CODE_INST_GEP) { 3573ff0cc061SDimitry Andric InBounds = Record[OpNum++]; 3574ff0cc061SDimitry Andric Ty = getTypeByID(Record[OpNum++]); 3575ff0cc061SDimitry Andric } else { 3576ff0cc061SDimitry Andric InBounds = BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD; 3577ff0cc061SDimitry Andric Ty = nullptr; 3578ff0cc061SDimitry Andric } 3579ff0cc061SDimitry Andric 3580f22ef01cSRoman Divacky Value *BasePtr; 3581f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr)) 35828f0fd8f6SDimitry Andric return error("Invalid record"); 3583f22ef01cSRoman Divacky 3584ff0cc061SDimitry Andric if (!Ty) 3585d88c1a5aSDimitry Andric Ty = cast<PointerType>(BasePtr->getType()->getScalarType()) 3586ff0cc061SDimitry Andric ->getElementType(); 3587ff0cc061SDimitry Andric else if (Ty != 3588d88c1a5aSDimitry Andric cast<PointerType>(BasePtr->getType()->getScalarType()) 3589ff0cc061SDimitry Andric ->getElementType()) 35908f0fd8f6SDimitry Andric return error( 3591ff0cc061SDimitry Andric "Explicit gep type does not match pointee type of pointer operand"); 3592ff0cc061SDimitry Andric 3593f22ef01cSRoman Divacky SmallVector<Value*, 16> GEPIdx; 3594f22ef01cSRoman Divacky while (OpNum != Record.size()) { 3595f22ef01cSRoman Divacky Value *Op; 3596f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 35978f0fd8f6SDimitry Andric return error("Invalid record"); 3598f22ef01cSRoman Divacky GEPIdx.push_back(Op); 3599f22ef01cSRoman Divacky } 3600f22ef01cSRoman Divacky 3601ff0cc061SDimitry Andric I = GetElementPtrInst::Create(Ty, BasePtr, GEPIdx); 3602ff0cc061SDimitry Andric 3603f22ef01cSRoman Divacky InstructionList.push_back(I); 3604ff0cc061SDimitry Andric if (InBounds) 3605f22ef01cSRoman Divacky cast<GetElementPtrInst>(I)->setIsInBounds(true); 3606f22ef01cSRoman Divacky break; 3607f22ef01cSRoman Divacky } 3608f22ef01cSRoman Divacky 3609f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_EXTRACTVAL: { 3610f22ef01cSRoman Divacky // EXTRACTVAL: [opty, opval, n x indices] 3611f22ef01cSRoman Divacky unsigned OpNum = 0; 3612f22ef01cSRoman Divacky Value *Agg; 3613f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, Agg)) 36148f0fd8f6SDimitry Andric return error("Invalid record"); 3615f22ef01cSRoman Divacky 3616ff0cc061SDimitry Andric unsigned RecSize = Record.size(); 3617ff0cc061SDimitry Andric if (OpNum == RecSize) 36188f0fd8f6SDimitry Andric return error("EXTRACTVAL: Invalid instruction with 0 indices"); 3619ff0cc061SDimitry Andric 3620f22ef01cSRoman Divacky SmallVector<unsigned, 4> EXTRACTVALIdx; 3621ff0cc061SDimitry Andric Type *CurTy = Agg->getType(); 3622ff0cc061SDimitry Andric for (; OpNum != RecSize; ++OpNum) { 3623ff0cc061SDimitry Andric bool IsArray = CurTy->isArrayTy(); 3624ff0cc061SDimitry Andric bool IsStruct = CurTy->isStructTy(); 3625f22ef01cSRoman Divacky uint64_t Index = Record[OpNum]; 3626ff0cc061SDimitry Andric 3627ff0cc061SDimitry Andric if (!IsStruct && !IsArray) 36288f0fd8f6SDimitry Andric return error("EXTRACTVAL: Invalid type"); 3629f22ef01cSRoman Divacky if ((unsigned)Index != Index) 36308f0fd8f6SDimitry Andric return error("Invalid value"); 3631ff0cc061SDimitry Andric if (IsStruct && Index >= CurTy->subtypes().size()) 36328f0fd8f6SDimitry Andric return error("EXTRACTVAL: Invalid struct index"); 3633ff0cc061SDimitry Andric if (IsArray && Index >= CurTy->getArrayNumElements()) 36348f0fd8f6SDimitry Andric return error("EXTRACTVAL: Invalid array index"); 3635f22ef01cSRoman Divacky EXTRACTVALIdx.push_back((unsigned)Index); 3636ff0cc061SDimitry Andric 3637ff0cc061SDimitry Andric if (IsStruct) 3638ff0cc061SDimitry Andric CurTy = CurTy->subtypes()[Index]; 3639ff0cc061SDimitry Andric else 3640ff0cc061SDimitry Andric CurTy = CurTy->subtypes()[0]; 3641f22ef01cSRoman Divacky } 3642f22ef01cSRoman Divacky 364317a519f9SDimitry Andric I = ExtractValueInst::Create(Agg, EXTRACTVALIdx); 3644f22ef01cSRoman Divacky InstructionList.push_back(I); 3645f22ef01cSRoman Divacky break; 3646f22ef01cSRoman Divacky } 3647f22ef01cSRoman Divacky 3648f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_INSERTVAL: { 3649f22ef01cSRoman Divacky // INSERTVAL: [opty, opval, opty, opval, n x indices] 3650f22ef01cSRoman Divacky unsigned OpNum = 0; 3651f22ef01cSRoman Divacky Value *Agg; 3652f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, Agg)) 36538f0fd8f6SDimitry Andric return error("Invalid record"); 3654f22ef01cSRoman Divacky Value *Val; 3655f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, Val)) 36568f0fd8f6SDimitry Andric return error("Invalid record"); 3657f22ef01cSRoman Divacky 3658ff0cc061SDimitry Andric unsigned RecSize = Record.size(); 3659ff0cc061SDimitry Andric if (OpNum == RecSize) 36608f0fd8f6SDimitry Andric return error("INSERTVAL: Invalid instruction with 0 indices"); 3661ff0cc061SDimitry Andric 3662f22ef01cSRoman Divacky SmallVector<unsigned, 4> INSERTVALIdx; 3663ff0cc061SDimitry Andric Type *CurTy = Agg->getType(); 3664ff0cc061SDimitry Andric for (; OpNum != RecSize; ++OpNum) { 3665ff0cc061SDimitry Andric bool IsArray = CurTy->isArrayTy(); 3666ff0cc061SDimitry Andric bool IsStruct = CurTy->isStructTy(); 3667f22ef01cSRoman Divacky uint64_t Index = Record[OpNum]; 3668ff0cc061SDimitry Andric 3669ff0cc061SDimitry Andric if (!IsStruct && !IsArray) 36708f0fd8f6SDimitry Andric return error("INSERTVAL: Invalid type"); 3671f22ef01cSRoman Divacky if ((unsigned)Index != Index) 36728f0fd8f6SDimitry Andric return error("Invalid value"); 3673ff0cc061SDimitry Andric if (IsStruct && Index >= CurTy->subtypes().size()) 36748f0fd8f6SDimitry Andric return error("INSERTVAL: Invalid struct index"); 3675ff0cc061SDimitry Andric if (IsArray && Index >= CurTy->getArrayNumElements()) 36768f0fd8f6SDimitry Andric return error("INSERTVAL: Invalid array index"); 3677ff0cc061SDimitry Andric 3678f22ef01cSRoman Divacky INSERTVALIdx.push_back((unsigned)Index); 3679ff0cc061SDimitry Andric if (IsStruct) 3680ff0cc061SDimitry Andric CurTy = CurTy->subtypes()[Index]; 3681ff0cc061SDimitry Andric else 3682ff0cc061SDimitry Andric CurTy = CurTy->subtypes()[0]; 3683f22ef01cSRoman Divacky } 3684f22ef01cSRoman Divacky 3685ff0cc061SDimitry Andric if (CurTy != Val->getType()) 36868f0fd8f6SDimitry Andric return error("Inserted value type doesn't match aggregate type"); 3687ff0cc061SDimitry Andric 368817a519f9SDimitry Andric I = InsertValueInst::Create(Agg, Val, INSERTVALIdx); 3689f22ef01cSRoman Divacky InstructionList.push_back(I); 3690f22ef01cSRoman Divacky break; 3691f22ef01cSRoman Divacky } 3692f22ef01cSRoman Divacky 3693f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval] 3694f22ef01cSRoman Divacky // obsolete form of select 3695f22ef01cSRoman Divacky // handles select i1 ... in old bitcode 3696f22ef01cSRoman Divacky unsigned OpNum = 0; 3697f22ef01cSRoman Divacky Value *TrueVal, *FalseVal, *Cond; 3698f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) || 36993861d79fSDimitry Andric popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) || 37003861d79fSDimitry Andric popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond)) 37018f0fd8f6SDimitry Andric return error("Invalid record"); 3702f22ef01cSRoman Divacky 3703f22ef01cSRoman Divacky I = SelectInst::Create(Cond, TrueVal, FalseVal); 3704f22ef01cSRoman Divacky InstructionList.push_back(I); 3705f22ef01cSRoman Divacky break; 3706f22ef01cSRoman Divacky } 3707f22ef01cSRoman Divacky 3708f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred] 3709f22ef01cSRoman Divacky // new form of select 3710f22ef01cSRoman Divacky // handles select i1 or select [N x i1] 3711f22ef01cSRoman Divacky unsigned OpNum = 0; 3712f22ef01cSRoman Divacky Value *TrueVal, *FalseVal, *Cond; 3713f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) || 37143861d79fSDimitry Andric popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) || 3715f22ef01cSRoman Divacky getValueTypePair(Record, OpNum, NextValueNo, Cond)) 37168f0fd8f6SDimitry Andric return error("Invalid record"); 3717f22ef01cSRoman Divacky 3718f22ef01cSRoman Divacky // select condition can be either i1 or [N x i1] 37196122f3e6SDimitry Andric if (VectorType* vector_type = 37206122f3e6SDimitry Andric dyn_cast<VectorType>(Cond->getType())) { 3721f22ef01cSRoman Divacky // expect <n x i1> 3722f22ef01cSRoman Divacky if (vector_type->getElementType() != Type::getInt1Ty(Context)) 37238f0fd8f6SDimitry Andric return error("Invalid type for value"); 3724f22ef01cSRoman Divacky } else { 3725f22ef01cSRoman Divacky // expect i1 3726f22ef01cSRoman Divacky if (Cond->getType() != Type::getInt1Ty(Context)) 37278f0fd8f6SDimitry Andric return error("Invalid type for value"); 3728f22ef01cSRoman Divacky } 3729f22ef01cSRoman Divacky 3730f22ef01cSRoman Divacky I = SelectInst::Create(Cond, TrueVal, FalseVal); 3731f22ef01cSRoman Divacky InstructionList.push_back(I); 3732f22ef01cSRoman Divacky break; 3733f22ef01cSRoman Divacky } 3734f22ef01cSRoman Divacky 3735f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval] 3736f22ef01cSRoman Divacky unsigned OpNum = 0; 3737f22ef01cSRoman Divacky Value *Vec, *Idx; 3738f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, Vec) || 373991bc56edSDimitry Andric getValueTypePair(Record, OpNum, NextValueNo, Idx)) 37408f0fd8f6SDimitry Andric return error("Invalid record"); 3741ff0cc061SDimitry Andric if (!Vec->getType()->isVectorTy()) 37428f0fd8f6SDimitry Andric return error("Invalid type for value"); 3743f22ef01cSRoman Divacky I = ExtractElementInst::Create(Vec, Idx); 3744f22ef01cSRoman Divacky InstructionList.push_back(I); 3745f22ef01cSRoman Divacky break; 3746f22ef01cSRoman Divacky } 3747f22ef01cSRoman Divacky 3748f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval] 3749f22ef01cSRoman Divacky unsigned OpNum = 0; 3750f22ef01cSRoman Divacky Value *Vec, *Elt, *Idx; 3751ff0cc061SDimitry Andric if (getValueTypePair(Record, OpNum, NextValueNo, Vec)) 37528f0fd8f6SDimitry Andric return error("Invalid record"); 3753ff0cc061SDimitry Andric if (!Vec->getType()->isVectorTy()) 37548f0fd8f6SDimitry Andric return error("Invalid type for value"); 3755ff0cc061SDimitry Andric if (popValue(Record, OpNum, NextValueNo, 3756f22ef01cSRoman Divacky cast<VectorType>(Vec->getType())->getElementType(), Elt) || 375791bc56edSDimitry Andric getValueTypePair(Record, OpNum, NextValueNo, Idx)) 37588f0fd8f6SDimitry Andric return error("Invalid record"); 3759f22ef01cSRoman Divacky I = InsertElementInst::Create(Vec, Elt, Idx); 3760f22ef01cSRoman Divacky InstructionList.push_back(I); 3761f22ef01cSRoman Divacky break; 3762f22ef01cSRoman Divacky } 3763f22ef01cSRoman Divacky 3764f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval] 3765f22ef01cSRoman Divacky unsigned OpNum = 0; 3766f22ef01cSRoman Divacky Value *Vec1, *Vec2, *Mask; 3767f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) || 37683861d79fSDimitry Andric popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2)) 37698f0fd8f6SDimitry Andric return error("Invalid record"); 3770f22ef01cSRoman Divacky 3771f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, Mask)) 37728f0fd8f6SDimitry Andric return error("Invalid record"); 3773ff0cc061SDimitry Andric if (!Vec1->getType()->isVectorTy() || !Vec2->getType()->isVectorTy()) 37748f0fd8f6SDimitry Andric return error("Invalid type for value"); 3775f22ef01cSRoman Divacky I = new ShuffleVectorInst(Vec1, Vec2, Mask); 3776f22ef01cSRoman Divacky InstructionList.push_back(I); 3777f22ef01cSRoman Divacky break; 3778f22ef01cSRoman Divacky } 3779f22ef01cSRoman Divacky 3780f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred] 3781f22ef01cSRoman Divacky // Old form of ICmp/FCmp returning bool 3782f22ef01cSRoman Divacky // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were 3783f22ef01cSRoman Divacky // both legal on vectors but had different behaviour. 3784f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred] 3785f22ef01cSRoman Divacky // FCmp/ICmp returning bool or vector of bool 3786f22ef01cSRoman Divacky 3787f22ef01cSRoman Divacky unsigned OpNum = 0; 3788f22ef01cSRoman Divacky Value *LHS, *RHS; 3789f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, LHS) || 3790875ed548SDimitry Andric popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS)) 3791875ed548SDimitry Andric return error("Invalid record"); 3792875ed548SDimitry Andric 3793875ed548SDimitry Andric unsigned PredVal = Record[OpNum]; 3794875ed548SDimitry Andric bool IsFP = LHS->getType()->isFPOrFPVectorTy(); 3795875ed548SDimitry Andric FastMathFlags FMF; 3796875ed548SDimitry Andric if (IsFP && Record.size() > OpNum+1) 3797875ed548SDimitry Andric FMF = getDecodedFastMathFlags(Record[++OpNum]); 3798875ed548SDimitry Andric 3799875ed548SDimitry Andric if (OpNum+1 != Record.size()) 38008f0fd8f6SDimitry Andric return error("Invalid record"); 3801f22ef01cSRoman Divacky 3802f22ef01cSRoman Divacky if (LHS->getType()->isFPOrFPVectorTy()) 3803875ed548SDimitry Andric I = new FCmpInst((FCmpInst::Predicate)PredVal, LHS, RHS); 3804f22ef01cSRoman Divacky else 3805875ed548SDimitry Andric I = new ICmpInst((ICmpInst::Predicate)PredVal, LHS, RHS); 3806875ed548SDimitry Andric 3807875ed548SDimitry Andric if (FMF.any()) 3808875ed548SDimitry Andric I->setFastMathFlags(FMF); 3809f22ef01cSRoman Divacky InstructionList.push_back(I); 3810f22ef01cSRoman Divacky break; 3811f22ef01cSRoman Divacky } 3812f22ef01cSRoman Divacky 3813f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>] 3814f22ef01cSRoman Divacky { 3815f22ef01cSRoman Divacky unsigned Size = Record.size(); 3816f22ef01cSRoman Divacky if (Size == 0) { 3817f22ef01cSRoman Divacky I = ReturnInst::Create(Context); 3818f22ef01cSRoman Divacky InstructionList.push_back(I); 3819f22ef01cSRoman Divacky break; 3820f22ef01cSRoman Divacky } 3821f22ef01cSRoman Divacky 3822f22ef01cSRoman Divacky unsigned OpNum = 0; 382391bc56edSDimitry Andric Value *Op = nullptr; 3824f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 38258f0fd8f6SDimitry Andric return error("Invalid record"); 382617a519f9SDimitry Andric if (OpNum != Record.size()) 38278f0fd8f6SDimitry Andric return error("Invalid record"); 3828f22ef01cSRoman Divacky 382917a519f9SDimitry Andric I = ReturnInst::Create(Context, Op); 3830f22ef01cSRoman Divacky InstructionList.push_back(I); 3831f22ef01cSRoman Divacky break; 3832f22ef01cSRoman Divacky } 3833f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#] 3834f22ef01cSRoman Divacky if (Record.size() != 1 && Record.size() != 3) 38358f0fd8f6SDimitry Andric return error("Invalid record"); 3836f22ef01cSRoman Divacky BasicBlock *TrueDest = getBasicBlock(Record[0]); 383791bc56edSDimitry Andric if (!TrueDest) 38388f0fd8f6SDimitry Andric return error("Invalid record"); 3839f22ef01cSRoman Divacky 3840f22ef01cSRoman Divacky if (Record.size() == 1) { 3841f22ef01cSRoman Divacky I = BranchInst::Create(TrueDest); 3842f22ef01cSRoman Divacky InstructionList.push_back(I); 3843f22ef01cSRoman Divacky } 3844f22ef01cSRoman Divacky else { 3845f22ef01cSRoman Divacky BasicBlock *FalseDest = getBasicBlock(Record[1]); 38463861d79fSDimitry Andric Value *Cond = getValue(Record, 2, NextValueNo, 38473861d79fSDimitry Andric Type::getInt1Ty(Context)); 384891bc56edSDimitry Andric if (!FalseDest || !Cond) 38498f0fd8f6SDimitry Andric return error("Invalid record"); 3850f22ef01cSRoman Divacky I = BranchInst::Create(TrueDest, FalseDest, Cond); 3851f22ef01cSRoman Divacky InstructionList.push_back(I); 3852f22ef01cSRoman Divacky } 3853f22ef01cSRoman Divacky break; 3854f22ef01cSRoman Divacky } 38557d523365SDimitry Andric case bitc::FUNC_CODE_INST_CLEANUPRET: { // CLEANUPRET: [val] or [val,bb#] 38567d523365SDimitry Andric if (Record.size() != 1 && Record.size() != 2) 38577d523365SDimitry Andric return error("Invalid record"); 38587d523365SDimitry Andric unsigned Idx = 0; 38597d523365SDimitry Andric Value *CleanupPad = 38607d523365SDimitry Andric getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context)); 38617d523365SDimitry Andric if (!CleanupPad) 38627d523365SDimitry Andric return error("Invalid record"); 38637d523365SDimitry Andric BasicBlock *UnwindDest = nullptr; 38647d523365SDimitry Andric if (Record.size() == 2) { 38657d523365SDimitry Andric UnwindDest = getBasicBlock(Record[Idx++]); 38667d523365SDimitry Andric if (!UnwindDest) 38677d523365SDimitry Andric return error("Invalid record"); 38687d523365SDimitry Andric } 38697d523365SDimitry Andric 38707d523365SDimitry Andric I = CleanupReturnInst::Create(CleanupPad, UnwindDest); 38717d523365SDimitry Andric InstructionList.push_back(I); 38727d523365SDimitry Andric break; 38737d523365SDimitry Andric } 38747d523365SDimitry Andric case bitc::FUNC_CODE_INST_CATCHRET: { // CATCHRET: [val,bb#] 38757d523365SDimitry Andric if (Record.size() != 2) 38767d523365SDimitry Andric return error("Invalid record"); 38777d523365SDimitry Andric unsigned Idx = 0; 38787d523365SDimitry Andric Value *CatchPad = 38797d523365SDimitry Andric getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context)); 38807d523365SDimitry Andric if (!CatchPad) 38817d523365SDimitry Andric return error("Invalid record"); 38827d523365SDimitry Andric BasicBlock *BB = getBasicBlock(Record[Idx++]); 38837d523365SDimitry Andric if (!BB) 38847d523365SDimitry Andric return error("Invalid record"); 38857d523365SDimitry Andric 38867d523365SDimitry Andric I = CatchReturnInst::Create(CatchPad, BB); 38877d523365SDimitry Andric InstructionList.push_back(I); 38887d523365SDimitry Andric break; 38897d523365SDimitry Andric } 38907d523365SDimitry Andric case bitc::FUNC_CODE_INST_CATCHSWITCH: { // CATCHSWITCH: [tok,num,(bb)*,bb?] 38917d523365SDimitry Andric // We must have, at minimum, the outer scope and the number of arguments. 38927d523365SDimitry Andric if (Record.size() < 2) 38937d523365SDimitry Andric return error("Invalid record"); 38947d523365SDimitry Andric 38957d523365SDimitry Andric unsigned Idx = 0; 38967d523365SDimitry Andric 38977d523365SDimitry Andric Value *ParentPad = 38987d523365SDimitry Andric getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context)); 38997d523365SDimitry Andric 39007d523365SDimitry Andric unsigned NumHandlers = Record[Idx++]; 39017d523365SDimitry Andric 39027d523365SDimitry Andric SmallVector<BasicBlock *, 2> Handlers; 39037d523365SDimitry Andric for (unsigned Op = 0; Op != NumHandlers; ++Op) { 39047d523365SDimitry Andric BasicBlock *BB = getBasicBlock(Record[Idx++]); 39057d523365SDimitry Andric if (!BB) 39067d523365SDimitry Andric return error("Invalid record"); 39077d523365SDimitry Andric Handlers.push_back(BB); 39087d523365SDimitry Andric } 39097d523365SDimitry Andric 39107d523365SDimitry Andric BasicBlock *UnwindDest = nullptr; 39117d523365SDimitry Andric if (Idx + 1 == Record.size()) { 39127d523365SDimitry Andric UnwindDest = getBasicBlock(Record[Idx++]); 39137d523365SDimitry Andric if (!UnwindDest) 39147d523365SDimitry Andric return error("Invalid record"); 39157d523365SDimitry Andric } 39167d523365SDimitry Andric 39177d523365SDimitry Andric if (Record.size() != Idx) 39187d523365SDimitry Andric return error("Invalid record"); 39197d523365SDimitry Andric 39207d523365SDimitry Andric auto *CatchSwitch = 39217d523365SDimitry Andric CatchSwitchInst::Create(ParentPad, UnwindDest, NumHandlers); 39227d523365SDimitry Andric for (BasicBlock *Handler : Handlers) 39237d523365SDimitry Andric CatchSwitch->addHandler(Handler); 39247d523365SDimitry Andric I = CatchSwitch; 39257d523365SDimitry Andric InstructionList.push_back(I); 39267d523365SDimitry Andric break; 39277d523365SDimitry Andric } 39287d523365SDimitry Andric case bitc::FUNC_CODE_INST_CATCHPAD: 39297d523365SDimitry Andric case bitc::FUNC_CODE_INST_CLEANUPPAD: { // [tok,num,(ty,val)*] 39307d523365SDimitry Andric // We must have, at minimum, the outer scope and the number of arguments. 39317d523365SDimitry Andric if (Record.size() < 2) 39327d523365SDimitry Andric return error("Invalid record"); 39337d523365SDimitry Andric 39347d523365SDimitry Andric unsigned Idx = 0; 39357d523365SDimitry Andric 39367d523365SDimitry Andric Value *ParentPad = 39377d523365SDimitry Andric getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context)); 39387d523365SDimitry Andric 39397d523365SDimitry Andric unsigned NumArgOperands = Record[Idx++]; 39407d523365SDimitry Andric 39417d523365SDimitry Andric SmallVector<Value *, 2> Args; 39427d523365SDimitry Andric for (unsigned Op = 0; Op != NumArgOperands; ++Op) { 39437d523365SDimitry Andric Value *Val; 39447d523365SDimitry Andric if (getValueTypePair(Record, Idx, NextValueNo, Val)) 39457d523365SDimitry Andric return error("Invalid record"); 39467d523365SDimitry Andric Args.push_back(Val); 39477d523365SDimitry Andric } 39487d523365SDimitry Andric 39497d523365SDimitry Andric if (Record.size() != Idx) 39507d523365SDimitry Andric return error("Invalid record"); 39517d523365SDimitry Andric 39527d523365SDimitry Andric if (BitCode == bitc::FUNC_CODE_INST_CLEANUPPAD) 39537d523365SDimitry Andric I = CleanupPadInst::Create(ParentPad, Args); 39547d523365SDimitry Andric else 39557d523365SDimitry Andric I = CatchPadInst::Create(ParentPad, Args); 39567d523365SDimitry Andric InstructionList.push_back(I); 39577d523365SDimitry Andric break; 39587d523365SDimitry Andric } 3959f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...] 39607ae0e2c9SDimitry Andric // Check magic 39617ae0e2c9SDimitry Andric if ((Record[0] >> 16) == SWITCH_INST_MAGIC) { 3962f785676fSDimitry Andric // "New" SwitchInst format with case ranges. The changes to write this 3963f785676fSDimitry Andric // format were reverted but we still recognize bitcode that uses it. 3964f785676fSDimitry Andric // Hopefully someday we will have support for case ranges and can use 3965f785676fSDimitry Andric // this format again. 39667ae0e2c9SDimitry Andric 39677ae0e2c9SDimitry Andric Type *OpTy = getTypeByID(Record[1]); 39687ae0e2c9SDimitry Andric unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth(); 39697ae0e2c9SDimitry Andric 39703861d79fSDimitry Andric Value *Cond = getValue(Record, 2, NextValueNo, OpTy); 39717ae0e2c9SDimitry Andric BasicBlock *Default = getBasicBlock(Record[3]); 397291bc56edSDimitry Andric if (!OpTy || !Cond || !Default) 39738f0fd8f6SDimitry Andric return error("Invalid record"); 39747ae0e2c9SDimitry Andric 39757ae0e2c9SDimitry Andric unsigned NumCases = Record[4]; 39767ae0e2c9SDimitry Andric 39777ae0e2c9SDimitry Andric SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases); 39787ae0e2c9SDimitry Andric InstructionList.push_back(SI); 39797ae0e2c9SDimitry Andric 39807ae0e2c9SDimitry Andric unsigned CurIdx = 5; 39817ae0e2c9SDimitry Andric for (unsigned i = 0; i != NumCases; ++i) { 3982f785676fSDimitry Andric SmallVector<ConstantInt*, 1> CaseVals; 39837ae0e2c9SDimitry Andric unsigned NumItems = Record[CurIdx++]; 39847ae0e2c9SDimitry Andric for (unsigned ci = 0; ci != NumItems; ++ci) { 39857ae0e2c9SDimitry Andric bool isSingleNumber = Record[CurIdx++]; 39867ae0e2c9SDimitry Andric 39877ae0e2c9SDimitry Andric APInt Low; 39887ae0e2c9SDimitry Andric unsigned ActiveWords = 1; 39897ae0e2c9SDimitry Andric if (ValueBitWidth > 64) 39907ae0e2c9SDimitry Andric ActiveWords = Record[CurIdx++]; 39918f0fd8f6SDimitry Andric Low = readWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords), 39927ae0e2c9SDimitry Andric ValueBitWidth); 39937ae0e2c9SDimitry Andric CurIdx += ActiveWords; 39947ae0e2c9SDimitry Andric 39957ae0e2c9SDimitry Andric if (!isSingleNumber) { 39967ae0e2c9SDimitry Andric ActiveWords = 1; 39977ae0e2c9SDimitry Andric if (ValueBitWidth > 64) 39987ae0e2c9SDimitry Andric ActiveWords = Record[CurIdx++]; 39998f0fd8f6SDimitry Andric APInt High = readWideAPInt( 40008f0fd8f6SDimitry Andric makeArrayRef(&Record[CurIdx], ActiveWords), ValueBitWidth); 40017ae0e2c9SDimitry Andric CurIdx += ActiveWords; 4002f785676fSDimitry Andric 4003f785676fSDimitry Andric // FIXME: It is not clear whether values in the range should be 4004f785676fSDimitry Andric // compared as signed or unsigned values. The partially 4005f785676fSDimitry Andric // implemented changes that used this format in the past used 4006f785676fSDimitry Andric // unsigned comparisons. 4007f785676fSDimitry Andric for ( ; Low.ule(High); ++Low) 4008f785676fSDimitry Andric CaseVals.push_back(ConstantInt::get(Context, Low)); 40097ae0e2c9SDimitry Andric } else 4010f785676fSDimitry Andric CaseVals.push_back(ConstantInt::get(Context, Low)); 40117ae0e2c9SDimitry Andric } 40127ae0e2c9SDimitry Andric BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]); 4013f785676fSDimitry Andric for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(), 4014f785676fSDimitry Andric cve = CaseVals.end(); cvi != cve; ++cvi) 4015f785676fSDimitry Andric SI->addCase(*cvi, DestBB); 40167ae0e2c9SDimitry Andric } 40177ae0e2c9SDimitry Andric I = SI; 40187ae0e2c9SDimitry Andric break; 40197ae0e2c9SDimitry Andric } 40207ae0e2c9SDimitry Andric 40217ae0e2c9SDimitry Andric // Old SwitchInst format without case ranges. 40227ae0e2c9SDimitry Andric 4023f22ef01cSRoman Divacky if (Record.size() < 3 || (Record.size() & 1) == 0) 40248f0fd8f6SDimitry Andric return error("Invalid record"); 40256122f3e6SDimitry Andric Type *OpTy = getTypeByID(Record[0]); 40263861d79fSDimitry Andric Value *Cond = getValue(Record, 1, NextValueNo, OpTy); 4027f22ef01cSRoman Divacky BasicBlock *Default = getBasicBlock(Record[2]); 402891bc56edSDimitry Andric if (!OpTy || !Cond || !Default) 40298f0fd8f6SDimitry Andric return error("Invalid record"); 4030f22ef01cSRoman Divacky unsigned NumCases = (Record.size()-3)/2; 4031f22ef01cSRoman Divacky SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases); 4032f22ef01cSRoman Divacky InstructionList.push_back(SI); 4033f22ef01cSRoman Divacky for (unsigned i = 0, e = NumCases; i != e; ++i) { 4034f22ef01cSRoman Divacky ConstantInt *CaseVal = 4035f22ef01cSRoman Divacky dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy)); 4036f22ef01cSRoman Divacky BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]); 403791bc56edSDimitry Andric if (!CaseVal || !DestBB) { 4038f22ef01cSRoman Divacky delete SI; 40398f0fd8f6SDimitry Andric return error("Invalid record"); 4040f22ef01cSRoman Divacky } 4041f22ef01cSRoman Divacky SI->addCase(CaseVal, DestBB); 4042f22ef01cSRoman Divacky } 4043f22ef01cSRoman Divacky I = SI; 4044f22ef01cSRoman Divacky break; 4045f22ef01cSRoman Divacky } 4046f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...] 4047f22ef01cSRoman Divacky if (Record.size() < 2) 40488f0fd8f6SDimitry Andric return error("Invalid record"); 40496122f3e6SDimitry Andric Type *OpTy = getTypeByID(Record[0]); 40503861d79fSDimitry Andric Value *Address = getValue(Record, 1, NextValueNo, OpTy); 405191bc56edSDimitry Andric if (!OpTy || !Address) 40528f0fd8f6SDimitry Andric return error("Invalid record"); 4053f22ef01cSRoman Divacky unsigned NumDests = Record.size()-2; 4054f22ef01cSRoman Divacky IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests); 4055f22ef01cSRoman Divacky InstructionList.push_back(IBI); 4056f22ef01cSRoman Divacky for (unsigned i = 0, e = NumDests; i != e; ++i) { 4057f22ef01cSRoman Divacky if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) { 4058f22ef01cSRoman Divacky IBI->addDestination(DestBB); 4059f22ef01cSRoman Divacky } else { 4060f22ef01cSRoman Divacky delete IBI; 40618f0fd8f6SDimitry Andric return error("Invalid record"); 4062f22ef01cSRoman Divacky } 4063f22ef01cSRoman Divacky } 4064f22ef01cSRoman Divacky I = IBI; 4065f22ef01cSRoman Divacky break; 4066f22ef01cSRoman Divacky } 4067f22ef01cSRoman Divacky 4068f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_INVOKE: { 4069f22ef01cSRoman Divacky // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...] 4070f785676fSDimitry Andric if (Record.size() < 4) 40718f0fd8f6SDimitry Andric return error("Invalid record"); 4072ff0cc061SDimitry Andric unsigned OpNum = 0; 40737a7e6055SDimitry Andric AttributeList PAL = getAttributes(Record[OpNum++]); 4074ff0cc061SDimitry Andric unsigned CCInfo = Record[OpNum++]; 4075ff0cc061SDimitry Andric BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]); 4076ff0cc061SDimitry Andric BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]); 4077f22ef01cSRoman Divacky 4078ff0cc061SDimitry Andric FunctionType *FTy = nullptr; 4079ff0cc061SDimitry Andric if (CCInfo >> 13 & 1 && 4080ff0cc061SDimitry Andric !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++])))) 40818f0fd8f6SDimitry Andric return error("Explicit invoke type is not a function type"); 4082ff0cc061SDimitry Andric 4083f22ef01cSRoman Divacky Value *Callee; 4084f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, Callee)) 40858f0fd8f6SDimitry Andric return error("Invalid record"); 4086f22ef01cSRoman Divacky 40876122f3e6SDimitry Andric PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType()); 4088ff0cc061SDimitry Andric if (!CalleeTy) 40898f0fd8f6SDimitry Andric return error("Callee is not a pointer"); 4090ff0cc061SDimitry Andric if (!FTy) { 4091ff0cc061SDimitry Andric FTy = dyn_cast<FunctionType>(CalleeTy->getElementType()); 4092ff0cc061SDimitry Andric if (!FTy) 40938f0fd8f6SDimitry Andric return error("Callee is not of pointer to function type"); 4094ff0cc061SDimitry Andric } else if (CalleeTy->getElementType() != FTy) 40958f0fd8f6SDimitry Andric return error("Explicit invoke type does not match pointee type of " 4096ff0cc061SDimitry Andric "callee operand"); 4097ff0cc061SDimitry Andric if (Record.size() < FTy->getNumParams() + OpNum) 40988f0fd8f6SDimitry Andric return error("Insufficient operands to call"); 4099f22ef01cSRoman Divacky 4100f22ef01cSRoman Divacky SmallVector<Value*, 16> Ops; 4101f22ef01cSRoman Divacky for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) { 41023861d79fSDimitry Andric Ops.push_back(getValue(Record, OpNum, NextValueNo, 41033861d79fSDimitry Andric FTy->getParamType(i))); 410491bc56edSDimitry Andric if (!Ops.back()) 41058f0fd8f6SDimitry Andric return error("Invalid record"); 4106f22ef01cSRoman Divacky } 4107f22ef01cSRoman Divacky 4108f22ef01cSRoman Divacky if (!FTy->isVarArg()) { 4109f22ef01cSRoman Divacky if (Record.size() != OpNum) 41108f0fd8f6SDimitry Andric return error("Invalid record"); 4111f22ef01cSRoman Divacky } else { 4112f22ef01cSRoman Divacky // Read type/value pairs for varargs params. 4113f22ef01cSRoman Divacky while (OpNum != Record.size()) { 4114f22ef01cSRoman Divacky Value *Op; 4115f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 41168f0fd8f6SDimitry Andric return error("Invalid record"); 4117f22ef01cSRoman Divacky Ops.push_back(Op); 4118f22ef01cSRoman Divacky } 4119f22ef01cSRoman Divacky } 4120f22ef01cSRoman Divacky 41217d523365SDimitry Andric I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops, OperandBundles); 41227d523365SDimitry Andric OperandBundles.clear(); 4123f22ef01cSRoman Divacky InstructionList.push_back(I); 41247d523365SDimitry Andric cast<InvokeInst>(I)->setCallingConv( 41257d523365SDimitry Andric static_cast<CallingConv::ID>(CallingConv::MaxID & CCInfo)); 4126f22ef01cSRoman Divacky cast<InvokeInst>(I)->setAttributes(PAL); 4127f22ef01cSRoman Divacky break; 4128f22ef01cSRoman Divacky } 41296122f3e6SDimitry Andric case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval] 41306122f3e6SDimitry Andric unsigned Idx = 0; 413191bc56edSDimitry Andric Value *Val = nullptr; 41326122f3e6SDimitry Andric if (getValueTypePair(Record, Idx, NextValueNo, Val)) 41338f0fd8f6SDimitry Andric return error("Invalid record"); 41346122f3e6SDimitry Andric I = ResumeInst::Create(Val); 41356122f3e6SDimitry Andric InstructionList.push_back(I); 41366122f3e6SDimitry Andric break; 41376122f3e6SDimitry Andric } 4138f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE 4139f22ef01cSRoman Divacky I = new UnreachableInst(Context); 4140f22ef01cSRoman Divacky InstructionList.push_back(I); 4141f22ef01cSRoman Divacky break; 4142f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...] 4143f22ef01cSRoman Divacky if (Record.size() < 1 || ((Record.size()-1)&1)) 41448f0fd8f6SDimitry Andric return error("Invalid record"); 41456122f3e6SDimitry Andric Type *Ty = getTypeByID(Record[0]); 4146f785676fSDimitry Andric if (!Ty) 41478f0fd8f6SDimitry Andric return error("Invalid record"); 4148f22ef01cSRoman Divacky 41493b0f4066SDimitry Andric PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2); 4150f22ef01cSRoman Divacky InstructionList.push_back(PN); 4151f22ef01cSRoman Divacky 4152f22ef01cSRoman Divacky for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) { 41533861d79fSDimitry Andric Value *V; 41543861d79fSDimitry Andric // With the new function encoding, it is possible that operands have 41553861d79fSDimitry Andric // negative IDs (for forward references). Use a signed VBR 41563861d79fSDimitry Andric // representation to keep the encoding small. 41573861d79fSDimitry Andric if (UseRelativeIDs) 41583861d79fSDimitry Andric V = getValueSigned(Record, 1+i, NextValueNo, Ty); 41593861d79fSDimitry Andric else 41603861d79fSDimitry Andric V = getValue(Record, 1+i, NextValueNo, Ty); 4161f22ef01cSRoman Divacky BasicBlock *BB = getBasicBlock(Record[2+i]); 4162f785676fSDimitry Andric if (!V || !BB) 41638f0fd8f6SDimitry Andric return error("Invalid record"); 4164f22ef01cSRoman Divacky PN->addIncoming(V, BB); 4165f22ef01cSRoman Divacky } 4166f22ef01cSRoman Divacky I = PN; 4167f22ef01cSRoman Divacky break; 4168f22ef01cSRoman Divacky } 4169f22ef01cSRoman Divacky 41708f0fd8f6SDimitry Andric case bitc::FUNC_CODE_INST_LANDINGPAD: 41718f0fd8f6SDimitry Andric case bitc::FUNC_CODE_INST_LANDINGPAD_OLD: { 41726122f3e6SDimitry Andric // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?] 41736122f3e6SDimitry Andric unsigned Idx = 0; 41748f0fd8f6SDimitry Andric if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD) { 41758f0fd8f6SDimitry Andric if (Record.size() < 3) 41768f0fd8f6SDimitry Andric return error("Invalid record"); 41778f0fd8f6SDimitry Andric } else { 41788f0fd8f6SDimitry Andric assert(BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD); 41796122f3e6SDimitry Andric if (Record.size() < 4) 41808f0fd8f6SDimitry Andric return error("Invalid record"); 41818f0fd8f6SDimitry Andric } 41826122f3e6SDimitry Andric Type *Ty = getTypeByID(Record[Idx++]); 4183f785676fSDimitry Andric if (!Ty) 41848f0fd8f6SDimitry Andric return error("Invalid record"); 41858f0fd8f6SDimitry Andric if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD) { 418691bc56edSDimitry Andric Value *PersFn = nullptr; 41876122f3e6SDimitry Andric if (getValueTypePair(Record, Idx, NextValueNo, PersFn)) 41888f0fd8f6SDimitry Andric return error("Invalid record"); 41898f0fd8f6SDimitry Andric 41908f0fd8f6SDimitry Andric if (!F->hasPersonalityFn()) 41918f0fd8f6SDimitry Andric F->setPersonalityFn(cast<Constant>(PersFn)); 41928f0fd8f6SDimitry Andric else if (F->getPersonalityFn() != cast<Constant>(PersFn)) 41938f0fd8f6SDimitry Andric return error("Personality function mismatch"); 41948f0fd8f6SDimitry Andric } 41956122f3e6SDimitry Andric 41966122f3e6SDimitry Andric bool IsCleanup = !!Record[Idx++]; 41976122f3e6SDimitry Andric unsigned NumClauses = Record[Idx++]; 41988f0fd8f6SDimitry Andric LandingPadInst *LP = LandingPadInst::Create(Ty, NumClauses); 41996122f3e6SDimitry Andric LP->setCleanup(IsCleanup); 42006122f3e6SDimitry Andric for (unsigned J = 0; J != NumClauses; ++J) { 42016122f3e6SDimitry Andric LandingPadInst::ClauseType CT = 42026122f3e6SDimitry Andric LandingPadInst::ClauseType(Record[Idx++]); (void)CT; 42036122f3e6SDimitry Andric Value *Val; 42046122f3e6SDimitry Andric 42056122f3e6SDimitry Andric if (getValueTypePair(Record, Idx, NextValueNo, Val)) { 42066122f3e6SDimitry Andric delete LP; 42078f0fd8f6SDimitry Andric return error("Invalid record"); 42086122f3e6SDimitry Andric } 42096122f3e6SDimitry Andric 42106122f3e6SDimitry Andric assert((CT != LandingPadInst::Catch || 42116122f3e6SDimitry Andric !isa<ArrayType>(Val->getType())) && 42126122f3e6SDimitry Andric "Catch clause has a invalid type!"); 42136122f3e6SDimitry Andric assert((CT != LandingPadInst::Filter || 42146122f3e6SDimitry Andric isa<ArrayType>(Val->getType())) && 42156122f3e6SDimitry Andric "Filter clause has invalid type!"); 421691bc56edSDimitry Andric LP->addClause(cast<Constant>(Val)); 42176122f3e6SDimitry Andric } 42186122f3e6SDimitry Andric 42196122f3e6SDimitry Andric I = LP; 42206122f3e6SDimitry Andric InstructionList.push_back(I); 42216122f3e6SDimitry Andric break; 42226122f3e6SDimitry Andric } 42236122f3e6SDimitry Andric 422417a519f9SDimitry Andric case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align] 422517a519f9SDimitry Andric if (Record.size() != 4) 42268f0fd8f6SDimitry Andric return error("Invalid record"); 4227ff0cc061SDimitry Andric uint64_t AlignRecord = Record[3]; 4228ff0cc061SDimitry Andric const uint64_t InAllocaMask = uint64_t(1) << 5; 4229ff0cc061SDimitry Andric const uint64_t ExplicitTypeMask = uint64_t(1) << 6; 42303ca95b02SDimitry Andric const uint64_t SwiftErrorMask = uint64_t(1) << 7; 42313ca95b02SDimitry Andric const uint64_t FlagMask = InAllocaMask | ExplicitTypeMask | 42323ca95b02SDimitry Andric SwiftErrorMask; 4233ff0cc061SDimitry Andric bool InAlloca = AlignRecord & InAllocaMask; 42343ca95b02SDimitry Andric bool SwiftError = AlignRecord & SwiftErrorMask; 4235ff0cc061SDimitry Andric Type *Ty = getTypeByID(Record[0]); 4236ff0cc061SDimitry Andric if ((AlignRecord & ExplicitTypeMask) == 0) { 4237ff0cc061SDimitry Andric auto *PTy = dyn_cast_or_null<PointerType>(Ty); 4238ff0cc061SDimitry Andric if (!PTy) 42398f0fd8f6SDimitry Andric return error("Old-style alloca with a non-pointer type"); 4240ff0cc061SDimitry Andric Ty = PTy->getElementType(); 4241ff0cc061SDimitry Andric } 42426122f3e6SDimitry Andric Type *OpTy = getTypeByID(Record[1]); 424317a519f9SDimitry Andric Value *Size = getFnValueByID(Record[2], OpTy); 4244ff0cc061SDimitry Andric unsigned Align; 4245d88c1a5aSDimitry Andric if (Error Err = parseAlignmentValue(AlignRecord & ~FlagMask, Align)) { 4246d88c1a5aSDimitry Andric return Err; 4247ff0cc061SDimitry Andric } 4248f785676fSDimitry Andric if (!Ty || !Size) 42498f0fd8f6SDimitry Andric return error("Invalid record"); 42507a7e6055SDimitry Andric 42517a7e6055SDimitry Andric // FIXME: Make this an optional field. 42527a7e6055SDimitry Andric const DataLayout &DL = TheModule->getDataLayout(); 42537a7e6055SDimitry Andric unsigned AS = DL.getAllocaAddrSpace(); 42547a7e6055SDimitry Andric 42557a7e6055SDimitry Andric AllocaInst *AI = new AllocaInst(Ty, AS, Size, Align); 425691bc56edSDimitry Andric AI->setUsedWithInAlloca(InAlloca); 42573ca95b02SDimitry Andric AI->setSwiftError(SwiftError); 425891bc56edSDimitry Andric I = AI; 4259f22ef01cSRoman Divacky InstructionList.push_back(I); 4260f22ef01cSRoman Divacky break; 4261f22ef01cSRoman Divacky } 4262f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol] 4263f22ef01cSRoman Divacky unsigned OpNum = 0; 4264f22ef01cSRoman Divacky Value *Op; 4265f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, Op) || 4266ff0cc061SDimitry Andric (OpNum + 2 != Record.size() && OpNum + 3 != Record.size())) 42678f0fd8f6SDimitry Andric return error("Invalid record"); 4268f22ef01cSRoman Divacky 4269ff0cc061SDimitry Andric Type *Ty = nullptr; 4270ff0cc061SDimitry Andric if (OpNum + 3 == Record.size()) 4271ff0cc061SDimitry Andric Ty = getTypeByID(Record[OpNum++]); 4272d88c1a5aSDimitry Andric if (Error Err = typeCheckLoadStoreInst(Ty, Op->getType())) 4273d88c1a5aSDimitry Andric return Err; 4274ff0cc061SDimitry Andric if (!Ty) 4275ff0cc061SDimitry Andric Ty = cast<PointerType>(Op->getType())->getElementType(); 4276ff0cc061SDimitry Andric 4277ff0cc061SDimitry Andric unsigned Align; 4278d88c1a5aSDimitry Andric if (Error Err = parseAlignmentValue(Record[OpNum], Align)) 4279d88c1a5aSDimitry Andric return Err; 4280ff0cc061SDimitry Andric I = new LoadInst(Ty, Op, "", Record[OpNum + 1], Align); 4281ff0cc061SDimitry Andric 4282f22ef01cSRoman Divacky InstructionList.push_back(I); 4283f22ef01cSRoman Divacky break; 4284f22ef01cSRoman Divacky } 42856122f3e6SDimitry Andric case bitc::FUNC_CODE_INST_LOADATOMIC: { 4286c4394386SDimitry Andric // LOADATOMIC: [opty, op, align, vol, ordering, ssid] 42876122f3e6SDimitry Andric unsigned OpNum = 0; 42886122f3e6SDimitry Andric Value *Op; 42896122f3e6SDimitry Andric if (getValueTypePair(Record, OpNum, NextValueNo, Op) || 4290ff0cc061SDimitry Andric (OpNum + 4 != Record.size() && OpNum + 5 != Record.size())) 42918f0fd8f6SDimitry Andric return error("Invalid record"); 42926122f3e6SDimitry Andric 4293ff0cc061SDimitry Andric Type *Ty = nullptr; 4294ff0cc061SDimitry Andric if (OpNum + 5 == Record.size()) 4295ff0cc061SDimitry Andric Ty = getTypeByID(Record[OpNum++]); 4296d88c1a5aSDimitry Andric if (Error Err = typeCheckLoadStoreInst(Ty, Op->getType())) 4297d88c1a5aSDimitry Andric return Err; 4298ff0cc061SDimitry Andric if (!Ty) 4299ff0cc061SDimitry Andric Ty = cast<PointerType>(Op->getType())->getElementType(); 4300ff0cc061SDimitry Andric 43018f0fd8f6SDimitry Andric AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]); 43023ca95b02SDimitry Andric if (Ordering == AtomicOrdering::NotAtomic || 43033ca95b02SDimitry Andric Ordering == AtomicOrdering::Release || 43043ca95b02SDimitry Andric Ordering == AtomicOrdering::AcquireRelease) 43058f0fd8f6SDimitry Andric return error("Invalid record"); 43063ca95b02SDimitry Andric if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0) 43078f0fd8f6SDimitry Andric return error("Invalid record"); 4308c4394386SDimitry Andric SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]); 43096122f3e6SDimitry Andric 4310ff0cc061SDimitry Andric unsigned Align; 4311d88c1a5aSDimitry Andric if (Error Err = parseAlignmentValue(Record[OpNum], Align)) 4312d88c1a5aSDimitry Andric return Err; 4313c4394386SDimitry Andric I = new LoadInst(Op, "", Record[OpNum+1], Align, Ordering, SSID); 4314ff0cc061SDimitry Andric 43156122f3e6SDimitry Andric InstructionList.push_back(I); 43166122f3e6SDimitry Andric break; 43176122f3e6SDimitry Andric } 4318ff0cc061SDimitry Andric case bitc::FUNC_CODE_INST_STORE: 4319ff0cc061SDimitry Andric case bitc::FUNC_CODE_INST_STORE_OLD: { // STORE2:[ptrty, ptr, val, align, vol] 4320f22ef01cSRoman Divacky unsigned OpNum = 0; 4321f22ef01cSRoman Divacky Value *Val, *Ptr; 4322f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) || 4323ff0cc061SDimitry Andric (BitCode == bitc::FUNC_CODE_INST_STORE 4324ff0cc061SDimitry Andric ? getValueTypePair(Record, OpNum, NextValueNo, Val) 4325ff0cc061SDimitry Andric : popValue(Record, OpNum, NextValueNo, 4326ff0cc061SDimitry Andric cast<PointerType>(Ptr->getType())->getElementType(), 4327ff0cc061SDimitry Andric Val)) || 4328f22ef01cSRoman Divacky OpNum + 2 != Record.size()) 43298f0fd8f6SDimitry Andric return error("Invalid record"); 4330f22ef01cSRoman Divacky 4331d88c1a5aSDimitry Andric if (Error Err = typeCheckLoadStoreInst(Val->getType(), Ptr->getType())) 4332d88c1a5aSDimitry Andric return Err; 4333ff0cc061SDimitry Andric unsigned Align; 4334d88c1a5aSDimitry Andric if (Error Err = parseAlignmentValue(Record[OpNum], Align)) 4335d88c1a5aSDimitry Andric return Err; 4336ff0cc061SDimitry Andric I = new StoreInst(Val, Ptr, Record[OpNum+1], Align); 4337f22ef01cSRoman Divacky InstructionList.push_back(I); 4338f22ef01cSRoman Divacky break; 4339f22ef01cSRoman Divacky } 4340ff0cc061SDimitry Andric case bitc::FUNC_CODE_INST_STOREATOMIC: 4341ff0cc061SDimitry Andric case bitc::FUNC_CODE_INST_STOREATOMIC_OLD: { 4342c4394386SDimitry Andric // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, ssid] 43436122f3e6SDimitry Andric unsigned OpNum = 0; 43446122f3e6SDimitry Andric Value *Val, *Ptr; 43456122f3e6SDimitry Andric if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) || 43463ca95b02SDimitry Andric !isa<PointerType>(Ptr->getType()) || 4347ff0cc061SDimitry Andric (BitCode == bitc::FUNC_CODE_INST_STOREATOMIC 4348ff0cc061SDimitry Andric ? getValueTypePair(Record, OpNum, NextValueNo, Val) 4349ff0cc061SDimitry Andric : popValue(Record, OpNum, NextValueNo, 4350ff0cc061SDimitry Andric cast<PointerType>(Ptr->getType())->getElementType(), 4351ff0cc061SDimitry Andric Val)) || 43526122f3e6SDimitry Andric OpNum + 4 != Record.size()) 43538f0fd8f6SDimitry Andric return error("Invalid record"); 43546122f3e6SDimitry Andric 4355d88c1a5aSDimitry Andric if (Error Err = typeCheckLoadStoreInst(Val->getType(), Ptr->getType())) 4356d88c1a5aSDimitry Andric return Err; 43578f0fd8f6SDimitry Andric AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]); 43583ca95b02SDimitry Andric if (Ordering == AtomicOrdering::NotAtomic || 43593ca95b02SDimitry Andric Ordering == AtomicOrdering::Acquire || 43603ca95b02SDimitry Andric Ordering == AtomicOrdering::AcquireRelease) 43618f0fd8f6SDimitry Andric return error("Invalid record"); 4362c4394386SDimitry Andric SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]); 43633ca95b02SDimitry Andric if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0) 43648f0fd8f6SDimitry Andric return error("Invalid record"); 43656122f3e6SDimitry Andric 4366ff0cc061SDimitry Andric unsigned Align; 4367d88c1a5aSDimitry Andric if (Error Err = parseAlignmentValue(Record[OpNum], Align)) 4368d88c1a5aSDimitry Andric return Err; 4369c4394386SDimitry Andric I = new StoreInst(Val, Ptr, Record[OpNum+1], Align, Ordering, SSID); 43706122f3e6SDimitry Andric InstructionList.push_back(I); 43716122f3e6SDimitry Andric break; 43726122f3e6SDimitry Andric } 4373ff0cc061SDimitry Andric case bitc::FUNC_CODE_INST_CMPXCHG_OLD: 43746122f3e6SDimitry Andric case bitc::FUNC_CODE_INST_CMPXCHG: { 4375c4394386SDimitry Andric // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, ssid, 437691bc56edSDimitry Andric // failureordering?, isweak?] 43776122f3e6SDimitry Andric unsigned OpNum = 0; 43786122f3e6SDimitry Andric Value *Ptr, *Cmp, *New; 43796122f3e6SDimitry Andric if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) || 4380ff0cc061SDimitry Andric (BitCode == bitc::FUNC_CODE_INST_CMPXCHG 4381ff0cc061SDimitry Andric ? getValueTypePair(Record, OpNum, NextValueNo, Cmp) 4382ff0cc061SDimitry Andric : popValue(Record, OpNum, NextValueNo, 4383ff0cc061SDimitry Andric cast<PointerType>(Ptr->getType())->getElementType(), 4384ff0cc061SDimitry Andric Cmp)) || 4385ff0cc061SDimitry Andric popValue(Record, OpNum, NextValueNo, Cmp->getType(), New) || 4386ff0cc061SDimitry Andric Record.size() < OpNum + 3 || Record.size() > OpNum + 5) 43878f0fd8f6SDimitry Andric return error("Invalid record"); 43888f0fd8f6SDimitry Andric AtomicOrdering SuccessOrdering = getDecodedOrdering(Record[OpNum + 1]); 43893ca95b02SDimitry Andric if (SuccessOrdering == AtomicOrdering::NotAtomic || 43903ca95b02SDimitry Andric SuccessOrdering == AtomicOrdering::Unordered) 43918f0fd8f6SDimitry Andric return error("Invalid record"); 4392c4394386SDimitry Andric SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 2]); 439391bc56edSDimitry Andric 4394d88c1a5aSDimitry Andric if (Error Err = typeCheckLoadStoreInst(Cmp->getType(), Ptr->getType())) 4395d88c1a5aSDimitry Andric return Err; 439691bc56edSDimitry Andric AtomicOrdering FailureOrdering; 439791bc56edSDimitry Andric if (Record.size() < 7) 439891bc56edSDimitry Andric FailureOrdering = 439991bc56edSDimitry Andric AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering); 440091bc56edSDimitry Andric else 44018f0fd8f6SDimitry Andric FailureOrdering = getDecodedOrdering(Record[OpNum + 3]); 440291bc56edSDimitry Andric 440391bc56edSDimitry Andric I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering, 4404c4394386SDimitry Andric SSID); 44056122f3e6SDimitry Andric cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]); 440691bc56edSDimitry Andric 440791bc56edSDimitry Andric if (Record.size() < 8) { 440891bc56edSDimitry Andric // Before weak cmpxchgs existed, the instruction simply returned the 440991bc56edSDimitry Andric // value loaded from memory, so bitcode files from that era will be 441091bc56edSDimitry Andric // expecting the first component of a modern cmpxchg. 441191bc56edSDimitry Andric CurBB->getInstList().push_back(I); 441291bc56edSDimitry Andric I = ExtractValueInst::Create(I, 0); 441391bc56edSDimitry Andric } else { 441491bc56edSDimitry Andric cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]); 441591bc56edSDimitry Andric } 441691bc56edSDimitry Andric 44176122f3e6SDimitry Andric InstructionList.push_back(I); 44186122f3e6SDimitry Andric break; 44196122f3e6SDimitry Andric } 44206122f3e6SDimitry Andric case bitc::FUNC_CODE_INST_ATOMICRMW: { 4421c4394386SDimitry Andric // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, ssid] 44226122f3e6SDimitry Andric unsigned OpNum = 0; 44236122f3e6SDimitry Andric Value *Ptr, *Val; 44246122f3e6SDimitry Andric if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) || 44253ca95b02SDimitry Andric !isa<PointerType>(Ptr->getType()) || 44263861d79fSDimitry Andric popValue(Record, OpNum, NextValueNo, 44276122f3e6SDimitry Andric cast<PointerType>(Ptr->getType())->getElementType(), Val) || 44286122f3e6SDimitry Andric OpNum+4 != Record.size()) 44298f0fd8f6SDimitry Andric return error("Invalid record"); 44308f0fd8f6SDimitry Andric AtomicRMWInst::BinOp Operation = getDecodedRMWOperation(Record[OpNum]); 44316122f3e6SDimitry Andric if (Operation < AtomicRMWInst::FIRST_BINOP || 44326122f3e6SDimitry Andric Operation > AtomicRMWInst::LAST_BINOP) 44338f0fd8f6SDimitry Andric return error("Invalid record"); 44348f0fd8f6SDimitry Andric AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]); 44353ca95b02SDimitry Andric if (Ordering == AtomicOrdering::NotAtomic || 44363ca95b02SDimitry Andric Ordering == AtomicOrdering::Unordered) 44378f0fd8f6SDimitry Andric return error("Invalid record"); 4438c4394386SDimitry Andric SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]); 4439c4394386SDimitry Andric I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SSID); 44406122f3e6SDimitry Andric cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]); 44416122f3e6SDimitry Andric InstructionList.push_back(I); 44426122f3e6SDimitry Andric break; 44436122f3e6SDimitry Andric } 4444c4394386SDimitry Andric case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, ssid] 44456122f3e6SDimitry Andric if (2 != Record.size()) 44468f0fd8f6SDimitry Andric return error("Invalid record"); 44478f0fd8f6SDimitry Andric AtomicOrdering Ordering = getDecodedOrdering(Record[0]); 44483ca95b02SDimitry Andric if (Ordering == AtomicOrdering::NotAtomic || 44493ca95b02SDimitry Andric Ordering == AtomicOrdering::Unordered || 44503ca95b02SDimitry Andric Ordering == AtomicOrdering::Monotonic) 44518f0fd8f6SDimitry Andric return error("Invalid record"); 4452c4394386SDimitry Andric SyncScope::ID SSID = getDecodedSyncScopeID(Record[1]); 4453c4394386SDimitry Andric I = new FenceInst(Context, Ordering, SSID); 44546122f3e6SDimitry Andric InstructionList.push_back(I); 44556122f3e6SDimitry Andric break; 44566122f3e6SDimitry Andric } 445717a519f9SDimitry Andric case bitc::FUNC_CODE_INST_CALL: { 44587d523365SDimitry Andric // CALL: [paramattrs, cc, fmf, fnty, fnid, arg0, arg1...] 4459f22ef01cSRoman Divacky if (Record.size() < 3) 44608f0fd8f6SDimitry Andric return error("Invalid record"); 4461f22ef01cSRoman Divacky 4462ff0cc061SDimitry Andric unsigned OpNum = 0; 44637a7e6055SDimitry Andric AttributeList PAL = getAttributes(Record[OpNum++]); 4464ff0cc061SDimitry Andric unsigned CCInfo = Record[OpNum++]; 4465f22ef01cSRoman Divacky 44667d523365SDimitry Andric FastMathFlags FMF; 44677d523365SDimitry Andric if ((CCInfo >> bitc::CALL_FMF) & 1) { 44687d523365SDimitry Andric FMF = getDecodedFastMathFlags(Record[OpNum++]); 44697d523365SDimitry Andric if (!FMF.any()) 44707d523365SDimitry Andric return error("Fast math flags indicator set for call with no FMF"); 44717d523365SDimitry Andric } 44727d523365SDimitry Andric 4473ff0cc061SDimitry Andric FunctionType *FTy = nullptr; 44747d523365SDimitry Andric if (CCInfo >> bitc::CALL_EXPLICIT_TYPE & 1 && 4475ff0cc061SDimitry Andric !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++])))) 44768f0fd8f6SDimitry Andric return error("Explicit call type is not a function type"); 4477ff0cc061SDimitry Andric 4478f22ef01cSRoman Divacky Value *Callee; 4479f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, Callee)) 44808f0fd8f6SDimitry Andric return error("Invalid record"); 4481f22ef01cSRoman Divacky 44826122f3e6SDimitry Andric PointerType *OpTy = dyn_cast<PointerType>(Callee->getType()); 4483ff0cc061SDimitry Andric if (!OpTy) 44848f0fd8f6SDimitry Andric return error("Callee is not a pointer type"); 4485ff0cc061SDimitry Andric if (!FTy) { 4486ff0cc061SDimitry Andric FTy = dyn_cast<FunctionType>(OpTy->getElementType()); 4487ff0cc061SDimitry Andric if (!FTy) 44888f0fd8f6SDimitry Andric return error("Callee is not of pointer to function type"); 4489ff0cc061SDimitry Andric } else if (OpTy->getElementType() != FTy) 44908f0fd8f6SDimitry Andric return error("Explicit call type does not match pointee type of " 4491ff0cc061SDimitry Andric "callee operand"); 4492ff0cc061SDimitry Andric if (Record.size() < FTy->getNumParams() + OpNum) 44938f0fd8f6SDimitry Andric return error("Insufficient operands to call"); 4494f22ef01cSRoman Divacky 4495f22ef01cSRoman Divacky SmallVector<Value*, 16> Args; 4496f22ef01cSRoman Divacky // Read the fixed params. 4497f22ef01cSRoman Divacky for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) { 449817a519f9SDimitry Andric if (FTy->getParamType(i)->isLabelTy()) 4499f22ef01cSRoman Divacky Args.push_back(getBasicBlock(Record[OpNum])); 4500f22ef01cSRoman Divacky else 45013861d79fSDimitry Andric Args.push_back(getValue(Record, OpNum, NextValueNo, 45023861d79fSDimitry Andric FTy->getParamType(i))); 450391bc56edSDimitry Andric if (!Args.back()) 45048f0fd8f6SDimitry Andric return error("Invalid record"); 4505f22ef01cSRoman Divacky } 4506f22ef01cSRoman Divacky 4507f22ef01cSRoman Divacky // Read type/value pairs for varargs params. 4508f22ef01cSRoman Divacky if (!FTy->isVarArg()) { 4509f22ef01cSRoman Divacky if (OpNum != Record.size()) 45108f0fd8f6SDimitry Andric return error("Invalid record"); 4511f22ef01cSRoman Divacky } else { 4512f22ef01cSRoman Divacky while (OpNum != Record.size()) { 4513f22ef01cSRoman Divacky Value *Op; 4514f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 45158f0fd8f6SDimitry Andric return error("Invalid record"); 4516f22ef01cSRoman Divacky Args.push_back(Op); 4517f22ef01cSRoman Divacky } 4518f22ef01cSRoman Divacky } 4519f22ef01cSRoman Divacky 45207d523365SDimitry Andric I = CallInst::Create(FTy, Callee, Args, OperandBundles); 45217d523365SDimitry Andric OperandBundles.clear(); 4522f22ef01cSRoman Divacky InstructionList.push_back(I); 4523f22ef01cSRoman Divacky cast<CallInst>(I)->setCallingConv( 45247d523365SDimitry Andric static_cast<CallingConv::ID>((0x7ff & CCInfo) >> bitc::CALL_CCONV)); 452591bc56edSDimitry Andric CallInst::TailCallKind TCK = CallInst::TCK_None; 45267d523365SDimitry Andric if (CCInfo & 1 << bitc::CALL_TAIL) 452791bc56edSDimitry Andric TCK = CallInst::TCK_Tail; 45287d523365SDimitry Andric if (CCInfo & (1 << bitc::CALL_MUSTTAIL)) 452991bc56edSDimitry Andric TCK = CallInst::TCK_MustTail; 45307d523365SDimitry Andric if (CCInfo & (1 << bitc::CALL_NOTAIL)) 45317d523365SDimitry Andric TCK = CallInst::TCK_NoTail; 453291bc56edSDimitry Andric cast<CallInst>(I)->setTailCallKind(TCK); 4533f22ef01cSRoman Divacky cast<CallInst>(I)->setAttributes(PAL); 45347d523365SDimitry Andric if (FMF.any()) { 45357d523365SDimitry Andric if (!isa<FPMathOperator>(I)) 45367d523365SDimitry Andric return error("Fast-math-flags specified for call without " 45377d523365SDimitry Andric "floating-point scalar or vector return type"); 45387d523365SDimitry Andric I->setFastMathFlags(FMF); 45397d523365SDimitry Andric } 4540f22ef01cSRoman Divacky break; 4541f22ef01cSRoman Divacky } 4542f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty] 4543f22ef01cSRoman Divacky if (Record.size() < 3) 45448f0fd8f6SDimitry Andric return error("Invalid record"); 45456122f3e6SDimitry Andric Type *OpTy = getTypeByID(Record[0]); 45463861d79fSDimitry Andric Value *Op = getValue(Record, 1, NextValueNo, OpTy); 45476122f3e6SDimitry Andric Type *ResTy = getTypeByID(Record[2]); 4548f22ef01cSRoman Divacky if (!OpTy || !Op || !ResTy) 45498f0fd8f6SDimitry Andric return error("Invalid record"); 4550f22ef01cSRoman Divacky I = new VAArgInst(Op, ResTy); 4551f22ef01cSRoman Divacky InstructionList.push_back(I); 4552f22ef01cSRoman Divacky break; 4553f22ef01cSRoman Divacky } 45547d523365SDimitry Andric 45557d523365SDimitry Andric case bitc::FUNC_CODE_OPERAND_BUNDLE: { 45567d523365SDimitry Andric // A call or an invoke can be optionally prefixed with some variable 45577d523365SDimitry Andric // number of operand bundle blocks. These blocks are read into 45587d523365SDimitry Andric // OperandBundles and consumed at the next call or invoke instruction. 45597d523365SDimitry Andric 45607d523365SDimitry Andric if (Record.size() < 1 || Record[0] >= BundleTags.size()) 45617d523365SDimitry Andric return error("Invalid record"); 45627d523365SDimitry Andric 45637d523365SDimitry Andric std::vector<Value *> Inputs; 45647d523365SDimitry Andric 45657d523365SDimitry Andric unsigned OpNum = 1; 45667d523365SDimitry Andric while (OpNum != Record.size()) { 45677d523365SDimitry Andric Value *Op; 45687d523365SDimitry Andric if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 45697d523365SDimitry Andric return error("Invalid record"); 45707d523365SDimitry Andric Inputs.push_back(Op); 45717d523365SDimitry Andric } 45727d523365SDimitry Andric 45737d523365SDimitry Andric OperandBundles.emplace_back(BundleTags[Record[0]], std::move(Inputs)); 45747d523365SDimitry Andric continue; 45757d523365SDimitry Andric } 4576f22ef01cSRoman Divacky } 4577f22ef01cSRoman Divacky 4578f22ef01cSRoman Divacky // Add instruction to end of current BB. If there is no current BB, reject 4579f22ef01cSRoman Divacky // this file. 458091bc56edSDimitry Andric if (!CurBB) { 4581d8866befSDimitry Andric I->deleteValue(); 45828f0fd8f6SDimitry Andric return error("Invalid instruction with no BB"); 4583f22ef01cSRoman Divacky } 45847d523365SDimitry Andric if (!OperandBundles.empty()) { 4585d8866befSDimitry Andric I->deleteValue(); 45867d523365SDimitry Andric return error("Operand bundles found with no consumer"); 45877d523365SDimitry Andric } 4588f22ef01cSRoman Divacky CurBB->getInstList().push_back(I); 4589f22ef01cSRoman Divacky 4590f22ef01cSRoman Divacky // If this was a terminator instruction, move to the next block. 4591f22ef01cSRoman Divacky if (isa<TerminatorInst>(I)) { 4592f22ef01cSRoman Divacky ++CurBBNo; 459391bc56edSDimitry Andric CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr; 4594f22ef01cSRoman Divacky } 4595f22ef01cSRoman Divacky 4596f22ef01cSRoman Divacky // Non-void values get registered in the value table for future use. 4597f22ef01cSRoman Divacky if (I && !I->getType()->isVoidTy()) 45988f0fd8f6SDimitry Andric ValueList.assignValue(I, NextValueNo++); 4599f22ef01cSRoman Divacky } 4600f22ef01cSRoman Divacky 4601139f7f9bSDimitry Andric OutOfRecordLoop: 4602139f7f9bSDimitry Andric 46037d523365SDimitry Andric if (!OperandBundles.empty()) 46047d523365SDimitry Andric return error("Operand bundles found with no consumer"); 46057d523365SDimitry Andric 4606f22ef01cSRoman Divacky // Check the function list for unresolved values. 4607f22ef01cSRoman Divacky if (Argument *A = dyn_cast<Argument>(ValueList.back())) { 460891bc56edSDimitry Andric if (!A->getParent()) { 4609f22ef01cSRoman Divacky // We found at least one unresolved value. Nuke them all to avoid leaks. 4610f22ef01cSRoman Divacky for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){ 461191bc56edSDimitry Andric if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) { 4612f22ef01cSRoman Divacky A->replaceAllUsesWith(UndefValue::get(A->getType())); 4613f22ef01cSRoman Divacky delete A; 4614f22ef01cSRoman Divacky } 4615f22ef01cSRoman Divacky } 46168f0fd8f6SDimitry Andric return error("Never resolved value found in function"); 4617f22ef01cSRoman Divacky } 4618f22ef01cSRoman Divacky } 4619f22ef01cSRoman Divacky 46203ca95b02SDimitry Andric // Unexpected unresolved metadata about to be dropped. 4621d88c1a5aSDimitry Andric if (MDLoader->hasFwdRefs()) 46223ca95b02SDimitry Andric return error("Invalid function metadata: outgoing forward refs"); 4623e580952dSDimitry Andric 4624f22ef01cSRoman Divacky // Trim the value list down to the size it was before we parsed this function. 4625f22ef01cSRoman Divacky ValueList.shrinkTo(ModuleValueListSize); 4626d88c1a5aSDimitry Andric MDLoader->shrinkTo(ModuleMDLoaderSize); 4627f22ef01cSRoman Divacky std::vector<BasicBlock*>().swap(FunctionBBs); 4628d88c1a5aSDimitry Andric return Error::success(); 4629f22ef01cSRoman Divacky } 4630f22ef01cSRoman Divacky 4631f785676fSDimitry Andric /// Find the function body in the bitcode stream 4632d88c1a5aSDimitry Andric Error BitcodeReader::findFunctionInStream( 463391bc56edSDimitry Andric Function *F, 4634dff0c46cSDimitry Andric DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) { 4635dff0c46cSDimitry Andric while (DeferredFunctionInfoIterator->second == 0) { 46367d523365SDimitry Andric // This is the fallback handling for the old format bitcode that 46377d523365SDimitry Andric // didn't contain the function index in the VST, or when we have 46387d523365SDimitry Andric // an anonymous function which would not have a VST entry. 46397d523365SDimitry Andric // Assert that we have one of those two cases. 46407d523365SDimitry Andric assert(VSTOffset == 0 || !F->hasName()); 46417d523365SDimitry Andric // Parse the next body in the stream and set its position in the 46427d523365SDimitry Andric // DeferredFunctionInfo map. 4643d88c1a5aSDimitry Andric if (Error Err = rememberAndSkipFunctionBodies()) 4644d88c1a5aSDimitry Andric return Err; 4645dff0c46cSDimitry Andric } 4646d88c1a5aSDimitry Andric return Error::success(); 4647dff0c46cSDimitry Andric } 4648dff0c46cSDimitry Andric 4649c4394386SDimitry Andric SyncScope::ID BitcodeReader::getDecodedSyncScopeID(unsigned Val) { 4650c4394386SDimitry Andric if (Val == SyncScope::SingleThread || Val == SyncScope::System) 4651c4394386SDimitry Andric return SyncScope::ID(Val); 4652c4394386SDimitry Andric if (Val >= SSIDs.size()) 4653c4394386SDimitry Andric return SyncScope::System; // Map unknown synchronization scopes to system. 4654c4394386SDimitry Andric return SSIDs[Val]; 4655c4394386SDimitry Andric } 4656c4394386SDimitry Andric 4657f22ef01cSRoman Divacky //===----------------------------------------------------------------------===// 4658f22ef01cSRoman Divacky // GVMaterializer implementation 4659f22ef01cSRoman Divacky //===----------------------------------------------------------------------===// 4660f22ef01cSRoman Divacky 4661d88c1a5aSDimitry Andric Error BitcodeReader::materialize(GlobalValue *GV) { 4662f22ef01cSRoman Divacky Function *F = dyn_cast<Function>(GV); 4663f22ef01cSRoman Divacky // If it's not a function or is already material, ignore the request. 4664f785676fSDimitry Andric if (!F || !F->isMaterializable()) 4665d88c1a5aSDimitry Andric return Error::success(); 4666f22ef01cSRoman Divacky 4667f22ef01cSRoman Divacky DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F); 4668f22ef01cSRoman Divacky assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!"); 4669dff0c46cSDimitry Andric // If its position is recorded as 0, its body is somewhere in the stream 4670dff0c46cSDimitry Andric // but we haven't seen it yet. 46713dac3a9bSDimitry Andric if (DFII->second == 0) 4672d88c1a5aSDimitry Andric if (Error Err = findFunctionInStream(F, DFII)) 4673d88c1a5aSDimitry Andric return Err; 4674f22ef01cSRoman Divacky 46753ca95b02SDimitry Andric // Materialize metadata before parsing any function bodies. 4676d88c1a5aSDimitry Andric if (Error Err = materializeMetadata()) 4677d88c1a5aSDimitry Andric return Err; 46783ca95b02SDimitry Andric 4679f22ef01cSRoman Divacky // Move the bit stream to the saved position of the deferred function body. 4680f22ef01cSRoman Divacky Stream.JumpToBit(DFII->second); 4681f22ef01cSRoman Divacky 4682d88c1a5aSDimitry Andric if (Error Err = parseFunctionBody(F)) 4683d88c1a5aSDimitry Andric return Err; 468439d628a0SDimitry Andric F->setIsMaterializable(false); 4685f22ef01cSRoman Divacky 4686ff0cc061SDimitry Andric if (StripDebugInfo) 4687ff0cc061SDimitry Andric stripDebugInfo(*F); 4688ff0cc061SDimitry Andric 4689f22ef01cSRoman Divacky // Upgrade any old intrinsic calls in the function. 46903dac3a9bSDimitry Andric for (auto &I : UpgradedIntrinsics) { 46917d523365SDimitry Andric for (auto UI = I.first->materialized_user_begin(), UE = I.first->user_end(); 46927d523365SDimitry Andric UI != UE;) { 46933dac3a9bSDimitry Andric User *U = *UI; 46943dac3a9bSDimitry Andric ++UI; 46953dac3a9bSDimitry Andric if (CallInst *CI = dyn_cast<CallInst>(U)) 46963dac3a9bSDimitry Andric UpgradeIntrinsicCall(CI, I.second); 4697f22ef01cSRoman Divacky } 4698f22ef01cSRoman Divacky } 4699f22ef01cSRoman Divacky 47003ca95b02SDimitry Andric // Update calls to the remangled intrinsics 47013ca95b02SDimitry Andric for (auto &I : RemangledIntrinsics) 47023ca95b02SDimitry Andric for (auto UI = I.first->materialized_user_begin(), UE = I.first->user_end(); 47033ca95b02SDimitry Andric UI != UE;) 47043ca95b02SDimitry Andric // Don't expect any other users than call sites 47053ca95b02SDimitry Andric CallSite(*UI++).setCalledFunction(I.second); 47063ca95b02SDimitry Andric 47077d523365SDimitry Andric // Finish fn->subprogram upgrade for materialized functions. 4708d88c1a5aSDimitry Andric if (DISubprogram *SP = MDLoader->lookupSubprogramForFunction(F)) 47097d523365SDimitry Andric F->setSubprogram(SP); 47107d523365SDimitry Andric 4711d88c1a5aSDimitry Andric // Check if the TBAA Metadata are valid, otherwise we will need to strip them. 4712d88c1a5aSDimitry Andric if (!MDLoader->isStrippingTBAA()) { 4713d88c1a5aSDimitry Andric for (auto &I : instructions(F)) { 4714d88c1a5aSDimitry Andric MDNode *TBAA = I.getMetadata(LLVMContext::MD_tbaa); 4715d88c1a5aSDimitry Andric if (!TBAA || TBAAVerifyHelper.visitTBAAMetadata(I, TBAA)) 4716d88c1a5aSDimitry Andric continue; 4717d88c1a5aSDimitry Andric MDLoader->setStripTBAA(true); 4718d88c1a5aSDimitry Andric stripTBAA(F->getParent()); 4719d88c1a5aSDimitry Andric } 4720d88c1a5aSDimitry Andric } 4721d88c1a5aSDimitry Andric 472239d628a0SDimitry Andric // Bring in any functions that this function forward-referenced via 472339d628a0SDimitry Andric // blockaddresses. 472439d628a0SDimitry Andric return materializeForwardReferencedFunctions(); 4725f22ef01cSRoman Divacky } 4726f22ef01cSRoman Divacky 4727d88c1a5aSDimitry Andric Error BitcodeReader::materializeModule() { 4728d88c1a5aSDimitry Andric if (Error Err = materializeMetadata()) 4729d88c1a5aSDimitry Andric return Err; 4730ff0cc061SDimitry Andric 473139d628a0SDimitry Andric // Promise to materialize all forward references. 473239d628a0SDimitry Andric WillMaterializeAllForwardRefs = true; 473339d628a0SDimitry Andric 4734f22ef01cSRoman Divacky // Iterate over the module, deserializing any functions that are still on 4735f22ef01cSRoman Divacky // disk. 47367d523365SDimitry Andric for (Function &F : *TheModule) { 4737d88c1a5aSDimitry Andric if (Error Err = materialize(&F)) 4738d88c1a5aSDimitry Andric return Err; 4739f785676fSDimitry Andric } 47407d523365SDimitry Andric // At this point, if there are any function bodies, parse the rest of 47417d523365SDimitry Andric // the bits in the module past the last function block we have recorded 47427d523365SDimitry Andric // through either lazy scanning or the VST. 47437d523365SDimitry Andric if (LastFunctionBlockBit || NextUnreadBit) 4744d88c1a5aSDimitry Andric if (Error Err = parseModule(LastFunctionBlockBit > NextUnreadBit 4745d88c1a5aSDimitry Andric ? LastFunctionBlockBit 4746d88c1a5aSDimitry Andric : NextUnreadBit)) 4747d88c1a5aSDimitry Andric return Err; 4748dff0c46cSDimitry Andric 474939d628a0SDimitry Andric // Check that all block address forward references got resolved (as we 475039d628a0SDimitry Andric // promised above). 475139d628a0SDimitry Andric if (!BasicBlockFwdRefs.empty()) 47528f0fd8f6SDimitry Andric return error("Never resolved function from blockaddress"); 475339d628a0SDimitry Andric 4754f22ef01cSRoman Divacky // Upgrade any intrinsic calls that slipped through (should not happen!) and 4755f22ef01cSRoman Divacky // delete the old functions to clean up. We can't do this unless the entire 4756f22ef01cSRoman Divacky // module is materialized because there could always be another function body 4757f22ef01cSRoman Divacky // with calls to the old function. 47583dac3a9bSDimitry Andric for (auto &I : UpgradedIntrinsics) { 47593dac3a9bSDimitry Andric for (auto *U : I.first->users()) { 47603dac3a9bSDimitry Andric if (CallInst *CI = dyn_cast<CallInst>(U)) 47613dac3a9bSDimitry Andric UpgradeIntrinsicCall(CI, I.second); 4762f22ef01cSRoman Divacky } 47633dac3a9bSDimitry Andric if (!I.first->use_empty()) 47643dac3a9bSDimitry Andric I.first->replaceAllUsesWith(I.second); 47653dac3a9bSDimitry Andric I.first->eraseFromParent(); 4766f22ef01cSRoman Divacky } 47673dac3a9bSDimitry Andric UpgradedIntrinsics.clear(); 47683ca95b02SDimitry Andric // Do the same for remangled intrinsics 47693ca95b02SDimitry Andric for (auto &I : RemangledIntrinsics) { 47703ca95b02SDimitry Andric I.first->replaceAllUsesWith(I.second); 47713ca95b02SDimitry Andric I.first->eraseFromParent(); 47723ca95b02SDimitry Andric } 47733ca95b02SDimitry Andric RemangledIntrinsics.clear(); 4774f785676fSDimitry Andric 47757d523365SDimitry Andric UpgradeDebugInfo(*TheModule); 47763ca95b02SDimitry Andric 47773ca95b02SDimitry Andric UpgradeModuleFlags(*TheModule); 4778d88c1a5aSDimitry Andric return Error::success(); 4779dff0c46cSDimitry Andric } 47806122f3e6SDimitry Andric 478139d628a0SDimitry Andric std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const { 478239d628a0SDimitry Andric return IdentifiedStructTypes; 478339d628a0SDimitry Andric } 478439d628a0SDimitry Andric 47853ca95b02SDimitry Andric ModuleSummaryIndexBitcodeReader::ModuleSummaryIndexBitcodeReader( 4786f37b6182SDimitry Andric BitstreamCursor Cursor, StringRef Strtab, ModuleSummaryIndex &TheIndex, 4787f37b6182SDimitry Andric StringRef ModulePath, unsigned ModuleId) 4788f37b6182SDimitry Andric : BitcodeReaderBase(std::move(Cursor), Strtab), TheIndex(TheIndex), 4789f37b6182SDimitry Andric ModulePath(ModulePath), ModuleId(ModuleId) {} 4790f37b6182SDimitry Andric 479124d58133SDimitry Andric ModuleSummaryIndex::ModuleInfo * 479224d58133SDimitry Andric ModuleSummaryIndexBitcodeReader::addThisModule() { 479324d58133SDimitry Andric return TheIndex.addModule(ModulePath, ModuleId); 4794f37b6182SDimitry Andric } 47953ca95b02SDimitry Andric 47960f5676f4SDimitry Andric std::pair<ValueInfo, GlobalValue::GUID> 47970f5676f4SDimitry Andric ModuleSummaryIndexBitcodeReader::getValueInfoFromValueId(unsigned ValueId) { 47980f5676f4SDimitry Andric auto VGI = ValueIdToValueInfoMap[ValueId]; 47990f5676f4SDimitry Andric assert(VGI.first); 48000f5676f4SDimitry Andric return VGI; 48017d523365SDimitry Andric } 48027d523365SDimitry Andric 48036bc11b14SDimitry Andric void ModuleSummaryIndexBitcodeReader::setValueGUID( 48046bc11b14SDimitry Andric uint64_t ValueID, StringRef ValueName, GlobalValue::LinkageTypes Linkage, 48056bc11b14SDimitry Andric StringRef SourceFileName) { 48066bc11b14SDimitry Andric std::string GlobalId = 48076bc11b14SDimitry Andric GlobalValue::getGlobalIdentifier(ValueName, Linkage, SourceFileName); 48086bc11b14SDimitry Andric auto ValueGUID = GlobalValue::getGUID(GlobalId); 48096bc11b14SDimitry Andric auto OriginalNameID = ValueGUID; 48106bc11b14SDimitry Andric if (GlobalValue::isLocalLinkage(Linkage)) 48116bc11b14SDimitry Andric OriginalNameID = GlobalValue::getGUID(ValueName); 48126bc11b14SDimitry Andric if (PrintSummaryGUIDs) 48136bc11b14SDimitry Andric dbgs() << "GUID " << ValueGUID << "(" << OriginalNameID << ") is " 48146bc11b14SDimitry Andric << ValueName << "\n"; 48150f5676f4SDimitry Andric ValueIdToValueInfoMap[ValueID] = 48160f5676f4SDimitry Andric std::make_pair(TheIndex.getOrInsertValueInfo(ValueGUID), OriginalNameID); 48176bc11b14SDimitry Andric } 48186bc11b14SDimitry Andric 48193ca95b02SDimitry Andric // Specialized value symbol table parser used when reading module index 48203ca95b02SDimitry Andric // blocks where we don't actually create global values. The parsed information 48213ca95b02SDimitry Andric // is saved in the bitcode reader for use when later parsing summaries. 4822d88c1a5aSDimitry Andric Error ModuleSummaryIndexBitcodeReader::parseValueSymbolTable( 48233ca95b02SDimitry Andric uint64_t Offset, 48243ca95b02SDimitry Andric DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap) { 48256bc11b14SDimitry Andric // With a strtab the VST is not required to parse the summary. 48266bc11b14SDimitry Andric if (UseStrtab) 48276bc11b14SDimitry Andric return Error::success(); 48286bc11b14SDimitry Andric 48293ca95b02SDimitry Andric assert(Offset > 0 && "Expected non-zero VST offset"); 48303ca95b02SDimitry Andric uint64_t CurrentBit = jumpToValueSymbolTable(Offset, Stream); 48317d523365SDimitry Andric 48327d523365SDimitry Andric if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID)) 48337d523365SDimitry Andric return error("Invalid record"); 48347d523365SDimitry Andric 48357d523365SDimitry Andric SmallVector<uint64_t, 64> Record; 48367d523365SDimitry Andric 48377d523365SDimitry Andric // Read all the records for this value table. 48387d523365SDimitry Andric SmallString<128> ValueName; 4839d88c1a5aSDimitry Andric 4840d88c1a5aSDimitry Andric while (true) { 48417d523365SDimitry Andric BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 48427d523365SDimitry Andric 48437d523365SDimitry Andric switch (Entry.Kind) { 48447d523365SDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already. 48457d523365SDimitry Andric case BitstreamEntry::Error: 48467d523365SDimitry Andric return error("Malformed block"); 48477d523365SDimitry Andric case BitstreamEntry::EndBlock: 48483ca95b02SDimitry Andric // Done parsing VST, jump back to wherever we came from. 48493ca95b02SDimitry Andric Stream.JumpToBit(CurrentBit); 4850d88c1a5aSDimitry Andric return Error::success(); 48517d523365SDimitry Andric case BitstreamEntry::Record: 48527d523365SDimitry Andric // The interesting case. 48537d523365SDimitry Andric break; 48547d523365SDimitry Andric } 48557d523365SDimitry Andric 48567d523365SDimitry Andric // Read a record. 48577d523365SDimitry Andric Record.clear(); 48587d523365SDimitry Andric switch (Stream.readRecord(Entry.ID, Record)) { 48597d523365SDimitry Andric default: // Default behavior: ignore (e.g. VST_CODE_BBENTRY records). 48607d523365SDimitry Andric break; 48613ca95b02SDimitry Andric case bitc::VST_CODE_ENTRY: { // VST_CODE_ENTRY: [valueid, namechar x N] 48623ca95b02SDimitry Andric if (convertToString(Record, 1, ValueName)) 48633ca95b02SDimitry Andric return error("Invalid record"); 48643ca95b02SDimitry Andric unsigned ValueID = Record[0]; 48653ca95b02SDimitry Andric assert(!SourceFileName.empty()); 48663ca95b02SDimitry Andric auto VLI = ValueIdToLinkageMap.find(ValueID); 48673ca95b02SDimitry Andric assert(VLI != ValueIdToLinkageMap.end() && 48683ca95b02SDimitry Andric "No linkage found for VST entry?"); 48693ca95b02SDimitry Andric auto Linkage = VLI->second; 48706bc11b14SDimitry Andric setValueGUID(ValueID, ValueName, Linkage, SourceFileName); 48713ca95b02SDimitry Andric ValueName.clear(); 48723ca95b02SDimitry Andric break; 48733ca95b02SDimitry Andric } 48747d523365SDimitry Andric case bitc::VST_CODE_FNENTRY: { 48753ca95b02SDimitry Andric // VST_CODE_FNENTRY: [valueid, offset, namechar x N] 48767d523365SDimitry Andric if (convertToString(Record, 2, ValueName)) 48777d523365SDimitry Andric return error("Invalid record"); 48787d523365SDimitry Andric unsigned ValueID = Record[0]; 48793ca95b02SDimitry Andric assert(!SourceFileName.empty()); 48803ca95b02SDimitry Andric auto VLI = ValueIdToLinkageMap.find(ValueID); 48813ca95b02SDimitry Andric assert(VLI != ValueIdToLinkageMap.end() && 48823ca95b02SDimitry Andric "No linkage found for VST entry?"); 48833ca95b02SDimitry Andric auto Linkage = VLI->second; 48846bc11b14SDimitry Andric setValueGUID(ValueID, ValueName, Linkage, SourceFileName); 48857d523365SDimitry Andric ValueName.clear(); 48867d523365SDimitry Andric break; 48877d523365SDimitry Andric } 48883ca95b02SDimitry Andric case bitc::VST_CODE_COMBINED_ENTRY: { 48893ca95b02SDimitry Andric // VST_CODE_COMBINED_ENTRY: [valueid, refguid] 48903ca95b02SDimitry Andric unsigned ValueID = Record[0]; 48913ca95b02SDimitry Andric GlobalValue::GUID RefGUID = Record[1]; 48923ca95b02SDimitry Andric // The "original name", which is the second value of the pair will be 48933ca95b02SDimitry Andric // overriden later by a FS_COMBINED_ORIGINAL_NAME in the combined index. 48940f5676f4SDimitry Andric ValueIdToValueInfoMap[ValueID] = 48950f5676f4SDimitry Andric std::make_pair(TheIndex.getOrInsertValueInfo(RefGUID), RefGUID); 48967d523365SDimitry Andric break; 48977d523365SDimitry Andric } 48987d523365SDimitry Andric } 48997d523365SDimitry Andric } 49007d523365SDimitry Andric } 49017d523365SDimitry Andric 49023ca95b02SDimitry Andric // Parse just the blocks needed for building the index out of the module. 49033ca95b02SDimitry Andric // At the end of this routine the module Index is populated with a map 49043ca95b02SDimitry Andric // from global value id to GlobalValueSummary objects. 4905f37b6182SDimitry Andric Error ModuleSummaryIndexBitcodeReader::parseModule() { 49067d523365SDimitry Andric if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID)) 49077d523365SDimitry Andric return error("Invalid record"); 49087d523365SDimitry Andric 49093ca95b02SDimitry Andric SmallVector<uint64_t, 64> Record; 49103ca95b02SDimitry Andric DenseMap<unsigned, GlobalValue::LinkageTypes> ValueIdToLinkageMap; 49113ca95b02SDimitry Andric unsigned ValueId = 0; 49123ca95b02SDimitry Andric 49133ca95b02SDimitry Andric // Read the index for this module. 4914d88c1a5aSDimitry Andric while (true) { 49157d523365SDimitry Andric BitstreamEntry Entry = Stream.advance(); 49167d523365SDimitry Andric 49177d523365SDimitry Andric switch (Entry.Kind) { 49187d523365SDimitry Andric case BitstreamEntry::Error: 49197d523365SDimitry Andric return error("Malformed block"); 49207d523365SDimitry Andric case BitstreamEntry::EndBlock: 4921d88c1a5aSDimitry Andric return Error::success(); 49227d523365SDimitry Andric 49237d523365SDimitry Andric case BitstreamEntry::SubBlock: 49247d523365SDimitry Andric switch (Entry.ID) { 49257d523365SDimitry Andric default: // Skip unknown content. 49267d523365SDimitry Andric if (Stream.SkipBlock()) 49277d523365SDimitry Andric return error("Invalid record"); 49287d523365SDimitry Andric break; 49297d523365SDimitry Andric case bitc::BLOCKINFO_BLOCK_ID: 49307d523365SDimitry Andric // Need to parse these to get abbrev ids (e.g. for VST) 4931d88c1a5aSDimitry Andric if (readBlockInfo()) 49327d523365SDimitry Andric return error("Malformed block"); 49337d523365SDimitry Andric break; 49347d523365SDimitry Andric case bitc::VALUE_SYMTAB_BLOCK_ID: 49353ca95b02SDimitry Andric // Should have been parsed earlier via VSTOffset, unless there 49363ca95b02SDimitry Andric // is no summary section. 49373ca95b02SDimitry Andric assert(((SeenValueSymbolTable && VSTOffset > 0) || 49383ca95b02SDimitry Andric !SeenGlobalValSummary) && 49393ca95b02SDimitry Andric "Expected early VST parse via VSTOffset record"); 49407d523365SDimitry Andric if (Stream.SkipBlock()) 49417d523365SDimitry Andric return error("Invalid record"); 49423ca95b02SDimitry Andric break; 49433ca95b02SDimitry Andric case bitc::GLOBALVAL_SUMMARY_BLOCK_ID: 494424d58133SDimitry Andric case bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID: 49453ca95b02SDimitry Andric assert(!SeenValueSymbolTable && 49463ca95b02SDimitry Andric "Already read VST when parsing summary block?"); 4947d88c1a5aSDimitry Andric // We might not have a VST if there were no values in the 4948d88c1a5aSDimitry Andric // summary. An empty summary block generated when we are 4949d88c1a5aSDimitry Andric // performing ThinLTO compiles so we don't later invoke 4950d88c1a5aSDimitry Andric // the regular LTO process on them. 4951d88c1a5aSDimitry Andric if (VSTOffset > 0) { 4952d88c1a5aSDimitry Andric if (Error Err = parseValueSymbolTable(VSTOffset, ValueIdToLinkageMap)) 4953d88c1a5aSDimitry Andric return Err; 49543ca95b02SDimitry Andric SeenValueSymbolTable = true; 4955d88c1a5aSDimitry Andric } 49563ca95b02SDimitry Andric SeenGlobalValSummary = true; 495724d58133SDimitry Andric if (Error Err = parseEntireSummary(Entry.ID)) 4958d88c1a5aSDimitry Andric return Err; 49597d523365SDimitry Andric break; 49607d523365SDimitry Andric case bitc::MODULE_STRTAB_BLOCK_ID: 4961d88c1a5aSDimitry Andric if (Error Err = parseModuleStringTable()) 4962d88c1a5aSDimitry Andric return Err; 49637d523365SDimitry Andric break; 49647d523365SDimitry Andric } 49657d523365SDimitry Andric continue; 49667d523365SDimitry Andric 49673ca95b02SDimitry Andric case BitstreamEntry::Record: { 49683ca95b02SDimitry Andric Record.clear(); 49693ca95b02SDimitry Andric auto BitCode = Stream.readRecord(Entry.ID, Record); 49703ca95b02SDimitry Andric switch (BitCode) { 49713ca95b02SDimitry Andric default: 49723ca95b02SDimitry Andric break; // Default behavior, ignore unknown content. 49736bc11b14SDimitry Andric case bitc::MODULE_CODE_VERSION: { 49746bc11b14SDimitry Andric if (Error Err = parseVersionRecord(Record).takeError()) 49756bc11b14SDimitry Andric return Err; 49766bc11b14SDimitry Andric break; 49776bc11b14SDimitry Andric } 49783ca95b02SDimitry Andric /// MODULE_CODE_SOURCE_FILENAME: [namechar x N] 49793ca95b02SDimitry Andric case bitc::MODULE_CODE_SOURCE_FILENAME: { 49803ca95b02SDimitry Andric SmallString<128> ValueName; 49813ca95b02SDimitry Andric if (convertToString(Record, 0, ValueName)) 49823ca95b02SDimitry Andric return error("Invalid record"); 49833ca95b02SDimitry Andric SourceFileName = ValueName.c_str(); 49843ca95b02SDimitry Andric break; 49853ca95b02SDimitry Andric } 49863ca95b02SDimitry Andric /// MODULE_CODE_HASH: [5*i32] 49873ca95b02SDimitry Andric case bitc::MODULE_CODE_HASH: { 49883ca95b02SDimitry Andric if (Record.size() != 5) 49893ca95b02SDimitry Andric return error("Invalid hash length " + Twine(Record.size()).str()); 499024d58133SDimitry Andric auto &Hash = addThisModule()->second.second; 49913ca95b02SDimitry Andric int Pos = 0; 49923ca95b02SDimitry Andric for (auto &Val : Record) { 49933ca95b02SDimitry Andric assert(!(Val >> 32) && "Unexpected high bits set"); 49943ca95b02SDimitry Andric Hash[Pos++] = Val; 49953ca95b02SDimitry Andric } 49963ca95b02SDimitry Andric break; 49973ca95b02SDimitry Andric } 49983ca95b02SDimitry Andric /// MODULE_CODE_VSTOFFSET: [offset] 49993ca95b02SDimitry Andric case bitc::MODULE_CODE_VSTOFFSET: 50003ca95b02SDimitry Andric if (Record.size() < 1) 50013ca95b02SDimitry Andric return error("Invalid record"); 5002d88c1a5aSDimitry Andric // Note that we subtract 1 here because the offset is relative to one 5003d88c1a5aSDimitry Andric // word before the start of the identification or module block, which 5004d88c1a5aSDimitry Andric // was historically always the start of the regular bitcode header. 5005d88c1a5aSDimitry Andric VSTOffset = Record[0] - 1; 50063ca95b02SDimitry Andric break; 50076bc11b14SDimitry Andric // v1 GLOBALVAR: [pointer type, isconst, initid, linkage, ...] 50086bc11b14SDimitry Andric // v1 FUNCTION: [type, callingconv, isproto, linkage, ...] 50096bc11b14SDimitry Andric // v1 ALIAS: [alias type, addrspace, aliasee val#, linkage, ...] 50106bc11b14SDimitry Andric // v2: [strtab offset, strtab size, v1] 50117a7e6055SDimitry Andric case bitc::MODULE_CODE_GLOBALVAR: 50127a7e6055SDimitry Andric case bitc::MODULE_CODE_FUNCTION: 50133ca95b02SDimitry Andric case bitc::MODULE_CODE_ALIAS: { 50146bc11b14SDimitry Andric StringRef Name; 50156bc11b14SDimitry Andric ArrayRef<uint64_t> GVRecord; 50166bc11b14SDimitry Andric std::tie(Name, GVRecord) = readNameFromStrtab(Record); 50176bc11b14SDimitry Andric if (GVRecord.size() <= 3) 50183ca95b02SDimitry Andric return error("Invalid record"); 50196bc11b14SDimitry Andric uint64_t RawLinkage = GVRecord[3]; 50203ca95b02SDimitry Andric GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage); 50216bc11b14SDimitry Andric if (!UseStrtab) { 50223ca95b02SDimitry Andric ValueIdToLinkageMap[ValueId++] = Linkage; 50233ca95b02SDimitry Andric break; 50243ca95b02SDimitry Andric } 50256bc11b14SDimitry Andric 50266bc11b14SDimitry Andric setValueGUID(ValueId++, Name, Linkage, SourceFileName); 50276bc11b14SDimitry Andric break; 50286bc11b14SDimitry Andric } 50293ca95b02SDimitry Andric } 50303ca95b02SDimitry Andric } 50317d523365SDimitry Andric continue; 50327d523365SDimitry Andric } 50337d523365SDimitry Andric } 50347d523365SDimitry Andric } 50357d523365SDimitry Andric 5036d88c1a5aSDimitry Andric std::vector<ValueInfo> 5037d88c1a5aSDimitry Andric ModuleSummaryIndexBitcodeReader::makeRefList(ArrayRef<uint64_t> Record) { 5038d88c1a5aSDimitry Andric std::vector<ValueInfo> Ret; 5039d88c1a5aSDimitry Andric Ret.reserve(Record.size()); 5040d88c1a5aSDimitry Andric for (uint64_t RefValueId : Record) 50410f5676f4SDimitry Andric Ret.push_back(getValueInfoFromValueId(RefValueId).first); 5042d88c1a5aSDimitry Andric return Ret; 5043d88c1a5aSDimitry Andric } 5044d88c1a5aSDimitry Andric 5045d88c1a5aSDimitry Andric std::vector<FunctionSummary::EdgeTy> ModuleSummaryIndexBitcodeReader::makeCallList( 5046d88c1a5aSDimitry Andric ArrayRef<uint64_t> Record, bool IsOldProfileFormat, bool HasProfile) { 5047d88c1a5aSDimitry Andric std::vector<FunctionSummary::EdgeTy> Ret; 5048d88c1a5aSDimitry Andric Ret.reserve(Record.size()); 5049d88c1a5aSDimitry Andric for (unsigned I = 0, E = Record.size(); I != E; ++I) { 5050d88c1a5aSDimitry Andric CalleeInfo::HotnessType Hotness = CalleeInfo::HotnessType::Unknown; 50510f5676f4SDimitry Andric ValueInfo Callee = getValueInfoFromValueId(Record[I]).first; 5052d88c1a5aSDimitry Andric if (IsOldProfileFormat) { 5053d88c1a5aSDimitry Andric I += 1; // Skip old callsitecount field 5054d88c1a5aSDimitry Andric if (HasProfile) 5055d88c1a5aSDimitry Andric I += 1; // Skip old profilecount field 5056d88c1a5aSDimitry Andric } else if (HasProfile) 5057d88c1a5aSDimitry Andric Hotness = static_cast<CalleeInfo::HotnessType>(Record[++I]); 50580f5676f4SDimitry Andric Ret.push_back(FunctionSummary::EdgeTy{Callee, CalleeInfo{Hotness}}); 5059d88c1a5aSDimitry Andric } 5060d88c1a5aSDimitry Andric return Ret; 5061d88c1a5aSDimitry Andric } 5062d88c1a5aSDimitry Andric 50633ca95b02SDimitry Andric // Eagerly parse the entire summary block. This populates the GlobalValueSummary 50643ca95b02SDimitry Andric // objects in the index. 506524d58133SDimitry Andric Error ModuleSummaryIndexBitcodeReader::parseEntireSummary(unsigned ID) { 506624d58133SDimitry Andric if (Stream.EnterSubBlock(ID)) 50677d523365SDimitry Andric return error("Invalid record"); 50687d523365SDimitry Andric SmallVector<uint64_t, 64> Record; 50697d523365SDimitry Andric 50703ca95b02SDimitry Andric // Parse version 50713ca95b02SDimitry Andric { 50723ca95b02SDimitry Andric BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 50733ca95b02SDimitry Andric if (Entry.Kind != BitstreamEntry::Record) 50743ca95b02SDimitry Andric return error("Invalid Summary Block: record for version expected"); 50753ca95b02SDimitry Andric if (Stream.readRecord(Entry.ID, Record) != bitc::FS_VERSION) 50763ca95b02SDimitry Andric return error("Invalid Summary Block: version expected"); 50773ca95b02SDimitry Andric } 50783ca95b02SDimitry Andric const uint64_t Version = Record[0]; 5079d88c1a5aSDimitry Andric const bool IsOldProfileFormat = Version == 1; 50802cab237bSDimitry Andric if (Version < 1 || Version > 4) 5081d88c1a5aSDimitry Andric return error("Invalid summary version " + Twine(Version) + 50822cab237bSDimitry Andric ", 1, 2, 3 or 4 expected"); 50833ca95b02SDimitry Andric Record.clear(); 50843ca95b02SDimitry Andric 50853ca95b02SDimitry Andric // Keep around the last seen summary to be used when we see an optional 50863ca95b02SDimitry Andric // "OriginalName" attachement. 50873ca95b02SDimitry Andric GlobalValueSummary *LastSeenSummary = nullptr; 50887a7e6055SDimitry Andric GlobalValue::GUID LastSeenGUID = 0; 50897a7e6055SDimitry Andric 50907a7e6055SDimitry Andric // We can expect to see any number of type ID information records before 50917a7e6055SDimitry Andric // each function summary records; these variables store the information 50927a7e6055SDimitry Andric // collected so far so that it can be used to create the summary object. 5093d88c1a5aSDimitry Andric std::vector<GlobalValue::GUID> PendingTypeTests; 50947a7e6055SDimitry Andric std::vector<FunctionSummary::VFuncId> PendingTypeTestAssumeVCalls, 50957a7e6055SDimitry Andric PendingTypeCheckedLoadVCalls; 50967a7e6055SDimitry Andric std::vector<FunctionSummary::ConstVCall> PendingTypeTestAssumeConstVCalls, 50977a7e6055SDimitry Andric PendingTypeCheckedLoadConstVCalls; 5098d88c1a5aSDimitry Andric 5099d88c1a5aSDimitry Andric while (true) { 51007d523365SDimitry Andric BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 51017d523365SDimitry Andric 51027d523365SDimitry Andric switch (Entry.Kind) { 51037d523365SDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already. 51047d523365SDimitry Andric case BitstreamEntry::Error: 51057d523365SDimitry Andric return error("Malformed block"); 51067d523365SDimitry Andric case BitstreamEntry::EndBlock: 5107d88c1a5aSDimitry Andric return Error::success(); 51087d523365SDimitry Andric case BitstreamEntry::Record: 51097d523365SDimitry Andric // The interesting case. 51107d523365SDimitry Andric break; 51117d523365SDimitry Andric } 51127d523365SDimitry Andric 51137d523365SDimitry Andric // Read a record. The record format depends on whether this 51147d523365SDimitry Andric // is a per-module index or a combined index file. In the per-module 51157d523365SDimitry Andric // case the records contain the associated value's ID for correlation 51167d523365SDimitry Andric // with VST entries. In the combined index the correlation is done 51177d523365SDimitry Andric // via the bitcode offset of the summary records (which were saved 51187d523365SDimitry Andric // in the combined index VST entries). The records also contain 51197d523365SDimitry Andric // information used for ThinLTO renaming and importing. 51207d523365SDimitry Andric Record.clear(); 51213ca95b02SDimitry Andric auto BitCode = Stream.readRecord(Entry.ID, Record); 51223ca95b02SDimitry Andric switch (BitCode) { 51237d523365SDimitry Andric default: // Default behavior: ignore. 51247d523365SDimitry Andric break; 51256bc11b14SDimitry Andric case bitc::FS_VALUE_GUID: { // [valueid, refguid] 51266bc11b14SDimitry Andric uint64_t ValueID = Record[0]; 51276bc11b14SDimitry Andric GlobalValue::GUID RefGUID = Record[1]; 51280f5676f4SDimitry Andric ValueIdToValueInfoMap[ValueID] = 51290f5676f4SDimitry Andric std::make_pair(TheIndex.getOrInsertValueInfo(RefGUID), RefGUID); 51306bc11b14SDimitry Andric break; 51316bc11b14SDimitry Andric } 51322cab237bSDimitry Andric // FS_PERMODULE: [valueid, flags, instcount, fflags, numrefs, 51332cab237bSDimitry Andric // numrefs x valueid, n x (valueid)] 51342cab237bSDimitry Andric // FS_PERMODULE_PROFILE: [valueid, flags, instcount, fflags, numrefs, 51353ca95b02SDimitry Andric // numrefs x valueid, 5136d88c1a5aSDimitry Andric // n x (valueid, hotness)] 51373ca95b02SDimitry Andric case bitc::FS_PERMODULE: 51383ca95b02SDimitry Andric case bitc::FS_PERMODULE_PROFILE: { 51397d523365SDimitry Andric unsigned ValueID = Record[0]; 51403ca95b02SDimitry Andric uint64_t RawFlags = Record[1]; 51417d523365SDimitry Andric unsigned InstCount = Record[2]; 51422cab237bSDimitry Andric uint64_t RawFunFlags = 0; 51433ca95b02SDimitry Andric unsigned NumRefs = Record[3]; 51442cab237bSDimitry Andric int RefListStartIndex = 4; 51452cab237bSDimitry Andric if (Version >= 4) { 51462cab237bSDimitry Andric RawFunFlags = Record[3]; 51472cab237bSDimitry Andric NumRefs = Record[4]; 51482cab237bSDimitry Andric RefListStartIndex = 5; 51492cab237bSDimitry Andric } 51502cab237bSDimitry Andric 51513ca95b02SDimitry Andric auto Flags = getDecodedGVSummaryFlags(RawFlags, Version); 51527d523365SDimitry Andric // The module path string ref set in the summary must be owned by the 51537d523365SDimitry Andric // index's module string table. Since we don't have a module path 51547d523365SDimitry Andric // string table section in the per-module index, we create a single 51557d523365SDimitry Andric // module path string table entry with an empty (0) ID to take 51567d523365SDimitry Andric // ownership. 51573ca95b02SDimitry Andric int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs; 51583ca95b02SDimitry Andric assert(Record.size() >= RefListStartIndex + NumRefs && 51593ca95b02SDimitry Andric "Record size inconsistent with number of references"); 5160d88c1a5aSDimitry Andric std::vector<ValueInfo> Refs = makeRefList( 5161d88c1a5aSDimitry Andric ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs)); 51623ca95b02SDimitry Andric bool HasProfile = (BitCode == bitc::FS_PERMODULE_PROFILE); 5163d88c1a5aSDimitry Andric std::vector<FunctionSummary::EdgeTy> Calls = makeCallList( 5164d88c1a5aSDimitry Andric ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex), 5165d88c1a5aSDimitry Andric IsOldProfileFormat, HasProfile); 5166d88c1a5aSDimitry Andric auto FS = llvm::make_unique<FunctionSummary>( 51672cab237bSDimitry Andric Flags, InstCount, getDecodedFFlags(RawFunFlags), std::move(Refs), 51682cab237bSDimitry Andric std::move(Calls), std::move(PendingTypeTests), 51692cab237bSDimitry Andric std::move(PendingTypeTestAssumeVCalls), 51707a7e6055SDimitry Andric std::move(PendingTypeCheckedLoadVCalls), 51717a7e6055SDimitry Andric std::move(PendingTypeTestAssumeConstVCalls), 51727a7e6055SDimitry Andric std::move(PendingTypeCheckedLoadConstVCalls)); 5173d88c1a5aSDimitry Andric PendingTypeTests.clear(); 51747a7e6055SDimitry Andric PendingTypeTestAssumeVCalls.clear(); 51757a7e6055SDimitry Andric PendingTypeCheckedLoadVCalls.clear(); 51767a7e6055SDimitry Andric PendingTypeTestAssumeConstVCalls.clear(); 51777a7e6055SDimitry Andric PendingTypeCheckedLoadConstVCalls.clear(); 51780f5676f4SDimitry Andric auto VIAndOriginalGUID = getValueInfoFromValueId(ValueID); 517924d58133SDimitry Andric FS->setModulePath(addThisModule()->first()); 51800f5676f4SDimitry Andric FS->setOriginalName(VIAndOriginalGUID.second); 51810f5676f4SDimitry Andric TheIndex.addGlobalValueSummary(VIAndOriginalGUID.first, std::move(FS)); 51823ca95b02SDimitry Andric break; 51833ca95b02SDimitry Andric } 51843ca95b02SDimitry Andric // FS_ALIAS: [valueid, flags, valueid] 51853ca95b02SDimitry Andric // Aliases must be emitted (and parsed) after all FS_PERMODULE entries, as 51863ca95b02SDimitry Andric // they expect all aliasee summaries to be available. 51873ca95b02SDimitry Andric case bitc::FS_ALIAS: { 51883ca95b02SDimitry Andric unsigned ValueID = Record[0]; 51893ca95b02SDimitry Andric uint64_t RawFlags = Record[1]; 51903ca95b02SDimitry Andric unsigned AliaseeID = Record[2]; 51913ca95b02SDimitry Andric auto Flags = getDecodedGVSummaryFlags(RawFlags, Version); 51922cab237bSDimitry Andric auto AS = llvm::make_unique<AliasSummary>(Flags); 51933ca95b02SDimitry Andric // The module path string ref set in the summary must be owned by the 51943ca95b02SDimitry Andric // index's module string table. Since we don't have a module path 51953ca95b02SDimitry Andric // string table section in the per-module index, we create a single 51963ca95b02SDimitry Andric // module path string table entry with an empty (0) ID to take 51973ca95b02SDimitry Andric // ownership. 519824d58133SDimitry Andric AS->setModulePath(addThisModule()->first()); 51993ca95b02SDimitry Andric 52000f5676f4SDimitry Andric GlobalValue::GUID AliaseeGUID = 52010f5676f4SDimitry Andric getValueInfoFromValueId(AliaseeID).first.getGUID(); 5202f37b6182SDimitry Andric auto AliaseeInModule = 5203f37b6182SDimitry Andric TheIndex.findSummaryInModule(AliaseeGUID, ModulePath); 5204f37b6182SDimitry Andric if (!AliaseeInModule) 52053ca95b02SDimitry Andric return error("Alias expects aliasee summary to be parsed"); 5206f37b6182SDimitry Andric AS->setAliasee(AliaseeInModule); 52072cab237bSDimitry Andric AS->setAliaseeGUID(AliaseeGUID); 52083ca95b02SDimitry Andric 52090f5676f4SDimitry Andric auto GUID = getValueInfoFromValueId(ValueID); 52103ca95b02SDimitry Andric AS->setOriginalName(GUID.second); 5211d88c1a5aSDimitry Andric TheIndex.addGlobalValueSummary(GUID.first, std::move(AS)); 52123ca95b02SDimitry Andric break; 52133ca95b02SDimitry Andric } 52143ca95b02SDimitry Andric // FS_PERMODULE_GLOBALVAR_INIT_REFS: [valueid, flags, n x valueid] 52153ca95b02SDimitry Andric case bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS: { 52163ca95b02SDimitry Andric unsigned ValueID = Record[0]; 52173ca95b02SDimitry Andric uint64_t RawFlags = Record[1]; 52183ca95b02SDimitry Andric auto Flags = getDecodedGVSummaryFlags(RawFlags, Version); 5219d88c1a5aSDimitry Andric std::vector<ValueInfo> Refs = 5220d88c1a5aSDimitry Andric makeRefList(ArrayRef<uint64_t>(Record).slice(2)); 5221d88c1a5aSDimitry Andric auto FS = llvm::make_unique<GlobalVarSummary>(Flags, std::move(Refs)); 522224d58133SDimitry Andric FS->setModulePath(addThisModule()->first()); 52230f5676f4SDimitry Andric auto GUID = getValueInfoFromValueId(ValueID); 52243ca95b02SDimitry Andric FS->setOriginalName(GUID.second); 5225d88c1a5aSDimitry Andric TheIndex.addGlobalValueSummary(GUID.first, std::move(FS)); 52263ca95b02SDimitry Andric break; 52273ca95b02SDimitry Andric } 52282cab237bSDimitry Andric // FS_COMBINED: [valueid, modid, flags, instcount, fflags, numrefs, 5229d88c1a5aSDimitry Andric // numrefs x valueid, n x (valueid)] 52302cab237bSDimitry Andric // FS_COMBINED_PROFILE: [valueid, modid, flags, instcount, fflags, numrefs, 5231d88c1a5aSDimitry Andric // numrefs x valueid, n x (valueid, hotness)] 52323ca95b02SDimitry Andric case bitc::FS_COMBINED: 52333ca95b02SDimitry Andric case bitc::FS_COMBINED_PROFILE: { 52343ca95b02SDimitry Andric unsigned ValueID = Record[0]; 52353ca95b02SDimitry Andric uint64_t ModuleId = Record[1]; 52363ca95b02SDimitry Andric uint64_t RawFlags = Record[2]; 52373ca95b02SDimitry Andric unsigned InstCount = Record[3]; 52382cab237bSDimitry Andric uint64_t RawFunFlags = 0; 52393ca95b02SDimitry Andric unsigned NumRefs = Record[4]; 52402cab237bSDimitry Andric int RefListStartIndex = 5; 52412cab237bSDimitry Andric 52422cab237bSDimitry Andric if (Version >= 4) { 52432cab237bSDimitry Andric RawFunFlags = Record[4]; 52442cab237bSDimitry Andric NumRefs = Record[5]; 52452cab237bSDimitry Andric RefListStartIndex = 6; 52462cab237bSDimitry Andric } 52472cab237bSDimitry Andric 52483ca95b02SDimitry Andric auto Flags = getDecodedGVSummaryFlags(RawFlags, Version); 52493ca95b02SDimitry Andric int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs; 52503ca95b02SDimitry Andric assert(Record.size() >= RefListStartIndex + NumRefs && 52513ca95b02SDimitry Andric "Record size inconsistent with number of references"); 5252d88c1a5aSDimitry Andric std::vector<ValueInfo> Refs = makeRefList( 5253d88c1a5aSDimitry Andric ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs)); 52543ca95b02SDimitry Andric bool HasProfile = (BitCode == bitc::FS_COMBINED_PROFILE); 5255d88c1a5aSDimitry Andric std::vector<FunctionSummary::EdgeTy> Edges = makeCallList( 5256d88c1a5aSDimitry Andric ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex), 5257d88c1a5aSDimitry Andric IsOldProfileFormat, HasProfile); 52580f5676f4SDimitry Andric ValueInfo VI = getValueInfoFromValueId(ValueID).first; 5259d88c1a5aSDimitry Andric auto FS = llvm::make_unique<FunctionSummary>( 52602cab237bSDimitry Andric Flags, InstCount, getDecodedFFlags(RawFunFlags), std::move(Refs), 52612cab237bSDimitry Andric std::move(Edges), std::move(PendingTypeTests), 52622cab237bSDimitry Andric std::move(PendingTypeTestAssumeVCalls), 52637a7e6055SDimitry Andric std::move(PendingTypeCheckedLoadVCalls), 52647a7e6055SDimitry Andric std::move(PendingTypeTestAssumeConstVCalls), 52657a7e6055SDimitry Andric std::move(PendingTypeCheckedLoadConstVCalls)); 5266d88c1a5aSDimitry Andric PendingTypeTests.clear(); 52677a7e6055SDimitry Andric PendingTypeTestAssumeVCalls.clear(); 52687a7e6055SDimitry Andric PendingTypeCheckedLoadVCalls.clear(); 52697a7e6055SDimitry Andric PendingTypeTestAssumeConstVCalls.clear(); 52707a7e6055SDimitry Andric PendingTypeCheckedLoadConstVCalls.clear(); 5271d88c1a5aSDimitry Andric LastSeenSummary = FS.get(); 52720f5676f4SDimitry Andric LastSeenGUID = VI.getGUID(); 5273d88c1a5aSDimitry Andric FS->setModulePath(ModuleIdMap[ModuleId]); 52740f5676f4SDimitry Andric TheIndex.addGlobalValueSummary(VI, std::move(FS)); 52753ca95b02SDimitry Andric break; 52763ca95b02SDimitry Andric } 52773ca95b02SDimitry Andric // FS_COMBINED_ALIAS: [valueid, modid, flags, valueid] 52783ca95b02SDimitry Andric // Aliases must be emitted (and parsed) after all FS_COMBINED entries, as 52793ca95b02SDimitry Andric // they expect all aliasee summaries to be available. 52803ca95b02SDimitry Andric case bitc::FS_COMBINED_ALIAS: { 52813ca95b02SDimitry Andric unsigned ValueID = Record[0]; 52823ca95b02SDimitry Andric uint64_t ModuleId = Record[1]; 52833ca95b02SDimitry Andric uint64_t RawFlags = Record[2]; 52843ca95b02SDimitry Andric unsigned AliaseeValueId = Record[3]; 52853ca95b02SDimitry Andric auto Flags = getDecodedGVSummaryFlags(RawFlags, Version); 52862cab237bSDimitry Andric auto AS = llvm::make_unique<AliasSummary>(Flags); 52873ca95b02SDimitry Andric LastSeenSummary = AS.get(); 52883ca95b02SDimitry Andric AS->setModulePath(ModuleIdMap[ModuleId]); 52893ca95b02SDimitry Andric 52900f5676f4SDimitry Andric auto AliaseeGUID = 52910f5676f4SDimitry Andric getValueInfoFromValueId(AliaseeValueId).first.getGUID(); 52923ca95b02SDimitry Andric auto AliaseeInModule = 5293d88c1a5aSDimitry Andric TheIndex.findSummaryInModule(AliaseeGUID, AS->modulePath()); 52943ca95b02SDimitry Andric AS->setAliasee(AliaseeInModule); 52952cab237bSDimitry Andric AS->setAliaseeGUID(AliaseeGUID); 52963ca95b02SDimitry Andric 52970f5676f4SDimitry Andric ValueInfo VI = getValueInfoFromValueId(ValueID).first; 52980f5676f4SDimitry Andric LastSeenGUID = VI.getGUID(); 52990f5676f4SDimitry Andric TheIndex.addGlobalValueSummary(VI, std::move(AS)); 53003ca95b02SDimitry Andric break; 53013ca95b02SDimitry Andric } 53023ca95b02SDimitry Andric // FS_COMBINED_GLOBALVAR_INIT_REFS: [valueid, modid, flags, n x valueid] 53033ca95b02SDimitry Andric case bitc::FS_COMBINED_GLOBALVAR_INIT_REFS: { 53043ca95b02SDimitry Andric unsigned ValueID = Record[0]; 53053ca95b02SDimitry Andric uint64_t ModuleId = Record[1]; 53063ca95b02SDimitry Andric uint64_t RawFlags = Record[2]; 53073ca95b02SDimitry Andric auto Flags = getDecodedGVSummaryFlags(RawFlags, Version); 5308d88c1a5aSDimitry Andric std::vector<ValueInfo> Refs = 5309d88c1a5aSDimitry Andric makeRefList(ArrayRef<uint64_t>(Record).slice(3)); 5310d88c1a5aSDimitry Andric auto FS = llvm::make_unique<GlobalVarSummary>(Flags, std::move(Refs)); 53113ca95b02SDimitry Andric LastSeenSummary = FS.get(); 53123ca95b02SDimitry Andric FS->setModulePath(ModuleIdMap[ModuleId]); 53130f5676f4SDimitry Andric ValueInfo VI = getValueInfoFromValueId(ValueID).first; 53140f5676f4SDimitry Andric LastSeenGUID = VI.getGUID(); 53150f5676f4SDimitry Andric TheIndex.addGlobalValueSummary(VI, std::move(FS)); 53163ca95b02SDimitry Andric break; 53173ca95b02SDimitry Andric } 53183ca95b02SDimitry Andric // FS_COMBINED_ORIGINAL_NAME: [original_name] 53193ca95b02SDimitry Andric case bitc::FS_COMBINED_ORIGINAL_NAME: { 53203ca95b02SDimitry Andric uint64_t OriginalName = Record[0]; 53213ca95b02SDimitry Andric if (!LastSeenSummary) 53223ca95b02SDimitry Andric return error("Name attachment that does not follow a combined record"); 53233ca95b02SDimitry Andric LastSeenSummary->setOriginalName(OriginalName); 53247a7e6055SDimitry Andric TheIndex.addOriginalName(LastSeenGUID, OriginalName); 53253ca95b02SDimitry Andric // Reset the LastSeenSummary 53263ca95b02SDimitry Andric LastSeenSummary = nullptr; 53277a7e6055SDimitry Andric LastSeenGUID = 0; 5328d88c1a5aSDimitry Andric break; 5329d88c1a5aSDimitry Andric } 53302cab237bSDimitry Andric case bitc::FS_TYPE_TESTS: 5331d88c1a5aSDimitry Andric assert(PendingTypeTests.empty()); 5332d88c1a5aSDimitry Andric PendingTypeTests.insert(PendingTypeTests.end(), Record.begin(), 5333d88c1a5aSDimitry Andric Record.end()); 5334d88c1a5aSDimitry Andric break; 53352cab237bSDimitry Andric 53362cab237bSDimitry Andric case bitc::FS_TYPE_TEST_ASSUME_VCALLS: 53377a7e6055SDimitry Andric assert(PendingTypeTestAssumeVCalls.empty()); 53387a7e6055SDimitry Andric for (unsigned I = 0; I != Record.size(); I += 2) 53397a7e6055SDimitry Andric PendingTypeTestAssumeVCalls.push_back({Record[I], Record[I+1]}); 53407a7e6055SDimitry Andric break; 53412cab237bSDimitry Andric 53422cab237bSDimitry Andric case bitc::FS_TYPE_CHECKED_LOAD_VCALLS: 53437a7e6055SDimitry Andric assert(PendingTypeCheckedLoadVCalls.empty()); 53447a7e6055SDimitry Andric for (unsigned I = 0; I != Record.size(); I += 2) 53457a7e6055SDimitry Andric PendingTypeCheckedLoadVCalls.push_back({Record[I], Record[I+1]}); 53467a7e6055SDimitry Andric break; 53472cab237bSDimitry Andric 53482cab237bSDimitry Andric case bitc::FS_TYPE_TEST_ASSUME_CONST_VCALL: 53497a7e6055SDimitry Andric PendingTypeTestAssumeConstVCalls.push_back( 53507a7e6055SDimitry Andric {{Record[0], Record[1]}, {Record.begin() + 2, Record.end()}}); 53517a7e6055SDimitry Andric break; 53522cab237bSDimitry Andric 53532cab237bSDimitry Andric case bitc::FS_TYPE_CHECKED_LOAD_CONST_VCALL: 53547a7e6055SDimitry Andric PendingTypeCheckedLoadConstVCalls.push_back( 53557a7e6055SDimitry Andric {{Record[0], Record[1]}, {Record.begin() + 2, Record.end()}}); 53567a7e6055SDimitry Andric break; 53572cab237bSDimitry Andric 535824d58133SDimitry Andric case bitc::FS_CFI_FUNCTION_DEFS: { 535924d58133SDimitry Andric std::set<std::string> &CfiFunctionDefs = TheIndex.cfiFunctionDefs(); 536024d58133SDimitry Andric for (unsigned I = 0; I != Record.size(); I += 2) 536124d58133SDimitry Andric CfiFunctionDefs.insert( 536224d58133SDimitry Andric {Strtab.data() + Record[I], static_cast<size_t>(Record[I + 1])}); 536324d58133SDimitry Andric break; 536424d58133SDimitry Andric } 536524d58133SDimitry Andric case bitc::FS_CFI_FUNCTION_DECLS: { 536624d58133SDimitry Andric std::set<std::string> &CfiFunctionDecls = TheIndex.cfiFunctionDecls(); 536724d58133SDimitry Andric for (unsigned I = 0; I != Record.size(); I += 2) 536824d58133SDimitry Andric CfiFunctionDecls.insert( 536924d58133SDimitry Andric {Strtab.data() + Record[I], static_cast<size_t>(Record[I + 1])}); 537024d58133SDimitry Andric break; 537124d58133SDimitry Andric } 53727d523365SDimitry Andric } 53737d523365SDimitry Andric } 53747d523365SDimitry Andric llvm_unreachable("Exit infinite loop"); 53757d523365SDimitry Andric } 53767d523365SDimitry Andric 53777d523365SDimitry Andric // Parse the module string table block into the Index. 53787d523365SDimitry Andric // This populates the ModulePathStringTable map in the index. 5379d88c1a5aSDimitry Andric Error ModuleSummaryIndexBitcodeReader::parseModuleStringTable() { 53807d523365SDimitry Andric if (Stream.EnterSubBlock(bitc::MODULE_STRTAB_BLOCK_ID)) 53817d523365SDimitry Andric return error("Invalid record"); 53827d523365SDimitry Andric 53837d523365SDimitry Andric SmallVector<uint64_t, 64> Record; 53847d523365SDimitry Andric 53857d523365SDimitry Andric SmallString<128> ModulePath; 538624d58133SDimitry Andric ModuleSummaryIndex::ModuleInfo *LastSeenModule = nullptr; 5387d88c1a5aSDimitry Andric 5388d88c1a5aSDimitry Andric while (true) { 53897d523365SDimitry Andric BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 53907d523365SDimitry Andric 53917d523365SDimitry Andric switch (Entry.Kind) { 53927d523365SDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already. 53937d523365SDimitry Andric case BitstreamEntry::Error: 53947d523365SDimitry Andric return error("Malformed block"); 53957d523365SDimitry Andric case BitstreamEntry::EndBlock: 5396d88c1a5aSDimitry Andric return Error::success(); 53977d523365SDimitry Andric case BitstreamEntry::Record: 53987d523365SDimitry Andric // The interesting case. 53997d523365SDimitry Andric break; 54007d523365SDimitry Andric } 54017d523365SDimitry Andric 54027d523365SDimitry Andric Record.clear(); 54037d523365SDimitry Andric switch (Stream.readRecord(Entry.ID, Record)) { 54047d523365SDimitry Andric default: // Default behavior: ignore. 54057d523365SDimitry Andric break; 54067d523365SDimitry Andric case bitc::MST_CODE_ENTRY: { 54077d523365SDimitry Andric // MST_ENTRY: [modid, namechar x N] 54083ca95b02SDimitry Andric uint64_t ModuleId = Record[0]; 54093ca95b02SDimitry Andric 54107d523365SDimitry Andric if (convertToString(Record, 1, ModulePath)) 54117d523365SDimitry Andric return error("Invalid record"); 54123ca95b02SDimitry Andric 541324d58133SDimitry Andric LastSeenModule = TheIndex.addModule(ModulePath, ModuleId); 541424d58133SDimitry Andric ModuleIdMap[ModuleId] = LastSeenModule->first(); 54153ca95b02SDimitry Andric 54167d523365SDimitry Andric ModulePath.clear(); 54177d523365SDimitry Andric break; 54187d523365SDimitry Andric } 54193ca95b02SDimitry Andric /// MST_CODE_HASH: [5*i32] 54203ca95b02SDimitry Andric case bitc::MST_CODE_HASH: { 54213ca95b02SDimitry Andric if (Record.size() != 5) 54223ca95b02SDimitry Andric return error("Invalid hash length " + Twine(Record.size()).str()); 542324d58133SDimitry Andric if (!LastSeenModule) 54243ca95b02SDimitry Andric return error("Invalid hash that does not follow a module path"); 54253ca95b02SDimitry Andric int Pos = 0; 54263ca95b02SDimitry Andric for (auto &Val : Record) { 54273ca95b02SDimitry Andric assert(!(Val >> 32) && "Unexpected high bits set"); 542824d58133SDimitry Andric LastSeenModule->second.second[Pos++] = Val; 54293ca95b02SDimitry Andric } 543024d58133SDimitry Andric // Reset LastSeenModule to avoid overriding the hash unexpectedly. 543124d58133SDimitry Andric LastSeenModule = nullptr; 54323ca95b02SDimitry Andric break; 54333ca95b02SDimitry Andric } 54347d523365SDimitry Andric } 54357d523365SDimitry Andric } 54367d523365SDimitry Andric llvm_unreachable("Exit infinite loop"); 54377d523365SDimitry Andric } 54387d523365SDimitry Andric 5439f785676fSDimitry Andric namespace { 5440d88c1a5aSDimitry Andric 54413ca95b02SDimitry Andric // FIXME: This class is only here to support the transition to llvm::Error. It 54423ca95b02SDimitry Andric // will be removed once this transition is complete. Clients should prefer to 54433ca95b02SDimitry Andric // deal with the Error value directly, rather than converting to error_code. 544491bc56edSDimitry Andric class BitcodeErrorCategoryType : public std::error_category { 5445d88c1a5aSDimitry Andric const char *name() const noexcept override { 5446f785676fSDimitry Andric return "llvm.bitcode"; 5447f785676fSDimitry Andric } 54482cab237bSDimitry Andric 544991bc56edSDimitry Andric std::string message(int IE) const override { 545039d628a0SDimitry Andric BitcodeError E = static_cast<BitcodeError>(IE); 5451f785676fSDimitry Andric switch (E) { 545239d628a0SDimitry Andric case BitcodeError::CorruptedBitcode: 545339d628a0SDimitry Andric return "Corrupted bitcode"; 5454f785676fSDimitry Andric } 5455f785676fSDimitry Andric llvm_unreachable("Unknown error type!"); 5456f785676fSDimitry Andric } 5457f785676fSDimitry Andric }; 5458d88c1a5aSDimitry Andric 54593ca95b02SDimitry Andric } // end anonymous namespace 5460f785676fSDimitry Andric 546139d628a0SDimitry Andric static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory; 546239d628a0SDimitry Andric 546339d628a0SDimitry Andric const std::error_category &llvm::BitcodeErrorCategory() { 546439d628a0SDimitry Andric return *ErrorCategory; 5465dff0c46cSDimitry Andric } 5466f22ef01cSRoman Divacky 5467a580b014SDimitry Andric static Expected<StringRef> readBlobInRecord(BitstreamCursor &Stream, 5468a580b014SDimitry Andric unsigned Block, unsigned RecordID) { 5469a580b014SDimitry Andric if (Stream.EnterSubBlock(Block)) 54706bc11b14SDimitry Andric return error("Invalid record"); 54716bc11b14SDimitry Andric 54726bc11b14SDimitry Andric StringRef Strtab; 54732cab237bSDimitry Andric while (true) { 54746bc11b14SDimitry Andric BitstreamEntry Entry = Stream.advance(); 54756bc11b14SDimitry Andric switch (Entry.Kind) { 54766bc11b14SDimitry Andric case BitstreamEntry::EndBlock: 54776bc11b14SDimitry Andric return Strtab; 54786bc11b14SDimitry Andric 54796bc11b14SDimitry Andric case BitstreamEntry::Error: 54806bc11b14SDimitry Andric return error("Malformed block"); 54816bc11b14SDimitry Andric 54826bc11b14SDimitry Andric case BitstreamEntry::SubBlock: 54836bc11b14SDimitry Andric if (Stream.SkipBlock()) 54846bc11b14SDimitry Andric return error("Malformed block"); 54856bc11b14SDimitry Andric break; 54866bc11b14SDimitry Andric 54876bc11b14SDimitry Andric case BitstreamEntry::Record: 54886bc11b14SDimitry Andric StringRef Blob; 54896bc11b14SDimitry Andric SmallVector<uint64_t, 1> Record; 5490a580b014SDimitry Andric if (Stream.readRecord(Entry.ID, Record, &Blob) == RecordID) 54916bc11b14SDimitry Andric Strtab = Blob; 54926bc11b14SDimitry Andric break; 54936bc11b14SDimitry Andric } 54946bc11b14SDimitry Andric } 54956bc11b14SDimitry Andric } 54966bc11b14SDimitry Andric 5497f22ef01cSRoman Divacky //===----------------------------------------------------------------------===// 5498f22ef01cSRoman Divacky // External interface 5499f22ef01cSRoman Divacky //===----------------------------------------------------------------------===// 5500f22ef01cSRoman Divacky 5501d88c1a5aSDimitry Andric Expected<std::vector<BitcodeModule>> 5502d88c1a5aSDimitry Andric llvm::getBitcodeModuleList(MemoryBufferRef Buffer) { 5503db17bf38SDimitry Andric auto FOrErr = getBitcodeFileContents(Buffer); 5504db17bf38SDimitry Andric if (!FOrErr) 5505db17bf38SDimitry Andric return FOrErr.takeError(); 5506db17bf38SDimitry Andric return std::move(FOrErr->Mods); 5507db17bf38SDimitry Andric } 5508db17bf38SDimitry Andric 5509db17bf38SDimitry Andric Expected<BitcodeFileContents> 5510db17bf38SDimitry Andric llvm::getBitcodeFileContents(MemoryBufferRef Buffer) { 5511d88c1a5aSDimitry Andric Expected<BitstreamCursor> StreamOrErr = initStream(Buffer); 5512d88c1a5aSDimitry Andric if (!StreamOrErr) 5513d88c1a5aSDimitry Andric return StreamOrErr.takeError(); 5514d88c1a5aSDimitry Andric BitstreamCursor &Stream = *StreamOrErr; 55158f0fd8f6SDimitry Andric 5516db17bf38SDimitry Andric BitcodeFileContents F; 5517d88c1a5aSDimitry Andric while (true) { 5518d88c1a5aSDimitry Andric uint64_t BCBegin = Stream.getCurrentByteNo(); 55198f0fd8f6SDimitry Andric 5520d88c1a5aSDimitry Andric // We may be consuming bitcode from a client that leaves garbage at the end 5521d88c1a5aSDimitry Andric // of the bitcode stream (e.g. Apple's ar tool). If we are close enough to 5522d88c1a5aSDimitry Andric // the end that there cannot possibly be another module, stop looking. 5523d88c1a5aSDimitry Andric if (BCBegin + 8 >= Stream.getBitcodeBytes().size()) 5524db17bf38SDimitry Andric return F; 55258f0fd8f6SDimitry Andric 5526d88c1a5aSDimitry Andric BitstreamEntry Entry = Stream.advance(); 5527d88c1a5aSDimitry Andric switch (Entry.Kind) { 5528d88c1a5aSDimitry Andric case BitstreamEntry::EndBlock: 5529d88c1a5aSDimitry Andric case BitstreamEntry::Error: 5530d88c1a5aSDimitry Andric return error("Malformed block"); 5531d88c1a5aSDimitry Andric 5532d88c1a5aSDimitry Andric case BitstreamEntry::SubBlock: { 5533d88c1a5aSDimitry Andric uint64_t IdentificationBit = -1ull; 5534d88c1a5aSDimitry Andric if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) { 5535d88c1a5aSDimitry Andric IdentificationBit = Stream.GetCurrentBitNo() - BCBegin * 8; 5536d88c1a5aSDimitry Andric if (Stream.SkipBlock()) 5537d88c1a5aSDimitry Andric return error("Malformed block"); 5538d88c1a5aSDimitry Andric 5539d88c1a5aSDimitry Andric Entry = Stream.advance(); 5540d88c1a5aSDimitry Andric if (Entry.Kind != BitstreamEntry::SubBlock || 5541d88c1a5aSDimitry Andric Entry.ID != bitc::MODULE_BLOCK_ID) 5542d88c1a5aSDimitry Andric return error("Malformed block"); 55438f0fd8f6SDimitry Andric } 5544d88c1a5aSDimitry Andric 5545d88c1a5aSDimitry Andric if (Entry.ID == bitc::MODULE_BLOCK_ID) { 5546d88c1a5aSDimitry Andric uint64_t ModuleBit = Stream.GetCurrentBitNo() - BCBegin * 8; 5547d88c1a5aSDimitry Andric if (Stream.SkipBlock()) 5548d88c1a5aSDimitry Andric return error("Malformed block"); 5549d88c1a5aSDimitry Andric 5550db17bf38SDimitry Andric F.Mods.push_back({Stream.getBitcodeBytes().slice( 5551d88c1a5aSDimitry Andric BCBegin, Stream.getCurrentByteNo() - BCBegin), 5552d88c1a5aSDimitry Andric Buffer.getBufferIdentifier(), IdentificationBit, 5553d88c1a5aSDimitry Andric ModuleBit}); 5554d88c1a5aSDimitry Andric continue; 5555d88c1a5aSDimitry Andric } 5556d88c1a5aSDimitry Andric 55576bc11b14SDimitry Andric if (Entry.ID == bitc::STRTAB_BLOCK_ID) { 5558a580b014SDimitry Andric Expected<StringRef> Strtab = 5559a580b014SDimitry Andric readBlobInRecord(Stream, bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB); 55606bc11b14SDimitry Andric if (!Strtab) 55616bc11b14SDimitry Andric return Strtab.takeError(); 55626bc11b14SDimitry Andric // This string table is used by every preceding bitcode module that does 55636bc11b14SDimitry Andric // not have its own string table. A bitcode file may have multiple 55646bc11b14SDimitry Andric // string tables if it was created by binary concatenation, for example 55656bc11b14SDimitry Andric // with "llvm-cat -b". 5566db17bf38SDimitry Andric for (auto I = F.Mods.rbegin(), E = F.Mods.rend(); I != E; ++I) { 55676bc11b14SDimitry Andric if (!I->Strtab.empty()) 55686bc11b14SDimitry Andric break; 55696bc11b14SDimitry Andric I->Strtab = *Strtab; 55706bc11b14SDimitry Andric } 5571a580b014SDimitry Andric // Similarly, the string table is used by every preceding symbol table; 5572a580b014SDimitry Andric // normally there will be just one unless the bitcode file was created 5573a580b014SDimitry Andric // by binary concatenation. 5574a580b014SDimitry Andric if (!F.Symtab.empty() && F.StrtabForSymtab.empty()) 5575a580b014SDimitry Andric F.StrtabForSymtab = *Strtab; 5576a580b014SDimitry Andric continue; 5577a580b014SDimitry Andric } 5578a580b014SDimitry Andric 5579a580b014SDimitry Andric if (Entry.ID == bitc::SYMTAB_BLOCK_ID) { 5580a580b014SDimitry Andric Expected<StringRef> SymtabOrErr = 5581a580b014SDimitry Andric readBlobInRecord(Stream, bitc::SYMTAB_BLOCK_ID, bitc::SYMTAB_BLOB); 5582a580b014SDimitry Andric if (!SymtabOrErr) 5583a580b014SDimitry Andric return SymtabOrErr.takeError(); 5584a580b014SDimitry Andric 5585a580b014SDimitry Andric // We can expect the bitcode file to have multiple symbol tables if it 5586a580b014SDimitry Andric // was created by binary concatenation. In that case we silently 5587a580b014SDimitry Andric // ignore any subsequent symbol tables, which is fine because this is a 5588a580b014SDimitry Andric // low level function. The client is expected to notice that the number 5589a580b014SDimitry Andric // of modules in the symbol table does not match the number of modules 5590a580b014SDimitry Andric // in the input file and regenerate the symbol table. 5591a580b014SDimitry Andric if (F.Symtab.empty()) 5592a580b014SDimitry Andric F.Symtab = *SymtabOrErr; 55936bc11b14SDimitry Andric continue; 55946bc11b14SDimitry Andric } 55956bc11b14SDimitry Andric 5596d88c1a5aSDimitry Andric if (Stream.SkipBlock()) 5597d88c1a5aSDimitry Andric return error("Malformed block"); 5598d88c1a5aSDimitry Andric continue; 5599d88c1a5aSDimitry Andric } 5600d88c1a5aSDimitry Andric case BitstreamEntry::Record: 5601d88c1a5aSDimitry Andric Stream.skipRecord(Entry.ID); 5602d88c1a5aSDimitry Andric continue; 5603d88c1a5aSDimitry Andric } 5604d88c1a5aSDimitry Andric } 56058f0fd8f6SDimitry Andric } 56068f0fd8f6SDimitry Andric 560739d628a0SDimitry Andric /// \brief Get a lazy one-at-time loading module from bitcode. 5608f22ef01cSRoman Divacky /// 560939d628a0SDimitry Andric /// This isn't always used in a lazy context. In particular, it's also used by 5610d88c1a5aSDimitry Andric /// \a parseModule(). If this is truly lazy, then we need to eagerly pull 561139d628a0SDimitry Andric /// in forward-referenced functions from block address references. 561239d628a0SDimitry Andric /// 56138f0fd8f6SDimitry Andric /// \param[in] MaterializeAll Set to \c true if we should materialize 56148f0fd8f6SDimitry Andric /// everything. 5615d88c1a5aSDimitry Andric Expected<std::unique_ptr<Module>> 5616d88c1a5aSDimitry Andric BitcodeModule::getModuleImpl(LLVMContext &Context, bool MaterializeAll, 5617d88c1a5aSDimitry Andric bool ShouldLazyLoadMetadata, bool IsImporting) { 5618d88c1a5aSDimitry Andric BitstreamCursor Stream(Buffer); 561939d628a0SDimitry Andric 5620d88c1a5aSDimitry Andric std::string ProducerIdentification; 5621d88c1a5aSDimitry Andric if (IdentificationBit != -1ull) { 5622d88c1a5aSDimitry Andric Stream.JumpToBit(IdentificationBit); 5623d88c1a5aSDimitry Andric Expected<std::string> ProducerIdentificationOrErr = 5624d88c1a5aSDimitry Andric readIdentificationBlock(Stream); 5625d88c1a5aSDimitry Andric if (!ProducerIdentificationOrErr) 5626d88c1a5aSDimitry Andric return ProducerIdentificationOrErr.takeError(); 562739d628a0SDimitry Andric 5628d88c1a5aSDimitry Andric ProducerIdentification = *ProducerIdentificationOrErr; 5629dff0c46cSDimitry Andric } 5630dff0c46cSDimitry Andric 5631d88c1a5aSDimitry Andric Stream.JumpToBit(ModuleBit); 56326bc11b14SDimitry Andric auto *R = new BitcodeReader(std::move(Stream), Strtab, ProducerIdentification, 56336bc11b14SDimitry Andric Context); 5634d88c1a5aSDimitry Andric 5635d88c1a5aSDimitry Andric std::unique_ptr<Module> M = 5636d88c1a5aSDimitry Andric llvm::make_unique<Module>(ModuleIdentifier, Context); 5637d88c1a5aSDimitry Andric M->setMaterializer(R); 5638d88c1a5aSDimitry Andric 5639d88c1a5aSDimitry Andric // Delay parsing Metadata if ShouldLazyLoadMetadata is true. 5640d88c1a5aSDimitry Andric if (Error Err = 5641d88c1a5aSDimitry Andric R->parseBitcodeInto(M.get(), ShouldLazyLoadMetadata, IsImporting)) 5642d88c1a5aSDimitry Andric return std::move(Err); 5643d88c1a5aSDimitry Andric 5644d88c1a5aSDimitry Andric if (MaterializeAll) { 5645d88c1a5aSDimitry Andric // Read in the entire module, and destroy the BitcodeReader. 5646d88c1a5aSDimitry Andric if (Error Err = M->materializeAll()) 5647d88c1a5aSDimitry Andric return std::move(Err); 5648d88c1a5aSDimitry Andric } else { 5649d88c1a5aSDimitry Andric // Resolve forward references from blockaddresses. 5650d88c1a5aSDimitry Andric if (Error Err = R->materializeForwardReferencedFunctions()) 5651d88c1a5aSDimitry Andric return std::move(Err); 5652d88c1a5aSDimitry Andric } 5653d88c1a5aSDimitry Andric return std::move(M); 5654f22ef01cSRoman Divacky } 5655f22ef01cSRoman Divacky 5656d88c1a5aSDimitry Andric Expected<std::unique_ptr<Module>> 5657d88c1a5aSDimitry Andric BitcodeModule::getLazyModule(LLVMContext &Context, bool ShouldLazyLoadMetadata, 5658d88c1a5aSDimitry Andric bool IsImporting) { 5659d88c1a5aSDimitry Andric return getModuleImpl(Context, false, ShouldLazyLoadMetadata, IsImporting); 56607d523365SDimitry Andric } 56617d523365SDimitry Andric 5662f37b6182SDimitry Andric // Parse the specified bitcode buffer and merge the index into CombinedIndex. 566324d58133SDimitry Andric // We don't use ModuleIdentifier here because the client may need to control the 566424d58133SDimitry Andric // module path used in the combined summary (e.g. when reading summaries for 566524d58133SDimitry Andric // regular LTO modules). 5666f37b6182SDimitry Andric Error BitcodeModule::readSummary(ModuleSummaryIndex &CombinedIndex, 566724d58133SDimitry Andric StringRef ModulePath, uint64_t ModuleId) { 5668f37b6182SDimitry Andric BitstreamCursor Stream(Buffer); 5669f37b6182SDimitry Andric Stream.JumpToBit(ModuleBit); 5670f37b6182SDimitry Andric 5671f37b6182SDimitry Andric ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, CombinedIndex, 567224d58133SDimitry Andric ModulePath, ModuleId); 5673f37b6182SDimitry Andric return R.parseModule(); 5674f37b6182SDimitry Andric } 5675f37b6182SDimitry Andric 56767d523365SDimitry Andric // Parse the specified bitcode buffer, returning the function info index. 5677d88c1a5aSDimitry Andric Expected<std::unique_ptr<ModuleSummaryIndex>> BitcodeModule::getSummary() { 5678d88c1a5aSDimitry Andric BitstreamCursor Stream(Buffer); 5679d88c1a5aSDimitry Andric Stream.JumpToBit(ModuleBit); 56807d523365SDimitry Andric 56813ca95b02SDimitry Andric auto Index = llvm::make_unique<ModuleSummaryIndex>(); 5682f37b6182SDimitry Andric ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, *Index, 5683f37b6182SDimitry Andric ModuleIdentifier, 0); 56847d523365SDimitry Andric 5685f37b6182SDimitry Andric if (Error Err = R.parseModule()) 5686d88c1a5aSDimitry Andric return std::move(Err); 56877d523365SDimitry Andric 56887d523365SDimitry Andric return std::move(Index); 56897d523365SDimitry Andric } 56907d523365SDimitry Andric 56913ca95b02SDimitry Andric // Check if the given bitcode buffer contains a global value summary block. 569224d58133SDimitry Andric Expected<BitcodeLTOInfo> BitcodeModule::getLTOInfo() { 5693d88c1a5aSDimitry Andric BitstreamCursor Stream(Buffer); 5694d88c1a5aSDimitry Andric Stream.JumpToBit(ModuleBit); 56957d523365SDimitry Andric 5696d88c1a5aSDimitry Andric if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID)) 5697d88c1a5aSDimitry Andric return error("Invalid record"); 5698d88c1a5aSDimitry Andric 5699d88c1a5aSDimitry Andric while (true) { 5700d88c1a5aSDimitry Andric BitstreamEntry Entry = Stream.advance(); 5701d88c1a5aSDimitry Andric 5702d88c1a5aSDimitry Andric switch (Entry.Kind) { 5703d88c1a5aSDimitry Andric case BitstreamEntry::Error: 5704d88c1a5aSDimitry Andric return error("Malformed block"); 5705d88c1a5aSDimitry Andric case BitstreamEntry::EndBlock: 570624d58133SDimitry Andric return BitcodeLTOInfo{/*IsThinLTO=*/false, /*HasSummary=*/false}; 57077d523365SDimitry Andric 5708d88c1a5aSDimitry Andric case BitstreamEntry::SubBlock: 5709d88c1a5aSDimitry Andric if (Entry.ID == bitc::GLOBALVAL_SUMMARY_BLOCK_ID) 571024d58133SDimitry Andric return BitcodeLTOInfo{/*IsThinLTO=*/true, /*HasSummary=*/true}; 571124d58133SDimitry Andric 571224d58133SDimitry Andric if (Entry.ID == bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID) 571324d58133SDimitry Andric return BitcodeLTOInfo{/*IsThinLTO=*/false, /*HasSummary=*/true}; 57147d523365SDimitry Andric 5715d88c1a5aSDimitry Andric // Ignore other sub-blocks. 5716d88c1a5aSDimitry Andric if (Stream.SkipBlock()) 5717d88c1a5aSDimitry Andric return error("Malformed block"); 5718d88c1a5aSDimitry Andric continue; 5719d88c1a5aSDimitry Andric 5720d88c1a5aSDimitry Andric case BitstreamEntry::Record: 5721d88c1a5aSDimitry Andric Stream.skipRecord(Entry.ID); 5722d88c1a5aSDimitry Andric continue; 5723d88c1a5aSDimitry Andric } 5724d88c1a5aSDimitry Andric } 5725d88c1a5aSDimitry Andric } 5726d88c1a5aSDimitry Andric 5727d88c1a5aSDimitry Andric static Expected<BitcodeModule> getSingleModule(MemoryBufferRef Buffer) { 5728d88c1a5aSDimitry Andric Expected<std::vector<BitcodeModule>> MsOrErr = getBitcodeModuleList(Buffer); 5729d88c1a5aSDimitry Andric if (!MsOrErr) 5730d88c1a5aSDimitry Andric return MsOrErr.takeError(); 5731d88c1a5aSDimitry Andric 5732d88c1a5aSDimitry Andric if (MsOrErr->size() != 1) 5733d88c1a5aSDimitry Andric return error("Expected a single module"); 5734d88c1a5aSDimitry Andric 5735d88c1a5aSDimitry Andric return (*MsOrErr)[0]; 5736d88c1a5aSDimitry Andric } 5737d88c1a5aSDimitry Andric 5738d88c1a5aSDimitry Andric Expected<std::unique_ptr<Module>> 5739d88c1a5aSDimitry Andric llvm::getLazyBitcodeModule(MemoryBufferRef Buffer, LLVMContext &Context, 5740d88c1a5aSDimitry Andric bool ShouldLazyLoadMetadata, bool IsImporting) { 5741d88c1a5aSDimitry Andric Expected<BitcodeModule> BM = getSingleModule(Buffer); 5742d88c1a5aSDimitry Andric if (!BM) 5743d88c1a5aSDimitry Andric return BM.takeError(); 5744d88c1a5aSDimitry Andric 5745d88c1a5aSDimitry Andric return BM->getLazyModule(Context, ShouldLazyLoadMetadata, IsImporting); 5746d88c1a5aSDimitry Andric } 5747d88c1a5aSDimitry Andric 5748d88c1a5aSDimitry Andric Expected<std::unique_ptr<Module>> llvm::getOwningLazyBitcodeModule( 5749d88c1a5aSDimitry Andric std::unique_ptr<MemoryBuffer> &&Buffer, LLVMContext &Context, 5750d88c1a5aSDimitry Andric bool ShouldLazyLoadMetadata, bool IsImporting) { 5751d88c1a5aSDimitry Andric auto MOrErr = getLazyBitcodeModule(*Buffer, Context, ShouldLazyLoadMetadata, 5752d88c1a5aSDimitry Andric IsImporting); 5753d88c1a5aSDimitry Andric if (MOrErr) 5754d88c1a5aSDimitry Andric (*MOrErr)->setOwnedMemoryBuffer(std::move(Buffer)); 5755d88c1a5aSDimitry Andric return MOrErr; 5756d88c1a5aSDimitry Andric } 5757d88c1a5aSDimitry Andric 5758d88c1a5aSDimitry Andric Expected<std::unique_ptr<Module>> 5759d88c1a5aSDimitry Andric BitcodeModule::parseModule(LLVMContext &Context) { 5760d88c1a5aSDimitry Andric return getModuleImpl(Context, true, false, false); 5761d88c1a5aSDimitry Andric // TODO: Restore the use-lists to the in-memory state when the bitcode was 5762d88c1a5aSDimitry Andric // written. We must defer until the Module has been fully materialized. 5763d88c1a5aSDimitry Andric } 5764d88c1a5aSDimitry Andric 5765d88c1a5aSDimitry Andric Expected<std::unique_ptr<Module>> llvm::parseBitcodeFile(MemoryBufferRef Buffer, 5766d88c1a5aSDimitry Andric LLVMContext &Context) { 5767d88c1a5aSDimitry Andric Expected<BitcodeModule> BM = getSingleModule(Buffer); 5768d88c1a5aSDimitry Andric if (!BM) 5769d88c1a5aSDimitry Andric return BM.takeError(); 5770d88c1a5aSDimitry Andric 5771d88c1a5aSDimitry Andric return BM->parseModule(Context); 5772d88c1a5aSDimitry Andric } 5773d88c1a5aSDimitry Andric 5774d88c1a5aSDimitry Andric Expected<std::string> llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer) { 5775d88c1a5aSDimitry Andric Expected<BitstreamCursor> StreamOrErr = initStream(Buffer); 5776d88c1a5aSDimitry Andric if (!StreamOrErr) 5777d88c1a5aSDimitry Andric return StreamOrErr.takeError(); 5778d88c1a5aSDimitry Andric 5779d88c1a5aSDimitry Andric return readTriple(*StreamOrErr); 5780d88c1a5aSDimitry Andric } 5781d88c1a5aSDimitry Andric 5782d88c1a5aSDimitry Andric Expected<bool> llvm::isBitcodeContainingObjCCategory(MemoryBufferRef Buffer) { 5783d88c1a5aSDimitry Andric Expected<BitstreamCursor> StreamOrErr = initStream(Buffer); 5784d88c1a5aSDimitry Andric if (!StreamOrErr) 5785d88c1a5aSDimitry Andric return StreamOrErr.takeError(); 5786d88c1a5aSDimitry Andric 5787d88c1a5aSDimitry Andric return hasObjCCategory(*StreamOrErr); 5788d88c1a5aSDimitry Andric } 5789d88c1a5aSDimitry Andric 5790d88c1a5aSDimitry Andric Expected<std::string> llvm::getBitcodeProducerString(MemoryBufferRef Buffer) { 5791d88c1a5aSDimitry Andric Expected<BitstreamCursor> StreamOrErr = initStream(Buffer); 5792d88c1a5aSDimitry Andric if (!StreamOrErr) 5793d88c1a5aSDimitry Andric return StreamOrErr.takeError(); 5794d88c1a5aSDimitry Andric 5795d88c1a5aSDimitry Andric return readIdentificationCode(*StreamOrErr); 5796d88c1a5aSDimitry Andric } 5797d88c1a5aSDimitry Andric 5798f37b6182SDimitry Andric Error llvm::readModuleSummaryIndex(MemoryBufferRef Buffer, 5799f37b6182SDimitry Andric ModuleSummaryIndex &CombinedIndex, 580024d58133SDimitry Andric uint64_t ModuleId) { 5801f37b6182SDimitry Andric Expected<BitcodeModule> BM = getSingleModule(Buffer); 5802f37b6182SDimitry Andric if (!BM) 5803f37b6182SDimitry Andric return BM.takeError(); 5804f37b6182SDimitry Andric 580524d58133SDimitry Andric return BM->readSummary(CombinedIndex, BM->getModuleIdentifier(), ModuleId); 5806f37b6182SDimitry Andric } 5807f37b6182SDimitry Andric 5808d88c1a5aSDimitry Andric Expected<std::unique_ptr<ModuleSummaryIndex>> 5809d88c1a5aSDimitry Andric llvm::getModuleSummaryIndex(MemoryBufferRef Buffer) { 5810d88c1a5aSDimitry Andric Expected<BitcodeModule> BM = getSingleModule(Buffer); 5811d88c1a5aSDimitry Andric if (!BM) 5812d88c1a5aSDimitry Andric return BM.takeError(); 5813d88c1a5aSDimitry Andric 5814d88c1a5aSDimitry Andric return BM->getSummary(); 5815d88c1a5aSDimitry Andric } 5816d88c1a5aSDimitry Andric 581724d58133SDimitry Andric Expected<BitcodeLTOInfo> llvm::getBitcodeLTOInfo(MemoryBufferRef Buffer) { 5818d88c1a5aSDimitry Andric Expected<BitcodeModule> BM = getSingleModule(Buffer); 5819d88c1a5aSDimitry Andric if (!BM) 5820d88c1a5aSDimitry Andric return BM.takeError(); 5821d88c1a5aSDimitry Andric 582224d58133SDimitry Andric return BM->getLTOInfo(); 58237d523365SDimitry Andric } 5824f37b6182SDimitry Andric 5825f37b6182SDimitry Andric Expected<std::unique_ptr<ModuleSummaryIndex>> 58265517e702SDimitry Andric llvm::getModuleSummaryIndexForFile(StringRef Path, 58275517e702SDimitry Andric bool IgnoreEmptyThinLTOIndexFile) { 5828f37b6182SDimitry Andric ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr = 5829f37b6182SDimitry Andric MemoryBuffer::getFileOrSTDIN(Path); 5830f37b6182SDimitry Andric if (!FileOrErr) 5831f37b6182SDimitry Andric return errorCodeToError(FileOrErr.getError()); 5832f37b6182SDimitry Andric if (IgnoreEmptyThinLTOIndexFile && !(*FileOrErr)->getBufferSize()) 5833f37b6182SDimitry Andric return nullptr; 5834f37b6182SDimitry Andric return getModuleSummaryIndex(**FileOrErr); 5835f37b6182SDimitry Andric } 5836