1 //===- BitcodeReader.cpp - Internal BitcodeReader implementation ----------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 9 #include "llvm/Bitcode/BitcodeReader.h" 10 #include "MetadataLoader.h" 11 #include "ValueList.h" 12 #include "llvm/ADT/APFloat.h" 13 #include "llvm/ADT/APInt.h" 14 #include "llvm/ADT/ArrayRef.h" 15 #include "llvm/ADT/DenseMap.h" 16 #include "llvm/ADT/STLExtras.h" 17 #include "llvm/ADT/SmallString.h" 18 #include "llvm/ADT/SmallVector.h" 19 #include "llvm/ADT/StringRef.h" 20 #include "llvm/ADT/Twine.h" 21 #include "llvm/Bitcode/BitcodeCommon.h" 22 #include "llvm/Bitcode/LLVMBitCodes.h" 23 #include "llvm/Bitstream/BitstreamReader.h" 24 #include "llvm/Config/llvm-config.h" 25 #include "llvm/IR/Argument.h" 26 #include "llvm/IR/AttributeMask.h" 27 #include "llvm/IR/Attributes.h" 28 #include "llvm/IR/AutoUpgrade.h" 29 #include "llvm/IR/BasicBlock.h" 30 #include "llvm/IR/CallingConv.h" 31 #include "llvm/IR/Comdat.h" 32 #include "llvm/IR/Constant.h" 33 #include "llvm/IR/Constants.h" 34 #include "llvm/IR/DataLayout.h" 35 #include "llvm/IR/DebugInfo.h" 36 #include "llvm/IR/DebugInfoMetadata.h" 37 #include "llvm/IR/DebugLoc.h" 38 #include "llvm/IR/DerivedTypes.h" 39 #include "llvm/IR/Function.h" 40 #include "llvm/IR/GVMaterializer.h" 41 #include "llvm/IR/GetElementPtrTypeIterator.h" 42 #include "llvm/IR/GlobalAlias.h" 43 #include "llvm/IR/GlobalIFunc.h" 44 #include "llvm/IR/GlobalObject.h" 45 #include "llvm/IR/GlobalValue.h" 46 #include "llvm/IR/GlobalVariable.h" 47 #include "llvm/IR/InlineAsm.h" 48 #include "llvm/IR/InstIterator.h" 49 #include "llvm/IR/InstrTypes.h" 50 #include "llvm/IR/Instruction.h" 51 #include "llvm/IR/Instructions.h" 52 #include "llvm/IR/Intrinsics.h" 53 #include "llvm/IR/IntrinsicsAArch64.h" 54 #include "llvm/IR/IntrinsicsARM.h" 55 #include "llvm/IR/LLVMContext.h" 56 #include "llvm/IR/Metadata.h" 57 #include "llvm/IR/Module.h" 58 #include "llvm/IR/ModuleSummaryIndex.h" 59 #include "llvm/IR/Operator.h" 60 #include "llvm/IR/Type.h" 61 #include "llvm/IR/Value.h" 62 #include "llvm/IR/Verifier.h" 63 #include "llvm/Support/AtomicOrdering.h" 64 #include "llvm/Support/Casting.h" 65 #include "llvm/Support/CommandLine.h" 66 #include "llvm/Support/Compiler.h" 67 #include "llvm/Support/Debug.h" 68 #include "llvm/Support/Error.h" 69 #include "llvm/Support/ErrorHandling.h" 70 #include "llvm/Support/ErrorOr.h" 71 #include "llvm/Support/MathExtras.h" 72 #include "llvm/Support/MemoryBuffer.h" 73 #include "llvm/Support/ModRef.h" 74 #include "llvm/Support/raw_ostream.h" 75 #include "llvm/TargetParser/Triple.h" 76 #include <algorithm> 77 #include <cassert> 78 #include <cstddef> 79 #include <cstdint> 80 #include <deque> 81 #include <map> 82 #include <memory> 83 #include <optional> 84 #include <set> 85 #include <string> 86 #include <system_error> 87 #include <tuple> 88 #include <utility> 89 #include <vector> 90 91 using namespace llvm; 92 93 static cl::opt<bool> PrintSummaryGUIDs( 94 "print-summary-global-ids", cl::init(false), cl::Hidden, 95 cl::desc( 96 "Print the global id for each value when reading the module summary")); 97 98 static cl::opt<bool> ExpandConstantExprs( 99 "expand-constant-exprs", cl::Hidden, 100 cl::desc( 101 "Expand constant expressions to instructions for testing purposes")); 102 103 namespace { 104 105 enum { 106 SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex 107 }; 108 109 } // end anonymous namespace 110 111 static Error error(const Twine &Message) { 112 return make_error<StringError>( 113 Message, make_error_code(BitcodeError::CorruptedBitcode)); 114 } 115 116 static Error hasInvalidBitcodeHeader(BitstreamCursor &Stream) { 117 if (!Stream.canSkipToPos(4)) 118 return createStringError(std::errc::illegal_byte_sequence, 119 "file too small to contain bitcode header"); 120 for (unsigned C : {'B', 'C'}) 121 if (Expected<SimpleBitstreamCursor::word_t> Res = Stream.Read(8)) { 122 if (Res.get() != C) 123 return createStringError(std::errc::illegal_byte_sequence, 124 "file doesn't start with bitcode header"); 125 } else 126 return Res.takeError(); 127 for (unsigned C : {0x0, 0xC, 0xE, 0xD}) 128 if (Expected<SimpleBitstreamCursor::word_t> Res = Stream.Read(4)) { 129 if (Res.get() != C) 130 return createStringError(std::errc::illegal_byte_sequence, 131 "file doesn't start with bitcode header"); 132 } else 133 return Res.takeError(); 134 return Error::success(); 135 } 136 137 static Expected<BitstreamCursor> initStream(MemoryBufferRef Buffer) { 138 const unsigned char *BufPtr = (const unsigned char *)Buffer.getBufferStart(); 139 const unsigned char *BufEnd = BufPtr + Buffer.getBufferSize(); 140 141 if (Buffer.getBufferSize() & 3) 142 return error("Invalid bitcode signature"); 143 144 // If we have a wrapper header, parse it and ignore the non-bc file contents. 145 // The magic number is 0x0B17C0DE stored in little endian. 146 if (isBitcodeWrapper(BufPtr, BufEnd)) 147 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true)) 148 return error("Invalid bitcode wrapper header"); 149 150 BitstreamCursor Stream(ArrayRef<uint8_t>(BufPtr, BufEnd)); 151 if (Error Err = hasInvalidBitcodeHeader(Stream)) 152 return std::move(Err); 153 154 return std::move(Stream); 155 } 156 157 /// Convert a string from a record into an std::string, return true on failure. 158 template <typename StrTy> 159 static bool convertToString(ArrayRef<uint64_t> Record, unsigned Idx, 160 StrTy &Result) { 161 if (Idx > Record.size()) 162 return true; 163 164 Result.append(Record.begin() + Idx, Record.end()); 165 return false; 166 } 167 168 // Strip all the TBAA attachment for the module. 169 static void stripTBAA(Module *M) { 170 for (auto &F : *M) { 171 if (F.isMaterializable()) 172 continue; 173 for (auto &I : instructions(F)) 174 I.setMetadata(LLVMContext::MD_tbaa, nullptr); 175 } 176 } 177 178 /// Read the "IDENTIFICATION_BLOCK_ID" block, do some basic enforcement on the 179 /// "epoch" encoded in the bitcode, and return the producer name if any. 180 static Expected<std::string> readIdentificationBlock(BitstreamCursor &Stream) { 181 if (Error Err = Stream.EnterSubBlock(bitc::IDENTIFICATION_BLOCK_ID)) 182 return std::move(Err); 183 184 // Read all the records. 185 SmallVector<uint64_t, 64> Record; 186 187 std::string ProducerIdentification; 188 189 while (true) { 190 BitstreamEntry Entry; 191 if (Error E = Stream.advance().moveInto(Entry)) 192 return std::move(E); 193 194 switch (Entry.Kind) { 195 default: 196 case BitstreamEntry::Error: 197 return error("Malformed block"); 198 case BitstreamEntry::EndBlock: 199 return ProducerIdentification; 200 case BitstreamEntry::Record: 201 // The interesting case. 202 break; 203 } 204 205 // Read a record. 206 Record.clear(); 207 Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record); 208 if (!MaybeBitCode) 209 return MaybeBitCode.takeError(); 210 switch (MaybeBitCode.get()) { 211 default: // Default behavior: reject 212 return error("Invalid value"); 213 case bitc::IDENTIFICATION_CODE_STRING: // IDENTIFICATION: [strchr x N] 214 convertToString(Record, 0, ProducerIdentification); 215 break; 216 case bitc::IDENTIFICATION_CODE_EPOCH: { // EPOCH: [epoch#] 217 unsigned epoch = (unsigned)Record[0]; 218 if (epoch != bitc::BITCODE_CURRENT_EPOCH) { 219 return error( 220 Twine("Incompatible epoch: Bitcode '") + Twine(epoch) + 221 "' vs current: '" + Twine(bitc::BITCODE_CURRENT_EPOCH) + "'"); 222 } 223 } 224 } 225 } 226 } 227 228 static Expected<std::string> readIdentificationCode(BitstreamCursor &Stream) { 229 // We expect a number of well-defined blocks, though we don't necessarily 230 // need to understand them all. 231 while (true) { 232 if (Stream.AtEndOfStream()) 233 return ""; 234 235 BitstreamEntry Entry; 236 if (Error E = Stream.advance().moveInto(Entry)) 237 return std::move(E); 238 239 switch (Entry.Kind) { 240 case BitstreamEntry::EndBlock: 241 case BitstreamEntry::Error: 242 return error("Malformed block"); 243 244 case BitstreamEntry::SubBlock: 245 if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) 246 return readIdentificationBlock(Stream); 247 248 // Ignore other sub-blocks. 249 if (Error Err = Stream.SkipBlock()) 250 return std::move(Err); 251 continue; 252 case BitstreamEntry::Record: 253 if (Error E = Stream.skipRecord(Entry.ID).takeError()) 254 return std::move(E); 255 continue; 256 } 257 } 258 } 259 260 static Expected<bool> hasObjCCategoryInModule(BitstreamCursor &Stream) { 261 if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID)) 262 return std::move(Err); 263 264 SmallVector<uint64_t, 64> Record; 265 // Read all the records for this module. 266 267 while (true) { 268 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); 269 if (!MaybeEntry) 270 return MaybeEntry.takeError(); 271 BitstreamEntry Entry = MaybeEntry.get(); 272 273 switch (Entry.Kind) { 274 case BitstreamEntry::SubBlock: // Handled for us already. 275 case BitstreamEntry::Error: 276 return error("Malformed block"); 277 case BitstreamEntry::EndBlock: 278 return false; 279 case BitstreamEntry::Record: 280 // The interesting case. 281 break; 282 } 283 284 // Read a record. 285 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record); 286 if (!MaybeRecord) 287 return MaybeRecord.takeError(); 288 switch (MaybeRecord.get()) { 289 default: 290 break; // Default behavior, ignore unknown content. 291 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N] 292 std::string S; 293 if (convertToString(Record, 0, S)) 294 return error("Invalid section name record"); 295 // Check for the i386 and other (x86_64, ARM) conventions 296 if (S.find("__DATA,__objc_catlist") != std::string::npos || 297 S.find("__OBJC,__category") != std::string::npos) 298 return true; 299 break; 300 } 301 } 302 Record.clear(); 303 } 304 llvm_unreachable("Exit infinite loop"); 305 } 306 307 static Expected<bool> hasObjCCategory(BitstreamCursor &Stream) { 308 // We expect a number of well-defined blocks, though we don't necessarily 309 // need to understand them all. 310 while (true) { 311 BitstreamEntry Entry; 312 if (Error E = Stream.advance().moveInto(Entry)) 313 return std::move(E); 314 315 switch (Entry.Kind) { 316 case BitstreamEntry::Error: 317 return error("Malformed block"); 318 case BitstreamEntry::EndBlock: 319 return false; 320 321 case BitstreamEntry::SubBlock: 322 if (Entry.ID == bitc::MODULE_BLOCK_ID) 323 return hasObjCCategoryInModule(Stream); 324 325 // Ignore other sub-blocks. 326 if (Error Err = Stream.SkipBlock()) 327 return std::move(Err); 328 continue; 329 330 case BitstreamEntry::Record: 331 if (Error E = Stream.skipRecord(Entry.ID).takeError()) 332 return std::move(E); 333 continue; 334 } 335 } 336 } 337 338 static Expected<std::string> readModuleTriple(BitstreamCursor &Stream) { 339 if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID)) 340 return std::move(Err); 341 342 SmallVector<uint64_t, 64> Record; 343 344 std::string Triple; 345 346 // Read all the records for this module. 347 while (true) { 348 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); 349 if (!MaybeEntry) 350 return MaybeEntry.takeError(); 351 BitstreamEntry Entry = MaybeEntry.get(); 352 353 switch (Entry.Kind) { 354 case BitstreamEntry::SubBlock: // Handled for us already. 355 case BitstreamEntry::Error: 356 return error("Malformed block"); 357 case BitstreamEntry::EndBlock: 358 return Triple; 359 case BitstreamEntry::Record: 360 // The interesting case. 361 break; 362 } 363 364 // Read a record. 365 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record); 366 if (!MaybeRecord) 367 return MaybeRecord.takeError(); 368 switch (MaybeRecord.get()) { 369 default: break; // Default behavior, ignore unknown content. 370 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N] 371 std::string S; 372 if (convertToString(Record, 0, S)) 373 return error("Invalid triple record"); 374 Triple = S; 375 break; 376 } 377 } 378 Record.clear(); 379 } 380 llvm_unreachable("Exit infinite loop"); 381 } 382 383 static Expected<std::string> readTriple(BitstreamCursor &Stream) { 384 // We expect a number of well-defined blocks, though we don't necessarily 385 // need to understand them all. 386 while (true) { 387 Expected<BitstreamEntry> MaybeEntry = Stream.advance(); 388 if (!MaybeEntry) 389 return MaybeEntry.takeError(); 390 BitstreamEntry Entry = MaybeEntry.get(); 391 392 switch (Entry.Kind) { 393 case BitstreamEntry::Error: 394 return error("Malformed block"); 395 case BitstreamEntry::EndBlock: 396 return ""; 397 398 case BitstreamEntry::SubBlock: 399 if (Entry.ID == bitc::MODULE_BLOCK_ID) 400 return readModuleTriple(Stream); 401 402 // Ignore other sub-blocks. 403 if (Error Err = Stream.SkipBlock()) 404 return std::move(Err); 405 continue; 406 407 case BitstreamEntry::Record: 408 if (llvm::Expected<unsigned> Skipped = Stream.skipRecord(Entry.ID)) 409 continue; 410 else 411 return Skipped.takeError(); 412 } 413 } 414 } 415 416 namespace { 417 418 class BitcodeReaderBase { 419 protected: 420 BitcodeReaderBase(BitstreamCursor Stream, StringRef Strtab) 421 : Stream(std::move(Stream)), Strtab(Strtab) { 422 this->Stream.setBlockInfo(&BlockInfo); 423 } 424 425 BitstreamBlockInfo BlockInfo; 426 BitstreamCursor Stream; 427 StringRef Strtab; 428 429 /// In version 2 of the bitcode we store names of global values and comdats in 430 /// a string table rather than in the VST. 431 bool UseStrtab = false; 432 433 Expected<unsigned> parseVersionRecord(ArrayRef<uint64_t> Record); 434 435 /// If this module uses a string table, pop the reference to the string table 436 /// and return the referenced string and the rest of the record. Otherwise 437 /// just return the record itself. 438 std::pair<StringRef, ArrayRef<uint64_t>> 439 readNameFromStrtab(ArrayRef<uint64_t> Record); 440 441 Error readBlockInfo(); 442 443 // Contains an arbitrary and optional string identifying the bitcode producer 444 std::string ProducerIdentification; 445 446 Error error(const Twine &Message); 447 }; 448 449 } // end anonymous namespace 450 451 Error BitcodeReaderBase::error(const Twine &Message) { 452 std::string FullMsg = Message.str(); 453 if (!ProducerIdentification.empty()) 454 FullMsg += " (Producer: '" + ProducerIdentification + "' Reader: 'LLVM " + 455 LLVM_VERSION_STRING "')"; 456 return ::error(FullMsg); 457 } 458 459 Expected<unsigned> 460 BitcodeReaderBase::parseVersionRecord(ArrayRef<uint64_t> Record) { 461 if (Record.empty()) 462 return error("Invalid version record"); 463 unsigned ModuleVersion = Record[0]; 464 if (ModuleVersion > 2) 465 return error("Invalid value"); 466 UseStrtab = ModuleVersion >= 2; 467 return ModuleVersion; 468 } 469 470 std::pair<StringRef, ArrayRef<uint64_t>> 471 BitcodeReaderBase::readNameFromStrtab(ArrayRef<uint64_t> Record) { 472 if (!UseStrtab) 473 return {"", Record}; 474 // Invalid reference. Let the caller complain about the record being empty. 475 if (Record[0] + Record[1] > Strtab.size()) 476 return {"", {}}; 477 return {StringRef(Strtab.data() + Record[0], Record[1]), Record.slice(2)}; 478 } 479 480 namespace { 481 482 /// This represents a constant expression or constant aggregate using a custom 483 /// structure internal to the bitcode reader. Later, this structure will be 484 /// expanded by materializeValue() either into a constant expression/aggregate, 485 /// or into an instruction sequence at the point of use. This allows us to 486 /// upgrade bitcode using constant expressions even if this kind of constant 487 /// expression is no longer supported. 488 class BitcodeConstant final : public Value, 489 TrailingObjects<BitcodeConstant, unsigned> { 490 friend TrailingObjects; 491 492 // Value subclass ID: Pick largest possible value to avoid any clashes. 493 static constexpr uint8_t SubclassID = 255; 494 495 public: 496 // Opcodes used for non-expressions. This includes constant aggregates 497 // (struct, array, vector) that might need expansion, as well as non-leaf 498 // constants that don't need expansion (no_cfi, dso_local, blockaddress), 499 // but still go through BitcodeConstant to avoid different uselist orders 500 // between the two cases. 501 static constexpr uint8_t ConstantStructOpcode = 255; 502 static constexpr uint8_t ConstantArrayOpcode = 254; 503 static constexpr uint8_t ConstantVectorOpcode = 253; 504 static constexpr uint8_t NoCFIOpcode = 252; 505 static constexpr uint8_t DSOLocalEquivalentOpcode = 251; 506 static constexpr uint8_t BlockAddressOpcode = 250; 507 static constexpr uint8_t FirstSpecialOpcode = BlockAddressOpcode; 508 509 // Separate struct to make passing different number of parameters to 510 // BitcodeConstant::create() more convenient. 511 struct ExtraInfo { 512 uint8_t Opcode; 513 uint8_t Flags; 514 unsigned Extra; 515 Type *SrcElemTy; 516 517 ExtraInfo(uint8_t Opcode, uint8_t Flags = 0, unsigned Extra = 0, 518 Type *SrcElemTy = nullptr) 519 : Opcode(Opcode), Flags(Flags), Extra(Extra), SrcElemTy(SrcElemTy) {} 520 }; 521 522 uint8_t Opcode; 523 uint8_t Flags; 524 unsigned NumOperands; 525 unsigned Extra; // GEP inrange index or blockaddress BB id. 526 Type *SrcElemTy; // GEP source element type. 527 528 private: 529 BitcodeConstant(Type *Ty, const ExtraInfo &Info, ArrayRef<unsigned> OpIDs) 530 : Value(Ty, SubclassID), Opcode(Info.Opcode), Flags(Info.Flags), 531 NumOperands(OpIDs.size()), Extra(Info.Extra), 532 SrcElemTy(Info.SrcElemTy) { 533 std::uninitialized_copy(OpIDs.begin(), OpIDs.end(), 534 getTrailingObjects<unsigned>()); 535 } 536 537 BitcodeConstant &operator=(const BitcodeConstant &) = delete; 538 539 public: 540 static BitcodeConstant *create(BumpPtrAllocator &A, Type *Ty, 541 const ExtraInfo &Info, 542 ArrayRef<unsigned> OpIDs) { 543 void *Mem = A.Allocate(totalSizeToAlloc<unsigned>(OpIDs.size()), 544 alignof(BitcodeConstant)); 545 return new (Mem) BitcodeConstant(Ty, Info, OpIDs); 546 } 547 548 static bool classof(const Value *V) { return V->getValueID() == SubclassID; } 549 550 ArrayRef<unsigned> getOperandIDs() const { 551 return ArrayRef(getTrailingObjects<unsigned>(), NumOperands); 552 } 553 554 std::optional<unsigned> getInRangeIndex() const { 555 assert(Opcode == Instruction::GetElementPtr); 556 if (Extra == (unsigned)-1) 557 return std::nullopt; 558 return Extra; 559 } 560 561 const char *getOpcodeName() const { 562 return Instruction::getOpcodeName(Opcode); 563 } 564 }; 565 566 class BitcodeReader : public BitcodeReaderBase, public GVMaterializer { 567 LLVMContext &Context; 568 Module *TheModule = nullptr; 569 // Next offset to start scanning for lazy parsing of function bodies. 570 uint64_t NextUnreadBit = 0; 571 // Last function offset found in the VST. 572 uint64_t LastFunctionBlockBit = 0; 573 bool SeenValueSymbolTable = false; 574 uint64_t VSTOffset = 0; 575 576 std::vector<std::string> SectionTable; 577 std::vector<std::string> GCTable; 578 579 std::vector<Type *> TypeList; 580 /// Track type IDs of contained types. Order is the same as the contained 581 /// types of a Type*. This is used during upgrades of typed pointer IR in 582 /// opaque pointer mode. 583 DenseMap<unsigned, SmallVector<unsigned, 1>> ContainedTypeIDs; 584 /// In some cases, we need to create a type ID for a type that was not 585 /// explicitly encoded in the bitcode, or we don't know about at the current 586 /// point. For example, a global may explicitly encode the value type ID, but 587 /// not have a type ID for the pointer to value type, for which we create a 588 /// virtual type ID instead. This map stores the new type ID that was created 589 /// for the given pair of Type and contained type ID. 590 DenseMap<std::pair<Type *, unsigned>, unsigned> VirtualTypeIDs; 591 DenseMap<Function *, unsigned> FunctionTypeIDs; 592 /// Allocator for BitcodeConstants. This should come before ValueList, 593 /// because the ValueList might hold ValueHandles to these constants, so 594 /// ValueList must be destroyed before Alloc. 595 BumpPtrAllocator Alloc; 596 BitcodeReaderValueList ValueList; 597 std::optional<MetadataLoader> MDLoader; 598 std::vector<Comdat *> ComdatList; 599 DenseSet<GlobalObject *> ImplicitComdatObjects; 600 SmallVector<Instruction *, 64> InstructionList; 601 602 std::vector<std::pair<GlobalVariable *, unsigned>> GlobalInits; 603 std::vector<std::pair<GlobalValue *, unsigned>> IndirectSymbolInits; 604 605 struct FunctionOperandInfo { 606 Function *F; 607 unsigned PersonalityFn; 608 unsigned Prefix; 609 unsigned Prologue; 610 }; 611 std::vector<FunctionOperandInfo> FunctionOperands; 612 613 /// The set of attributes by index. Index zero in the file is for null, and 614 /// is thus not represented here. As such all indices are off by one. 615 std::vector<AttributeList> MAttributes; 616 617 /// The set of attribute groups. 618 std::map<unsigned, AttributeList> MAttributeGroups; 619 620 /// While parsing a function body, this is a list of the basic blocks for the 621 /// function. 622 std::vector<BasicBlock*> FunctionBBs; 623 624 // When reading the module header, this list is populated with functions that 625 // have bodies later in the file. 626 std::vector<Function*> FunctionsWithBodies; 627 628 // When intrinsic functions are encountered which require upgrading they are 629 // stored here with their replacement function. 630 using UpdatedIntrinsicMap = DenseMap<Function *, Function *>; 631 UpdatedIntrinsicMap UpgradedIntrinsics; 632 633 // Several operations happen after the module header has been read, but 634 // before function bodies are processed. This keeps track of whether 635 // we've done this yet. 636 bool SeenFirstFunctionBody = false; 637 638 /// When function bodies are initially scanned, this map contains info about 639 /// where to find deferred function body in the stream. 640 DenseMap<Function*, uint64_t> DeferredFunctionInfo; 641 642 /// When Metadata block is initially scanned when parsing the module, we may 643 /// choose to defer parsing of the metadata. This vector contains info about 644 /// which Metadata blocks are deferred. 645 std::vector<uint64_t> DeferredMetadataInfo; 646 647 /// These are basic blocks forward-referenced by block addresses. They are 648 /// inserted lazily into functions when they're loaded. The basic block ID is 649 /// its index into the vector. 650 DenseMap<Function *, std::vector<BasicBlock *>> BasicBlockFwdRefs; 651 std::deque<Function *> BasicBlockFwdRefQueue; 652 653 /// These are Functions that contain BlockAddresses which refer a different 654 /// Function. When parsing the different Function, queue Functions that refer 655 /// to the different Function. Those Functions must be materialized in order 656 /// to resolve their BlockAddress constants before the different Function 657 /// gets moved into another Module. 658 std::vector<Function *> BackwardRefFunctions; 659 660 /// Indicates that we are using a new encoding for instruction operands where 661 /// most operands in the current FUNCTION_BLOCK are encoded relative to the 662 /// instruction number, for a more compact encoding. Some instruction 663 /// operands are not relative to the instruction ID: basic block numbers, and 664 /// types. Once the old style function blocks have been phased out, we would 665 /// not need this flag. 666 bool UseRelativeIDs = false; 667 668 /// True if all functions will be materialized, negating the need to process 669 /// (e.g.) blockaddress forward references. 670 bool WillMaterializeAllForwardRefs = false; 671 672 bool StripDebugInfo = false; 673 TBAAVerifier TBAAVerifyHelper; 674 675 std::vector<std::string> BundleTags; 676 SmallVector<SyncScope::ID, 8> SSIDs; 677 678 std::optional<ValueTypeCallbackTy> ValueTypeCallback; 679 680 public: 681 BitcodeReader(BitstreamCursor Stream, StringRef Strtab, 682 StringRef ProducerIdentification, LLVMContext &Context); 683 684 Error materializeForwardReferencedFunctions(); 685 686 Error materialize(GlobalValue *GV) override; 687 Error materializeModule() override; 688 std::vector<StructType *> getIdentifiedStructTypes() const override; 689 690 /// Main interface to parsing a bitcode buffer. 691 /// \returns true if an error occurred. 692 Error parseBitcodeInto(Module *M, bool ShouldLazyLoadMetadata, 693 bool IsImporting, ParserCallbacks Callbacks = {}); 694 695 static uint64_t decodeSignRotatedValue(uint64_t V); 696 697 /// Materialize any deferred Metadata block. 698 Error materializeMetadata() override; 699 700 void setStripDebugInfo() override; 701 702 private: 703 std::vector<StructType *> IdentifiedStructTypes; 704 StructType *createIdentifiedStructType(LLVMContext &Context, StringRef Name); 705 StructType *createIdentifiedStructType(LLVMContext &Context); 706 707 static constexpr unsigned InvalidTypeID = ~0u; 708 709 Type *getTypeByID(unsigned ID); 710 Type *getPtrElementTypeByID(unsigned ID); 711 unsigned getContainedTypeID(unsigned ID, unsigned Idx = 0); 712 unsigned getVirtualTypeID(Type *Ty, ArrayRef<unsigned> ContainedTypeIDs = {}); 713 714 void callValueTypeCallback(Value *F, unsigned TypeID); 715 Expected<Value *> materializeValue(unsigned ValID, BasicBlock *InsertBB); 716 Expected<Constant *> getValueForInitializer(unsigned ID); 717 718 Value *getFnValueByID(unsigned ID, Type *Ty, unsigned TyID, 719 BasicBlock *ConstExprInsertBB) { 720 if (Ty && Ty->isMetadataTy()) 721 return MetadataAsValue::get(Ty->getContext(), getFnMetadataByID(ID)); 722 return ValueList.getValueFwdRef(ID, Ty, TyID, ConstExprInsertBB); 723 } 724 725 Metadata *getFnMetadataByID(unsigned ID) { 726 return MDLoader->getMetadataFwdRefOrLoad(ID); 727 } 728 729 BasicBlock *getBasicBlock(unsigned ID) const { 730 if (ID >= FunctionBBs.size()) return nullptr; // Invalid ID 731 return FunctionBBs[ID]; 732 } 733 734 AttributeList getAttributes(unsigned i) const { 735 if (i-1 < MAttributes.size()) 736 return MAttributes[i-1]; 737 return AttributeList(); 738 } 739 740 /// Read a value/type pair out of the specified record from slot 'Slot'. 741 /// Increment Slot past the number of slots used in the record. Return true on 742 /// failure. 743 bool getValueTypePair(const SmallVectorImpl<uint64_t> &Record, unsigned &Slot, 744 unsigned InstNum, Value *&ResVal, unsigned &TypeID, 745 BasicBlock *ConstExprInsertBB) { 746 if (Slot == Record.size()) return true; 747 unsigned ValNo = (unsigned)Record[Slot++]; 748 // Adjust the ValNo, if it was encoded relative to the InstNum. 749 if (UseRelativeIDs) 750 ValNo = InstNum - ValNo; 751 if (ValNo < InstNum) { 752 // If this is not a forward reference, just return the value we already 753 // have. 754 TypeID = ValueList.getTypeID(ValNo); 755 ResVal = getFnValueByID(ValNo, nullptr, TypeID, ConstExprInsertBB); 756 assert((!ResVal || ResVal->getType() == getTypeByID(TypeID)) && 757 "Incorrect type ID stored for value"); 758 return ResVal == nullptr; 759 } 760 if (Slot == Record.size()) 761 return true; 762 763 TypeID = (unsigned)Record[Slot++]; 764 ResVal = getFnValueByID(ValNo, getTypeByID(TypeID), TypeID, 765 ConstExprInsertBB); 766 return ResVal == nullptr; 767 } 768 769 /// Read a value out of the specified record from slot 'Slot'. Increment Slot 770 /// past the number of slots used by the value in the record. Return true if 771 /// there is an error. 772 bool popValue(const SmallVectorImpl<uint64_t> &Record, unsigned &Slot, 773 unsigned InstNum, Type *Ty, unsigned TyID, Value *&ResVal, 774 BasicBlock *ConstExprInsertBB) { 775 if (getValue(Record, Slot, InstNum, Ty, TyID, ResVal, ConstExprInsertBB)) 776 return true; 777 // All values currently take a single record slot. 778 ++Slot; 779 return false; 780 } 781 782 /// Like popValue, but does not increment the Slot number. 783 bool getValue(const SmallVectorImpl<uint64_t> &Record, unsigned Slot, 784 unsigned InstNum, Type *Ty, unsigned TyID, Value *&ResVal, 785 BasicBlock *ConstExprInsertBB) { 786 ResVal = getValue(Record, Slot, InstNum, Ty, TyID, ConstExprInsertBB); 787 return ResVal == nullptr; 788 } 789 790 /// Version of getValue that returns ResVal directly, or 0 if there is an 791 /// error. 792 Value *getValue(const SmallVectorImpl<uint64_t> &Record, unsigned Slot, 793 unsigned InstNum, Type *Ty, unsigned TyID, 794 BasicBlock *ConstExprInsertBB) { 795 if (Slot == Record.size()) return nullptr; 796 unsigned ValNo = (unsigned)Record[Slot]; 797 // Adjust the ValNo, if it was encoded relative to the InstNum. 798 if (UseRelativeIDs) 799 ValNo = InstNum - ValNo; 800 return getFnValueByID(ValNo, Ty, TyID, ConstExprInsertBB); 801 } 802 803 /// Like getValue, but decodes signed VBRs. 804 Value *getValueSigned(const SmallVectorImpl<uint64_t> &Record, unsigned Slot, 805 unsigned InstNum, Type *Ty, unsigned TyID, 806 BasicBlock *ConstExprInsertBB) { 807 if (Slot == Record.size()) return nullptr; 808 unsigned ValNo = (unsigned)decodeSignRotatedValue(Record[Slot]); 809 // Adjust the ValNo, if it was encoded relative to the InstNum. 810 if (UseRelativeIDs) 811 ValNo = InstNum - ValNo; 812 return getFnValueByID(ValNo, Ty, TyID, ConstExprInsertBB); 813 } 814 815 /// Upgrades old-style typeless byval/sret/inalloca attributes by adding the 816 /// corresponding argument's pointee type. Also upgrades intrinsics that now 817 /// require an elementtype attribute. 818 Error propagateAttributeTypes(CallBase *CB, ArrayRef<unsigned> ArgsTys); 819 820 /// Converts alignment exponent (i.e. power of two (or zero)) to the 821 /// corresponding alignment to use. If alignment is too large, returns 822 /// a corresponding error code. 823 Error parseAlignmentValue(uint64_t Exponent, MaybeAlign &Alignment); 824 Error parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind); 825 Error parseModule(uint64_t ResumeBit, bool ShouldLazyLoadMetadata = false, 826 ParserCallbacks Callbacks = {}); 827 828 Error parseComdatRecord(ArrayRef<uint64_t> Record); 829 Error parseGlobalVarRecord(ArrayRef<uint64_t> Record); 830 Error parseFunctionRecord(ArrayRef<uint64_t> Record); 831 Error parseGlobalIndirectSymbolRecord(unsigned BitCode, 832 ArrayRef<uint64_t> Record); 833 834 Error parseAttributeBlock(); 835 Error parseAttributeGroupBlock(); 836 Error parseTypeTable(); 837 Error parseTypeTableBody(); 838 Error parseOperandBundleTags(); 839 Error parseSyncScopeNames(); 840 841 Expected<Value *> recordValue(SmallVectorImpl<uint64_t> &Record, 842 unsigned NameIndex, Triple &TT); 843 void setDeferredFunctionInfo(unsigned FuncBitcodeOffsetDelta, Function *F, 844 ArrayRef<uint64_t> Record); 845 Error parseValueSymbolTable(uint64_t Offset = 0); 846 Error parseGlobalValueSymbolTable(); 847 Error parseConstants(); 848 Error rememberAndSkipFunctionBodies(); 849 Error rememberAndSkipFunctionBody(); 850 /// Save the positions of the Metadata blocks and skip parsing the blocks. 851 Error rememberAndSkipMetadata(); 852 Error typeCheckLoadStoreInst(Type *ValType, Type *PtrType); 853 Error parseFunctionBody(Function *F); 854 Error globalCleanup(); 855 Error resolveGlobalAndIndirectSymbolInits(); 856 Error parseUseLists(); 857 Error findFunctionInStream( 858 Function *F, 859 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator); 860 861 SyncScope::ID getDecodedSyncScopeID(unsigned Val); 862 }; 863 864 /// Class to manage reading and parsing function summary index bitcode 865 /// files/sections. 866 class ModuleSummaryIndexBitcodeReader : public BitcodeReaderBase { 867 /// The module index built during parsing. 868 ModuleSummaryIndex &TheIndex; 869 870 /// Indicates whether we have encountered a global value summary section 871 /// yet during parsing. 872 bool SeenGlobalValSummary = false; 873 874 /// Indicates whether we have already parsed the VST, used for error checking. 875 bool SeenValueSymbolTable = false; 876 877 /// Set to the offset of the VST recorded in the MODULE_CODE_VSTOFFSET record. 878 /// Used to enable on-demand parsing of the VST. 879 uint64_t VSTOffset = 0; 880 881 // Map to save ValueId to ValueInfo association that was recorded in the 882 // ValueSymbolTable. It is used after the VST is parsed to convert 883 // call graph edges read from the function summary from referencing 884 // callees by their ValueId to using the ValueInfo instead, which is how 885 // they are recorded in the summary index being built. 886 // We save a GUID which refers to the same global as the ValueInfo, but 887 // ignoring the linkage, i.e. for values other than local linkage they are 888 // identical (this is the second tuple member). 889 // The third tuple member is the real GUID of the ValueInfo. 890 DenseMap<unsigned, 891 std::tuple<ValueInfo, GlobalValue::GUID, GlobalValue::GUID>> 892 ValueIdToValueInfoMap; 893 894 /// Map populated during module path string table parsing, from the 895 /// module ID to a string reference owned by the index's module 896 /// path string table, used to correlate with combined index 897 /// summary records. 898 DenseMap<uint64_t, StringRef> ModuleIdMap; 899 900 /// Original source file name recorded in a bitcode record. 901 std::string SourceFileName; 902 903 /// The string identifier given to this module by the client, normally the 904 /// path to the bitcode file. 905 StringRef ModulePath; 906 907 /// Callback to ask whether a symbol is the prevailing copy when invoked 908 /// during combined index building. 909 std::function<bool(GlobalValue::GUID)> IsPrevailing; 910 911 /// Saves the stack ids from the STACK_IDS record to consult when adding stack 912 /// ids from the lists in the callsite and alloc entries to the index. 913 std::vector<uint64_t> StackIds; 914 915 public: 916 ModuleSummaryIndexBitcodeReader( 917 BitstreamCursor Stream, StringRef Strtab, ModuleSummaryIndex &TheIndex, 918 StringRef ModulePath, 919 std::function<bool(GlobalValue::GUID)> IsPrevailing = nullptr); 920 921 Error parseModule(); 922 923 private: 924 void setValueGUID(uint64_t ValueID, StringRef ValueName, 925 GlobalValue::LinkageTypes Linkage, 926 StringRef SourceFileName); 927 Error parseValueSymbolTable( 928 uint64_t Offset, 929 DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap); 930 std::vector<ValueInfo> makeRefList(ArrayRef<uint64_t> Record); 931 std::vector<FunctionSummary::EdgeTy> makeCallList(ArrayRef<uint64_t> Record, 932 bool IsOldProfileFormat, 933 bool HasProfile, 934 bool HasRelBF); 935 Error parseEntireSummary(unsigned ID); 936 Error parseModuleStringTable(); 937 void parseTypeIdCompatibleVtableSummaryRecord(ArrayRef<uint64_t> Record); 938 void parseTypeIdCompatibleVtableInfo(ArrayRef<uint64_t> Record, size_t &Slot, 939 TypeIdCompatibleVtableInfo &TypeId); 940 std::vector<FunctionSummary::ParamAccess> 941 parseParamAccesses(ArrayRef<uint64_t> Record); 942 943 template <bool AllowNullValueInfo = false> 944 std::tuple<ValueInfo, GlobalValue::GUID, GlobalValue::GUID> 945 getValueInfoFromValueId(unsigned ValueId); 946 947 void addThisModule(); 948 ModuleSummaryIndex::ModuleInfo *getThisModule(); 949 }; 950 951 } // end anonymous namespace 952 953 std::error_code llvm::errorToErrorCodeAndEmitErrors(LLVMContext &Ctx, 954 Error Err) { 955 if (Err) { 956 std::error_code EC; 957 handleAllErrors(std::move(Err), [&](ErrorInfoBase &EIB) { 958 EC = EIB.convertToErrorCode(); 959 Ctx.emitError(EIB.message()); 960 }); 961 return EC; 962 } 963 return std::error_code(); 964 } 965 966 BitcodeReader::BitcodeReader(BitstreamCursor Stream, StringRef Strtab, 967 StringRef ProducerIdentification, 968 LLVMContext &Context) 969 : BitcodeReaderBase(std::move(Stream), Strtab), Context(Context), 970 ValueList(this->Stream.SizeInBytes(), 971 [this](unsigned ValID, BasicBlock *InsertBB) { 972 return materializeValue(ValID, InsertBB); 973 }) { 974 this->ProducerIdentification = std::string(ProducerIdentification); 975 } 976 977 Error BitcodeReader::materializeForwardReferencedFunctions() { 978 if (WillMaterializeAllForwardRefs) 979 return Error::success(); 980 981 // Prevent recursion. 982 WillMaterializeAllForwardRefs = true; 983 984 while (!BasicBlockFwdRefQueue.empty()) { 985 Function *F = BasicBlockFwdRefQueue.front(); 986 BasicBlockFwdRefQueue.pop_front(); 987 assert(F && "Expected valid function"); 988 if (!BasicBlockFwdRefs.count(F)) 989 // Already materialized. 990 continue; 991 992 // Check for a function that isn't materializable to prevent an infinite 993 // loop. When parsing a blockaddress stored in a global variable, there 994 // isn't a trivial way to check if a function will have a body without a 995 // linear search through FunctionsWithBodies, so just check it here. 996 if (!F->isMaterializable()) 997 return error("Never resolved function from blockaddress"); 998 999 // Try to materialize F. 1000 if (Error Err = materialize(F)) 1001 return Err; 1002 } 1003 assert(BasicBlockFwdRefs.empty() && "Function missing from queue"); 1004 1005 for (Function *F : BackwardRefFunctions) 1006 if (Error Err = materialize(F)) 1007 return Err; 1008 BackwardRefFunctions.clear(); 1009 1010 // Reset state. 1011 WillMaterializeAllForwardRefs = false; 1012 return Error::success(); 1013 } 1014 1015 //===----------------------------------------------------------------------===// 1016 // Helper functions to implement forward reference resolution, etc. 1017 //===----------------------------------------------------------------------===// 1018 1019 static bool hasImplicitComdat(size_t Val) { 1020 switch (Val) { 1021 default: 1022 return false; 1023 case 1: // Old WeakAnyLinkage 1024 case 4: // Old LinkOnceAnyLinkage 1025 case 10: // Old WeakODRLinkage 1026 case 11: // Old LinkOnceODRLinkage 1027 return true; 1028 } 1029 } 1030 1031 static GlobalValue::LinkageTypes getDecodedLinkage(unsigned Val) { 1032 switch (Val) { 1033 default: // Map unknown/new linkages to external 1034 case 0: 1035 return GlobalValue::ExternalLinkage; 1036 case 2: 1037 return GlobalValue::AppendingLinkage; 1038 case 3: 1039 return GlobalValue::InternalLinkage; 1040 case 5: 1041 return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage 1042 case 6: 1043 return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage 1044 case 7: 1045 return GlobalValue::ExternalWeakLinkage; 1046 case 8: 1047 return GlobalValue::CommonLinkage; 1048 case 9: 1049 return GlobalValue::PrivateLinkage; 1050 case 12: 1051 return GlobalValue::AvailableExternallyLinkage; 1052 case 13: 1053 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage 1054 case 14: 1055 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage 1056 case 15: 1057 return GlobalValue::ExternalLinkage; // Obsolete LinkOnceODRAutoHideLinkage 1058 case 1: // Old value with implicit comdat. 1059 case 16: 1060 return GlobalValue::WeakAnyLinkage; 1061 case 10: // Old value with implicit comdat. 1062 case 17: 1063 return GlobalValue::WeakODRLinkage; 1064 case 4: // Old value with implicit comdat. 1065 case 18: 1066 return GlobalValue::LinkOnceAnyLinkage; 1067 case 11: // Old value with implicit comdat. 1068 case 19: 1069 return GlobalValue::LinkOnceODRLinkage; 1070 } 1071 } 1072 1073 static FunctionSummary::FFlags getDecodedFFlags(uint64_t RawFlags) { 1074 FunctionSummary::FFlags Flags; 1075 Flags.ReadNone = RawFlags & 0x1; 1076 Flags.ReadOnly = (RawFlags >> 1) & 0x1; 1077 Flags.NoRecurse = (RawFlags >> 2) & 0x1; 1078 Flags.ReturnDoesNotAlias = (RawFlags >> 3) & 0x1; 1079 Flags.NoInline = (RawFlags >> 4) & 0x1; 1080 Flags.AlwaysInline = (RawFlags >> 5) & 0x1; 1081 Flags.NoUnwind = (RawFlags >> 6) & 0x1; 1082 Flags.MayThrow = (RawFlags >> 7) & 0x1; 1083 Flags.HasUnknownCall = (RawFlags >> 8) & 0x1; 1084 Flags.MustBeUnreachable = (RawFlags >> 9) & 0x1; 1085 return Flags; 1086 } 1087 1088 // Decode the flags for GlobalValue in the summary. The bits for each attribute: 1089 // 1090 // linkage: [0,4), notEligibleToImport: 4, live: 5, local: 6, canAutoHide: 7, 1091 // visibility: [8, 10). 1092 static GlobalValueSummary::GVFlags getDecodedGVSummaryFlags(uint64_t RawFlags, 1093 uint64_t Version) { 1094 // Summary were not emitted before LLVM 3.9, we don't need to upgrade Linkage 1095 // like getDecodedLinkage() above. Any future change to the linkage enum and 1096 // to getDecodedLinkage() will need to be taken into account here as above. 1097 auto Linkage = GlobalValue::LinkageTypes(RawFlags & 0xF); // 4 bits 1098 auto Visibility = GlobalValue::VisibilityTypes((RawFlags >> 8) & 3); // 2 bits 1099 RawFlags = RawFlags >> 4; 1100 bool NotEligibleToImport = (RawFlags & 0x1) || Version < 3; 1101 // The Live flag wasn't introduced until version 3. For dead stripping 1102 // to work correctly on earlier versions, we must conservatively treat all 1103 // values as live. 1104 bool Live = (RawFlags & 0x2) || Version < 3; 1105 bool Local = (RawFlags & 0x4); 1106 bool AutoHide = (RawFlags & 0x8); 1107 1108 return GlobalValueSummary::GVFlags(Linkage, Visibility, NotEligibleToImport, 1109 Live, Local, AutoHide); 1110 } 1111 1112 // Decode the flags for GlobalVariable in the summary 1113 static GlobalVarSummary::GVarFlags getDecodedGVarFlags(uint64_t RawFlags) { 1114 return GlobalVarSummary::GVarFlags( 1115 (RawFlags & 0x1) ? true : false, (RawFlags & 0x2) ? true : false, 1116 (RawFlags & 0x4) ? true : false, 1117 (GlobalObject::VCallVisibility)(RawFlags >> 3)); 1118 } 1119 1120 static GlobalValue::VisibilityTypes getDecodedVisibility(unsigned Val) { 1121 switch (Val) { 1122 default: // Map unknown visibilities to default. 1123 case 0: return GlobalValue::DefaultVisibility; 1124 case 1: return GlobalValue::HiddenVisibility; 1125 case 2: return GlobalValue::ProtectedVisibility; 1126 } 1127 } 1128 1129 static GlobalValue::DLLStorageClassTypes 1130 getDecodedDLLStorageClass(unsigned Val) { 1131 switch (Val) { 1132 default: // Map unknown values to default. 1133 case 0: return GlobalValue::DefaultStorageClass; 1134 case 1: return GlobalValue::DLLImportStorageClass; 1135 case 2: return GlobalValue::DLLExportStorageClass; 1136 } 1137 } 1138 1139 static bool getDecodedDSOLocal(unsigned Val) { 1140 switch(Val) { 1141 default: // Map unknown values to preemptable. 1142 case 0: return false; 1143 case 1: return true; 1144 } 1145 } 1146 1147 static GlobalVariable::ThreadLocalMode getDecodedThreadLocalMode(unsigned Val) { 1148 switch (Val) { 1149 case 0: return GlobalVariable::NotThreadLocal; 1150 default: // Map unknown non-zero value to general dynamic. 1151 case 1: return GlobalVariable::GeneralDynamicTLSModel; 1152 case 2: return GlobalVariable::LocalDynamicTLSModel; 1153 case 3: return GlobalVariable::InitialExecTLSModel; 1154 case 4: return GlobalVariable::LocalExecTLSModel; 1155 } 1156 } 1157 1158 static GlobalVariable::UnnamedAddr getDecodedUnnamedAddrType(unsigned Val) { 1159 switch (Val) { 1160 default: // Map unknown to UnnamedAddr::None. 1161 case 0: return GlobalVariable::UnnamedAddr::None; 1162 case 1: return GlobalVariable::UnnamedAddr::Global; 1163 case 2: return GlobalVariable::UnnamedAddr::Local; 1164 } 1165 } 1166 1167 static int getDecodedCastOpcode(unsigned Val) { 1168 switch (Val) { 1169 default: return -1; 1170 case bitc::CAST_TRUNC : return Instruction::Trunc; 1171 case bitc::CAST_ZEXT : return Instruction::ZExt; 1172 case bitc::CAST_SEXT : return Instruction::SExt; 1173 case bitc::CAST_FPTOUI : return Instruction::FPToUI; 1174 case bitc::CAST_FPTOSI : return Instruction::FPToSI; 1175 case bitc::CAST_UITOFP : return Instruction::UIToFP; 1176 case bitc::CAST_SITOFP : return Instruction::SIToFP; 1177 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc; 1178 case bitc::CAST_FPEXT : return Instruction::FPExt; 1179 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt; 1180 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr; 1181 case bitc::CAST_BITCAST : return Instruction::BitCast; 1182 case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast; 1183 } 1184 } 1185 1186 static int getDecodedUnaryOpcode(unsigned Val, Type *Ty) { 1187 bool IsFP = Ty->isFPOrFPVectorTy(); 1188 // UnOps are only valid for int/fp or vector of int/fp types 1189 if (!IsFP && !Ty->isIntOrIntVectorTy()) 1190 return -1; 1191 1192 switch (Val) { 1193 default: 1194 return -1; 1195 case bitc::UNOP_FNEG: 1196 return IsFP ? Instruction::FNeg : -1; 1197 } 1198 } 1199 1200 static int getDecodedBinaryOpcode(unsigned Val, Type *Ty) { 1201 bool IsFP = Ty->isFPOrFPVectorTy(); 1202 // BinOps are only valid for int/fp or vector of int/fp types 1203 if (!IsFP && !Ty->isIntOrIntVectorTy()) 1204 return -1; 1205 1206 switch (Val) { 1207 default: 1208 return -1; 1209 case bitc::BINOP_ADD: 1210 return IsFP ? Instruction::FAdd : Instruction::Add; 1211 case bitc::BINOP_SUB: 1212 return IsFP ? Instruction::FSub : Instruction::Sub; 1213 case bitc::BINOP_MUL: 1214 return IsFP ? Instruction::FMul : Instruction::Mul; 1215 case bitc::BINOP_UDIV: 1216 return IsFP ? -1 : Instruction::UDiv; 1217 case bitc::BINOP_SDIV: 1218 return IsFP ? Instruction::FDiv : Instruction::SDiv; 1219 case bitc::BINOP_UREM: 1220 return IsFP ? -1 : Instruction::URem; 1221 case bitc::BINOP_SREM: 1222 return IsFP ? Instruction::FRem : Instruction::SRem; 1223 case bitc::BINOP_SHL: 1224 return IsFP ? -1 : Instruction::Shl; 1225 case bitc::BINOP_LSHR: 1226 return IsFP ? -1 : Instruction::LShr; 1227 case bitc::BINOP_ASHR: 1228 return IsFP ? -1 : Instruction::AShr; 1229 case bitc::BINOP_AND: 1230 return IsFP ? -1 : Instruction::And; 1231 case bitc::BINOP_OR: 1232 return IsFP ? -1 : Instruction::Or; 1233 case bitc::BINOP_XOR: 1234 return IsFP ? -1 : Instruction::Xor; 1235 } 1236 } 1237 1238 static AtomicRMWInst::BinOp getDecodedRMWOperation(unsigned Val) { 1239 switch (Val) { 1240 default: return AtomicRMWInst::BAD_BINOP; 1241 case bitc::RMW_XCHG: return AtomicRMWInst::Xchg; 1242 case bitc::RMW_ADD: return AtomicRMWInst::Add; 1243 case bitc::RMW_SUB: return AtomicRMWInst::Sub; 1244 case bitc::RMW_AND: return AtomicRMWInst::And; 1245 case bitc::RMW_NAND: return AtomicRMWInst::Nand; 1246 case bitc::RMW_OR: return AtomicRMWInst::Or; 1247 case bitc::RMW_XOR: return AtomicRMWInst::Xor; 1248 case bitc::RMW_MAX: return AtomicRMWInst::Max; 1249 case bitc::RMW_MIN: return AtomicRMWInst::Min; 1250 case bitc::RMW_UMAX: return AtomicRMWInst::UMax; 1251 case bitc::RMW_UMIN: return AtomicRMWInst::UMin; 1252 case bitc::RMW_FADD: return AtomicRMWInst::FAdd; 1253 case bitc::RMW_FSUB: return AtomicRMWInst::FSub; 1254 case bitc::RMW_FMAX: return AtomicRMWInst::FMax; 1255 case bitc::RMW_FMIN: return AtomicRMWInst::FMin; 1256 case bitc::RMW_UINC_WRAP: 1257 return AtomicRMWInst::UIncWrap; 1258 case bitc::RMW_UDEC_WRAP: 1259 return AtomicRMWInst::UDecWrap; 1260 } 1261 } 1262 1263 static AtomicOrdering getDecodedOrdering(unsigned Val) { 1264 switch (Val) { 1265 case bitc::ORDERING_NOTATOMIC: return AtomicOrdering::NotAtomic; 1266 case bitc::ORDERING_UNORDERED: return AtomicOrdering::Unordered; 1267 case bitc::ORDERING_MONOTONIC: return AtomicOrdering::Monotonic; 1268 case bitc::ORDERING_ACQUIRE: return AtomicOrdering::Acquire; 1269 case bitc::ORDERING_RELEASE: return AtomicOrdering::Release; 1270 case bitc::ORDERING_ACQREL: return AtomicOrdering::AcquireRelease; 1271 default: // Map unknown orderings to sequentially-consistent. 1272 case bitc::ORDERING_SEQCST: return AtomicOrdering::SequentiallyConsistent; 1273 } 1274 } 1275 1276 static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val) { 1277 switch (Val) { 1278 default: // Map unknown selection kinds to any. 1279 case bitc::COMDAT_SELECTION_KIND_ANY: 1280 return Comdat::Any; 1281 case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH: 1282 return Comdat::ExactMatch; 1283 case bitc::COMDAT_SELECTION_KIND_LARGEST: 1284 return Comdat::Largest; 1285 case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES: 1286 return Comdat::NoDeduplicate; 1287 case bitc::COMDAT_SELECTION_KIND_SAME_SIZE: 1288 return Comdat::SameSize; 1289 } 1290 } 1291 1292 static FastMathFlags getDecodedFastMathFlags(unsigned Val) { 1293 FastMathFlags FMF; 1294 if (0 != (Val & bitc::UnsafeAlgebra)) 1295 FMF.setFast(); 1296 if (0 != (Val & bitc::AllowReassoc)) 1297 FMF.setAllowReassoc(); 1298 if (0 != (Val & bitc::NoNaNs)) 1299 FMF.setNoNaNs(); 1300 if (0 != (Val & bitc::NoInfs)) 1301 FMF.setNoInfs(); 1302 if (0 != (Val & bitc::NoSignedZeros)) 1303 FMF.setNoSignedZeros(); 1304 if (0 != (Val & bitc::AllowReciprocal)) 1305 FMF.setAllowReciprocal(); 1306 if (0 != (Val & bitc::AllowContract)) 1307 FMF.setAllowContract(true); 1308 if (0 != (Val & bitc::ApproxFunc)) 1309 FMF.setApproxFunc(); 1310 return FMF; 1311 } 1312 1313 static void upgradeDLLImportExportLinkage(GlobalValue *GV, unsigned Val) { 1314 // A GlobalValue with local linkage cannot have a DLL storage class. 1315 if (GV->hasLocalLinkage()) 1316 return; 1317 switch (Val) { 1318 case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break; 1319 case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break; 1320 } 1321 } 1322 1323 Type *BitcodeReader::getTypeByID(unsigned ID) { 1324 // The type table size is always specified correctly. 1325 if (ID >= TypeList.size()) 1326 return nullptr; 1327 1328 if (Type *Ty = TypeList[ID]) 1329 return Ty; 1330 1331 // If we have a forward reference, the only possible case is when it is to a 1332 // named struct. Just create a placeholder for now. 1333 return TypeList[ID] = createIdentifiedStructType(Context); 1334 } 1335 1336 unsigned BitcodeReader::getContainedTypeID(unsigned ID, unsigned Idx) { 1337 auto It = ContainedTypeIDs.find(ID); 1338 if (It == ContainedTypeIDs.end()) 1339 return InvalidTypeID; 1340 1341 if (Idx >= It->second.size()) 1342 return InvalidTypeID; 1343 1344 return It->second[Idx]; 1345 } 1346 1347 Type *BitcodeReader::getPtrElementTypeByID(unsigned ID) { 1348 if (ID >= TypeList.size()) 1349 return nullptr; 1350 1351 Type *Ty = TypeList[ID]; 1352 if (!Ty->isPointerTy()) 1353 return nullptr; 1354 1355 return getTypeByID(getContainedTypeID(ID, 0)); 1356 } 1357 1358 unsigned BitcodeReader::getVirtualTypeID(Type *Ty, 1359 ArrayRef<unsigned> ChildTypeIDs) { 1360 unsigned ChildTypeID = ChildTypeIDs.empty() ? InvalidTypeID : ChildTypeIDs[0]; 1361 auto CacheKey = std::make_pair(Ty, ChildTypeID); 1362 auto It = VirtualTypeIDs.find(CacheKey); 1363 if (It != VirtualTypeIDs.end()) { 1364 // The cmpxchg return value is the only place we need more than one 1365 // contained type ID, however the second one will always be the same (i1), 1366 // so we don't need to include it in the cache key. This asserts that the 1367 // contained types are indeed as expected and there are no collisions. 1368 assert((ChildTypeIDs.empty() || 1369 ContainedTypeIDs[It->second] == ChildTypeIDs) && 1370 "Incorrect cached contained type IDs"); 1371 return It->second; 1372 } 1373 1374 unsigned TypeID = TypeList.size(); 1375 TypeList.push_back(Ty); 1376 if (!ChildTypeIDs.empty()) 1377 append_range(ContainedTypeIDs[TypeID], ChildTypeIDs); 1378 VirtualTypeIDs.insert({CacheKey, TypeID}); 1379 return TypeID; 1380 } 1381 1382 static bool isConstExprSupported(const BitcodeConstant *BC) { 1383 uint8_t Opcode = BC->Opcode; 1384 1385 // These are not real constant expressions, always consider them supported. 1386 if (Opcode >= BitcodeConstant::FirstSpecialOpcode) 1387 return true; 1388 1389 // If -expand-constant-exprs is set, we want to consider all expressions 1390 // as unsupported. 1391 if (ExpandConstantExprs) 1392 return false; 1393 1394 if (Instruction::isBinaryOp(Opcode)) 1395 return ConstantExpr::isSupportedBinOp(Opcode); 1396 1397 if (Opcode == Instruction::GetElementPtr) 1398 return ConstantExpr::isSupportedGetElementPtr(BC->SrcElemTy); 1399 1400 switch (Opcode) { 1401 case Instruction::FNeg: 1402 case Instruction::Select: 1403 return false; 1404 default: 1405 return true; 1406 } 1407 } 1408 1409 Expected<Value *> BitcodeReader::materializeValue(unsigned StartValID, 1410 BasicBlock *InsertBB) { 1411 // Quickly handle the case where there is no BitcodeConstant to resolve. 1412 if (StartValID < ValueList.size() && ValueList[StartValID] && 1413 !isa<BitcodeConstant>(ValueList[StartValID])) 1414 return ValueList[StartValID]; 1415 1416 SmallDenseMap<unsigned, Value *> MaterializedValues; 1417 SmallVector<unsigned> Worklist; 1418 Worklist.push_back(StartValID); 1419 while (!Worklist.empty()) { 1420 unsigned ValID = Worklist.back(); 1421 if (MaterializedValues.count(ValID)) { 1422 // Duplicate expression that was already handled. 1423 Worklist.pop_back(); 1424 continue; 1425 } 1426 1427 if (ValID >= ValueList.size() || !ValueList[ValID]) 1428 return error("Invalid value ID"); 1429 1430 Value *V = ValueList[ValID]; 1431 auto *BC = dyn_cast<BitcodeConstant>(V); 1432 if (!BC) { 1433 MaterializedValues.insert({ValID, V}); 1434 Worklist.pop_back(); 1435 continue; 1436 } 1437 1438 // Iterate in reverse, so values will get popped from the worklist in 1439 // expected order. 1440 SmallVector<Value *> Ops; 1441 for (unsigned OpID : reverse(BC->getOperandIDs())) { 1442 auto It = MaterializedValues.find(OpID); 1443 if (It != MaterializedValues.end()) 1444 Ops.push_back(It->second); 1445 else 1446 Worklist.push_back(OpID); 1447 } 1448 1449 // Some expressions have not been resolved yet, handle them first and then 1450 // revisit this one. 1451 if (Ops.size() != BC->getOperandIDs().size()) 1452 continue; 1453 std::reverse(Ops.begin(), Ops.end()); 1454 1455 SmallVector<Constant *> ConstOps; 1456 for (Value *Op : Ops) 1457 if (auto *C = dyn_cast<Constant>(Op)) 1458 ConstOps.push_back(C); 1459 1460 // Materialize as constant expression if possible. 1461 if (isConstExprSupported(BC) && ConstOps.size() == Ops.size()) { 1462 Constant *C; 1463 if (Instruction::isCast(BC->Opcode)) { 1464 C = UpgradeBitCastExpr(BC->Opcode, ConstOps[0], BC->getType()); 1465 if (!C) 1466 C = ConstantExpr::getCast(BC->Opcode, ConstOps[0], BC->getType()); 1467 } else if (Instruction::isBinaryOp(BC->Opcode)) { 1468 C = ConstantExpr::get(BC->Opcode, ConstOps[0], ConstOps[1], BC->Flags); 1469 } else { 1470 switch (BC->Opcode) { 1471 case BitcodeConstant::NoCFIOpcode: { 1472 auto *GV = dyn_cast<GlobalValue>(ConstOps[0]); 1473 if (!GV) 1474 return error("no_cfi operand must be GlobalValue"); 1475 C = NoCFIValue::get(GV); 1476 break; 1477 } 1478 case BitcodeConstant::DSOLocalEquivalentOpcode: { 1479 auto *GV = dyn_cast<GlobalValue>(ConstOps[0]); 1480 if (!GV) 1481 return error("dso_local operand must be GlobalValue"); 1482 C = DSOLocalEquivalent::get(GV); 1483 break; 1484 } 1485 case BitcodeConstant::BlockAddressOpcode: { 1486 Function *Fn = dyn_cast<Function>(ConstOps[0]); 1487 if (!Fn) 1488 return error("blockaddress operand must be a function"); 1489 1490 // If the function is already parsed we can insert the block address 1491 // right away. 1492 BasicBlock *BB; 1493 unsigned BBID = BC->Extra; 1494 if (!BBID) 1495 // Invalid reference to entry block. 1496 return error("Invalid ID"); 1497 if (!Fn->empty()) { 1498 Function::iterator BBI = Fn->begin(), BBE = Fn->end(); 1499 for (size_t I = 0, E = BBID; I != E; ++I) { 1500 if (BBI == BBE) 1501 return error("Invalid ID"); 1502 ++BBI; 1503 } 1504 BB = &*BBI; 1505 } else { 1506 // Otherwise insert a placeholder and remember it so it can be 1507 // inserted when the function is parsed. 1508 auto &FwdBBs = BasicBlockFwdRefs[Fn]; 1509 if (FwdBBs.empty()) 1510 BasicBlockFwdRefQueue.push_back(Fn); 1511 if (FwdBBs.size() < BBID + 1) 1512 FwdBBs.resize(BBID + 1); 1513 if (!FwdBBs[BBID]) 1514 FwdBBs[BBID] = BasicBlock::Create(Context); 1515 BB = FwdBBs[BBID]; 1516 } 1517 C = BlockAddress::get(Fn, BB); 1518 break; 1519 } 1520 case BitcodeConstant::ConstantStructOpcode: 1521 C = ConstantStruct::get(cast<StructType>(BC->getType()), ConstOps); 1522 break; 1523 case BitcodeConstant::ConstantArrayOpcode: 1524 C = ConstantArray::get(cast<ArrayType>(BC->getType()), ConstOps); 1525 break; 1526 case BitcodeConstant::ConstantVectorOpcode: 1527 C = ConstantVector::get(ConstOps); 1528 break; 1529 case Instruction::ICmp: 1530 case Instruction::FCmp: 1531 C = ConstantExpr::getCompare(BC->Flags, ConstOps[0], ConstOps[1]); 1532 break; 1533 case Instruction::GetElementPtr: 1534 C = ConstantExpr::getGetElementPtr(BC->SrcElemTy, ConstOps[0], 1535 ArrayRef(ConstOps).drop_front(), 1536 BC->Flags, BC->getInRangeIndex()); 1537 break; 1538 case Instruction::ExtractElement: 1539 C = ConstantExpr::getExtractElement(ConstOps[0], ConstOps[1]); 1540 break; 1541 case Instruction::InsertElement: 1542 C = ConstantExpr::getInsertElement(ConstOps[0], ConstOps[1], 1543 ConstOps[2]); 1544 break; 1545 case Instruction::ShuffleVector: { 1546 SmallVector<int, 16> Mask; 1547 ShuffleVectorInst::getShuffleMask(ConstOps[2], Mask); 1548 C = ConstantExpr::getShuffleVector(ConstOps[0], ConstOps[1], Mask); 1549 break; 1550 } 1551 default: 1552 llvm_unreachable("Unhandled bitcode constant"); 1553 } 1554 } 1555 1556 // Cache resolved constant. 1557 ValueList.replaceValueWithoutRAUW(ValID, C); 1558 MaterializedValues.insert({ValID, C}); 1559 Worklist.pop_back(); 1560 continue; 1561 } 1562 1563 if (!InsertBB) 1564 return error(Twine("Value referenced by initializer is an unsupported " 1565 "constant expression of type ") + 1566 BC->getOpcodeName()); 1567 1568 // Materialize as instructions if necessary. 1569 Instruction *I; 1570 if (Instruction::isCast(BC->Opcode)) { 1571 I = CastInst::Create((Instruction::CastOps)BC->Opcode, Ops[0], 1572 BC->getType(), "constexpr", InsertBB); 1573 } else if (Instruction::isUnaryOp(BC->Opcode)) { 1574 I = UnaryOperator::Create((Instruction::UnaryOps)BC->Opcode, Ops[0], 1575 "constexpr", InsertBB); 1576 } else if (Instruction::isBinaryOp(BC->Opcode)) { 1577 I = BinaryOperator::Create((Instruction::BinaryOps)BC->Opcode, Ops[0], 1578 Ops[1], "constexpr", InsertBB); 1579 if (isa<OverflowingBinaryOperator>(I)) { 1580 if (BC->Flags & OverflowingBinaryOperator::NoSignedWrap) 1581 I->setHasNoSignedWrap(); 1582 if (BC->Flags & OverflowingBinaryOperator::NoUnsignedWrap) 1583 I->setHasNoUnsignedWrap(); 1584 } 1585 if (isa<PossiblyExactOperator>(I) && 1586 (BC->Flags & PossiblyExactOperator::IsExact)) 1587 I->setIsExact(); 1588 } else { 1589 switch (BC->Opcode) { 1590 case BitcodeConstant::ConstantVectorOpcode: { 1591 Type *IdxTy = Type::getInt32Ty(BC->getContext()); 1592 Value *V = PoisonValue::get(BC->getType()); 1593 for (auto Pair : enumerate(Ops)) { 1594 Value *Idx = ConstantInt::get(IdxTy, Pair.index()); 1595 V = InsertElementInst::Create(V, Pair.value(), Idx, "constexpr.ins", 1596 InsertBB); 1597 } 1598 I = cast<Instruction>(V); 1599 break; 1600 } 1601 case BitcodeConstant::ConstantStructOpcode: 1602 case BitcodeConstant::ConstantArrayOpcode: { 1603 Value *V = PoisonValue::get(BC->getType()); 1604 for (auto Pair : enumerate(Ops)) 1605 V = InsertValueInst::Create(V, Pair.value(), Pair.index(), 1606 "constexpr.ins", InsertBB); 1607 I = cast<Instruction>(V); 1608 break; 1609 } 1610 case Instruction::ICmp: 1611 case Instruction::FCmp: 1612 I = CmpInst::Create((Instruction::OtherOps)BC->Opcode, 1613 (CmpInst::Predicate)BC->Flags, Ops[0], Ops[1], 1614 "constexpr", InsertBB); 1615 break; 1616 case Instruction::GetElementPtr: 1617 I = GetElementPtrInst::Create(BC->SrcElemTy, Ops[0], 1618 ArrayRef(Ops).drop_front(), "constexpr", 1619 InsertBB); 1620 if (BC->Flags) 1621 cast<GetElementPtrInst>(I)->setIsInBounds(); 1622 break; 1623 case Instruction::Select: 1624 I = SelectInst::Create(Ops[0], Ops[1], Ops[2], "constexpr", InsertBB); 1625 break; 1626 case Instruction::ExtractElement: 1627 I = ExtractElementInst::Create(Ops[0], Ops[1], "constexpr", InsertBB); 1628 break; 1629 case Instruction::InsertElement: 1630 I = InsertElementInst::Create(Ops[0], Ops[1], Ops[2], "constexpr", 1631 InsertBB); 1632 break; 1633 case Instruction::ShuffleVector: 1634 I = new ShuffleVectorInst(Ops[0], Ops[1], Ops[2], "constexpr", 1635 InsertBB); 1636 break; 1637 default: 1638 llvm_unreachable("Unhandled bitcode constant"); 1639 } 1640 } 1641 1642 MaterializedValues.insert({ValID, I}); 1643 Worklist.pop_back(); 1644 } 1645 1646 return MaterializedValues[StartValID]; 1647 } 1648 1649 Expected<Constant *> BitcodeReader::getValueForInitializer(unsigned ID) { 1650 Expected<Value *> MaybeV = materializeValue(ID, /* InsertBB */ nullptr); 1651 if (!MaybeV) 1652 return MaybeV.takeError(); 1653 1654 // Result must be Constant if InsertBB is nullptr. 1655 return cast<Constant>(MaybeV.get()); 1656 } 1657 1658 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context, 1659 StringRef Name) { 1660 auto *Ret = StructType::create(Context, Name); 1661 IdentifiedStructTypes.push_back(Ret); 1662 return Ret; 1663 } 1664 1665 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context) { 1666 auto *Ret = StructType::create(Context); 1667 IdentifiedStructTypes.push_back(Ret); 1668 return Ret; 1669 } 1670 1671 //===----------------------------------------------------------------------===// 1672 // Functions for parsing blocks from the bitcode file 1673 //===----------------------------------------------------------------------===// 1674 1675 static uint64_t getRawAttributeMask(Attribute::AttrKind Val) { 1676 switch (Val) { 1677 case Attribute::EndAttrKinds: 1678 case Attribute::EmptyKey: 1679 case Attribute::TombstoneKey: 1680 llvm_unreachable("Synthetic enumerators which should never get here"); 1681 1682 case Attribute::None: return 0; 1683 case Attribute::ZExt: return 1 << 0; 1684 case Attribute::SExt: return 1 << 1; 1685 case Attribute::NoReturn: return 1 << 2; 1686 case Attribute::InReg: return 1 << 3; 1687 case Attribute::StructRet: return 1 << 4; 1688 case Attribute::NoUnwind: return 1 << 5; 1689 case Attribute::NoAlias: return 1 << 6; 1690 case Attribute::ByVal: return 1 << 7; 1691 case Attribute::Nest: return 1 << 8; 1692 case Attribute::ReadNone: return 1 << 9; 1693 case Attribute::ReadOnly: return 1 << 10; 1694 case Attribute::NoInline: return 1 << 11; 1695 case Attribute::AlwaysInline: return 1 << 12; 1696 case Attribute::OptimizeForSize: return 1 << 13; 1697 case Attribute::StackProtect: return 1 << 14; 1698 case Attribute::StackProtectReq: return 1 << 15; 1699 case Attribute::Alignment: return 31 << 16; 1700 case Attribute::NoCapture: return 1 << 21; 1701 case Attribute::NoRedZone: return 1 << 22; 1702 case Attribute::NoImplicitFloat: return 1 << 23; 1703 case Attribute::Naked: return 1 << 24; 1704 case Attribute::InlineHint: return 1 << 25; 1705 case Attribute::StackAlignment: return 7 << 26; 1706 case Attribute::ReturnsTwice: return 1 << 29; 1707 case Attribute::UWTable: return 1 << 30; 1708 case Attribute::NonLazyBind: return 1U << 31; 1709 case Attribute::SanitizeAddress: return 1ULL << 32; 1710 case Attribute::MinSize: return 1ULL << 33; 1711 case Attribute::NoDuplicate: return 1ULL << 34; 1712 case Attribute::StackProtectStrong: return 1ULL << 35; 1713 case Attribute::SanitizeThread: return 1ULL << 36; 1714 case Attribute::SanitizeMemory: return 1ULL << 37; 1715 case Attribute::NoBuiltin: return 1ULL << 38; 1716 case Attribute::Returned: return 1ULL << 39; 1717 case Attribute::Cold: return 1ULL << 40; 1718 case Attribute::Builtin: return 1ULL << 41; 1719 case Attribute::OptimizeNone: return 1ULL << 42; 1720 case Attribute::InAlloca: return 1ULL << 43; 1721 case Attribute::NonNull: return 1ULL << 44; 1722 case Attribute::JumpTable: return 1ULL << 45; 1723 case Attribute::Convergent: return 1ULL << 46; 1724 case Attribute::SafeStack: return 1ULL << 47; 1725 case Attribute::NoRecurse: return 1ULL << 48; 1726 // 1ULL << 49 is InaccessibleMemOnly, which is upgraded separately. 1727 // 1ULL << 50 is InaccessibleMemOrArgMemOnly, which is upgraded separately. 1728 case Attribute::SwiftSelf: return 1ULL << 51; 1729 case Attribute::SwiftError: return 1ULL << 52; 1730 case Attribute::WriteOnly: return 1ULL << 53; 1731 case Attribute::Speculatable: return 1ULL << 54; 1732 case Attribute::StrictFP: return 1ULL << 55; 1733 case Attribute::SanitizeHWAddress: return 1ULL << 56; 1734 case Attribute::NoCfCheck: return 1ULL << 57; 1735 case Attribute::OptForFuzzing: return 1ULL << 58; 1736 case Attribute::ShadowCallStack: return 1ULL << 59; 1737 case Attribute::SpeculativeLoadHardening: 1738 return 1ULL << 60; 1739 case Attribute::ImmArg: 1740 return 1ULL << 61; 1741 case Attribute::WillReturn: 1742 return 1ULL << 62; 1743 case Attribute::NoFree: 1744 return 1ULL << 63; 1745 default: 1746 // Other attributes are not supported in the raw format, 1747 // as we ran out of space. 1748 return 0; 1749 } 1750 llvm_unreachable("Unsupported attribute type"); 1751 } 1752 1753 static void addRawAttributeValue(AttrBuilder &B, uint64_t Val) { 1754 if (!Val) return; 1755 1756 for (Attribute::AttrKind I = Attribute::None; I != Attribute::EndAttrKinds; 1757 I = Attribute::AttrKind(I + 1)) { 1758 if (uint64_t A = (Val & getRawAttributeMask(I))) { 1759 if (I == Attribute::Alignment) 1760 B.addAlignmentAttr(1ULL << ((A >> 16) - 1)); 1761 else if (I == Attribute::StackAlignment) 1762 B.addStackAlignmentAttr(1ULL << ((A >> 26)-1)); 1763 else if (Attribute::isTypeAttrKind(I)) 1764 B.addTypeAttr(I, nullptr); // Type will be auto-upgraded. 1765 else 1766 B.addAttribute(I); 1767 } 1768 } 1769 } 1770 1771 /// This fills an AttrBuilder object with the LLVM attributes that have 1772 /// been decoded from the given integer. This function must stay in sync with 1773 /// 'encodeLLVMAttributesForBitcode'. 1774 static void decodeLLVMAttributesForBitcode(AttrBuilder &B, 1775 uint64_t EncodedAttrs, 1776 uint64_t AttrIdx) { 1777 // The alignment is stored as a 16-bit raw value from bits 31--16. We shift 1778 // the bits above 31 down by 11 bits. 1779 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16; 1780 assert((!Alignment || isPowerOf2_32(Alignment)) && 1781 "Alignment must be a power of two."); 1782 1783 if (Alignment) 1784 B.addAlignmentAttr(Alignment); 1785 1786 uint64_t Attrs = ((EncodedAttrs & (0xfffffULL << 32)) >> 11) | 1787 (EncodedAttrs & 0xffff); 1788 1789 if (AttrIdx == AttributeList::FunctionIndex) { 1790 // Upgrade old memory attributes. 1791 MemoryEffects ME = MemoryEffects::unknown(); 1792 if (Attrs & (1ULL << 9)) { 1793 // ReadNone 1794 Attrs &= ~(1ULL << 9); 1795 ME &= MemoryEffects::none(); 1796 } 1797 if (Attrs & (1ULL << 10)) { 1798 // ReadOnly 1799 Attrs &= ~(1ULL << 10); 1800 ME &= MemoryEffects::readOnly(); 1801 } 1802 if (Attrs & (1ULL << 49)) { 1803 // InaccessibleMemOnly 1804 Attrs &= ~(1ULL << 49); 1805 ME &= MemoryEffects::inaccessibleMemOnly(); 1806 } 1807 if (Attrs & (1ULL << 50)) { 1808 // InaccessibleMemOrArgMemOnly 1809 Attrs &= ~(1ULL << 50); 1810 ME &= MemoryEffects::inaccessibleOrArgMemOnly(); 1811 } 1812 if (Attrs & (1ULL << 53)) { 1813 // WriteOnly 1814 Attrs &= ~(1ULL << 53); 1815 ME &= MemoryEffects::writeOnly(); 1816 } 1817 if (ME != MemoryEffects::unknown()) 1818 B.addMemoryAttr(ME); 1819 } 1820 1821 addRawAttributeValue(B, Attrs); 1822 } 1823 1824 Error BitcodeReader::parseAttributeBlock() { 1825 if (Error Err = Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID)) 1826 return Err; 1827 1828 if (!MAttributes.empty()) 1829 return error("Invalid multiple blocks"); 1830 1831 SmallVector<uint64_t, 64> Record; 1832 1833 SmallVector<AttributeList, 8> Attrs; 1834 1835 // Read all the records. 1836 while (true) { 1837 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); 1838 if (!MaybeEntry) 1839 return MaybeEntry.takeError(); 1840 BitstreamEntry Entry = MaybeEntry.get(); 1841 1842 switch (Entry.Kind) { 1843 case BitstreamEntry::SubBlock: // Handled for us already. 1844 case BitstreamEntry::Error: 1845 return error("Malformed block"); 1846 case BitstreamEntry::EndBlock: 1847 return Error::success(); 1848 case BitstreamEntry::Record: 1849 // The interesting case. 1850 break; 1851 } 1852 1853 // Read a record. 1854 Record.clear(); 1855 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record); 1856 if (!MaybeRecord) 1857 return MaybeRecord.takeError(); 1858 switch (MaybeRecord.get()) { 1859 default: // Default behavior: ignore. 1860 break; 1861 case bitc::PARAMATTR_CODE_ENTRY_OLD: // ENTRY: [paramidx0, attr0, ...] 1862 // Deprecated, but still needed to read old bitcode files. 1863 if (Record.size() & 1) 1864 return error("Invalid parameter attribute record"); 1865 1866 for (unsigned i = 0, e = Record.size(); i != e; i += 2) { 1867 AttrBuilder B(Context); 1868 decodeLLVMAttributesForBitcode(B, Record[i+1], Record[i]); 1869 Attrs.push_back(AttributeList::get(Context, Record[i], B)); 1870 } 1871 1872 MAttributes.push_back(AttributeList::get(Context, Attrs)); 1873 Attrs.clear(); 1874 break; 1875 case bitc::PARAMATTR_CODE_ENTRY: // ENTRY: [attrgrp0, attrgrp1, ...] 1876 for (unsigned i = 0, e = Record.size(); i != e; ++i) 1877 Attrs.push_back(MAttributeGroups[Record[i]]); 1878 1879 MAttributes.push_back(AttributeList::get(Context, Attrs)); 1880 Attrs.clear(); 1881 break; 1882 } 1883 } 1884 } 1885 1886 // Returns Attribute::None on unrecognized codes. 1887 static Attribute::AttrKind getAttrFromCode(uint64_t Code) { 1888 switch (Code) { 1889 default: 1890 return Attribute::None; 1891 case bitc::ATTR_KIND_ALIGNMENT: 1892 return Attribute::Alignment; 1893 case bitc::ATTR_KIND_ALWAYS_INLINE: 1894 return Attribute::AlwaysInline; 1895 case bitc::ATTR_KIND_BUILTIN: 1896 return Attribute::Builtin; 1897 case bitc::ATTR_KIND_BY_VAL: 1898 return Attribute::ByVal; 1899 case bitc::ATTR_KIND_IN_ALLOCA: 1900 return Attribute::InAlloca; 1901 case bitc::ATTR_KIND_COLD: 1902 return Attribute::Cold; 1903 case bitc::ATTR_KIND_CONVERGENT: 1904 return Attribute::Convergent; 1905 case bitc::ATTR_KIND_DISABLE_SANITIZER_INSTRUMENTATION: 1906 return Attribute::DisableSanitizerInstrumentation; 1907 case bitc::ATTR_KIND_ELEMENTTYPE: 1908 return Attribute::ElementType; 1909 case bitc::ATTR_KIND_FNRETTHUNK_EXTERN: 1910 return Attribute::FnRetThunkExtern; 1911 case bitc::ATTR_KIND_INLINE_HINT: 1912 return Attribute::InlineHint; 1913 case bitc::ATTR_KIND_IN_REG: 1914 return Attribute::InReg; 1915 case bitc::ATTR_KIND_JUMP_TABLE: 1916 return Attribute::JumpTable; 1917 case bitc::ATTR_KIND_MEMORY: 1918 return Attribute::Memory; 1919 case bitc::ATTR_KIND_NOFPCLASS: 1920 return Attribute::NoFPClass; 1921 case bitc::ATTR_KIND_MIN_SIZE: 1922 return Attribute::MinSize; 1923 case bitc::ATTR_KIND_NAKED: 1924 return Attribute::Naked; 1925 case bitc::ATTR_KIND_NEST: 1926 return Attribute::Nest; 1927 case bitc::ATTR_KIND_NO_ALIAS: 1928 return Attribute::NoAlias; 1929 case bitc::ATTR_KIND_NO_BUILTIN: 1930 return Attribute::NoBuiltin; 1931 case bitc::ATTR_KIND_NO_CALLBACK: 1932 return Attribute::NoCallback; 1933 case bitc::ATTR_KIND_NO_CAPTURE: 1934 return Attribute::NoCapture; 1935 case bitc::ATTR_KIND_NO_DUPLICATE: 1936 return Attribute::NoDuplicate; 1937 case bitc::ATTR_KIND_NOFREE: 1938 return Attribute::NoFree; 1939 case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT: 1940 return Attribute::NoImplicitFloat; 1941 case bitc::ATTR_KIND_NO_INLINE: 1942 return Attribute::NoInline; 1943 case bitc::ATTR_KIND_NO_RECURSE: 1944 return Attribute::NoRecurse; 1945 case bitc::ATTR_KIND_NO_MERGE: 1946 return Attribute::NoMerge; 1947 case bitc::ATTR_KIND_NON_LAZY_BIND: 1948 return Attribute::NonLazyBind; 1949 case bitc::ATTR_KIND_NON_NULL: 1950 return Attribute::NonNull; 1951 case bitc::ATTR_KIND_DEREFERENCEABLE: 1952 return Attribute::Dereferenceable; 1953 case bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL: 1954 return Attribute::DereferenceableOrNull; 1955 case bitc::ATTR_KIND_ALLOC_ALIGN: 1956 return Attribute::AllocAlign; 1957 case bitc::ATTR_KIND_ALLOC_KIND: 1958 return Attribute::AllocKind; 1959 case bitc::ATTR_KIND_ALLOC_SIZE: 1960 return Attribute::AllocSize; 1961 case bitc::ATTR_KIND_ALLOCATED_POINTER: 1962 return Attribute::AllocatedPointer; 1963 case bitc::ATTR_KIND_NO_RED_ZONE: 1964 return Attribute::NoRedZone; 1965 case bitc::ATTR_KIND_NO_RETURN: 1966 return Attribute::NoReturn; 1967 case bitc::ATTR_KIND_NOSYNC: 1968 return Attribute::NoSync; 1969 case bitc::ATTR_KIND_NOCF_CHECK: 1970 return Attribute::NoCfCheck; 1971 case bitc::ATTR_KIND_NO_PROFILE: 1972 return Attribute::NoProfile; 1973 case bitc::ATTR_KIND_SKIP_PROFILE: 1974 return Attribute::SkipProfile; 1975 case bitc::ATTR_KIND_NO_UNWIND: 1976 return Attribute::NoUnwind; 1977 case bitc::ATTR_KIND_NO_SANITIZE_BOUNDS: 1978 return Attribute::NoSanitizeBounds; 1979 case bitc::ATTR_KIND_NO_SANITIZE_COVERAGE: 1980 return Attribute::NoSanitizeCoverage; 1981 case bitc::ATTR_KIND_NULL_POINTER_IS_VALID: 1982 return Attribute::NullPointerIsValid; 1983 case bitc::ATTR_KIND_OPTIMIZE_FOR_DEBUGGING: 1984 return Attribute::OptimizeForDebugging; 1985 case bitc::ATTR_KIND_OPT_FOR_FUZZING: 1986 return Attribute::OptForFuzzing; 1987 case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE: 1988 return Attribute::OptimizeForSize; 1989 case bitc::ATTR_KIND_OPTIMIZE_NONE: 1990 return Attribute::OptimizeNone; 1991 case bitc::ATTR_KIND_READ_NONE: 1992 return Attribute::ReadNone; 1993 case bitc::ATTR_KIND_READ_ONLY: 1994 return Attribute::ReadOnly; 1995 case bitc::ATTR_KIND_RETURNED: 1996 return Attribute::Returned; 1997 case bitc::ATTR_KIND_RETURNS_TWICE: 1998 return Attribute::ReturnsTwice; 1999 case bitc::ATTR_KIND_S_EXT: 2000 return Attribute::SExt; 2001 case bitc::ATTR_KIND_SPECULATABLE: 2002 return Attribute::Speculatable; 2003 case bitc::ATTR_KIND_STACK_ALIGNMENT: 2004 return Attribute::StackAlignment; 2005 case bitc::ATTR_KIND_STACK_PROTECT: 2006 return Attribute::StackProtect; 2007 case bitc::ATTR_KIND_STACK_PROTECT_REQ: 2008 return Attribute::StackProtectReq; 2009 case bitc::ATTR_KIND_STACK_PROTECT_STRONG: 2010 return Attribute::StackProtectStrong; 2011 case bitc::ATTR_KIND_SAFESTACK: 2012 return Attribute::SafeStack; 2013 case bitc::ATTR_KIND_SHADOWCALLSTACK: 2014 return Attribute::ShadowCallStack; 2015 case bitc::ATTR_KIND_STRICT_FP: 2016 return Attribute::StrictFP; 2017 case bitc::ATTR_KIND_STRUCT_RET: 2018 return Attribute::StructRet; 2019 case bitc::ATTR_KIND_SANITIZE_ADDRESS: 2020 return Attribute::SanitizeAddress; 2021 case bitc::ATTR_KIND_SANITIZE_HWADDRESS: 2022 return Attribute::SanitizeHWAddress; 2023 case bitc::ATTR_KIND_SANITIZE_THREAD: 2024 return Attribute::SanitizeThread; 2025 case bitc::ATTR_KIND_SANITIZE_MEMORY: 2026 return Attribute::SanitizeMemory; 2027 case bitc::ATTR_KIND_SPECULATIVE_LOAD_HARDENING: 2028 return Attribute::SpeculativeLoadHardening; 2029 case bitc::ATTR_KIND_SWIFT_ERROR: 2030 return Attribute::SwiftError; 2031 case bitc::ATTR_KIND_SWIFT_SELF: 2032 return Attribute::SwiftSelf; 2033 case bitc::ATTR_KIND_SWIFT_ASYNC: 2034 return Attribute::SwiftAsync; 2035 case bitc::ATTR_KIND_UW_TABLE: 2036 return Attribute::UWTable; 2037 case bitc::ATTR_KIND_VSCALE_RANGE: 2038 return Attribute::VScaleRange; 2039 case bitc::ATTR_KIND_WILLRETURN: 2040 return Attribute::WillReturn; 2041 case bitc::ATTR_KIND_WRITEONLY: 2042 return Attribute::WriteOnly; 2043 case bitc::ATTR_KIND_Z_EXT: 2044 return Attribute::ZExt; 2045 case bitc::ATTR_KIND_IMMARG: 2046 return Attribute::ImmArg; 2047 case bitc::ATTR_KIND_SANITIZE_MEMTAG: 2048 return Attribute::SanitizeMemTag; 2049 case bitc::ATTR_KIND_PREALLOCATED: 2050 return Attribute::Preallocated; 2051 case bitc::ATTR_KIND_NOUNDEF: 2052 return Attribute::NoUndef; 2053 case bitc::ATTR_KIND_BYREF: 2054 return Attribute::ByRef; 2055 case bitc::ATTR_KIND_MUSTPROGRESS: 2056 return Attribute::MustProgress; 2057 case bitc::ATTR_KIND_HOT: 2058 return Attribute::Hot; 2059 case bitc::ATTR_KIND_PRESPLIT_COROUTINE: 2060 return Attribute::PresplitCoroutine; 2061 } 2062 } 2063 2064 Error BitcodeReader::parseAlignmentValue(uint64_t Exponent, 2065 MaybeAlign &Alignment) { 2066 // Note: Alignment in bitcode files is incremented by 1, so that zero 2067 // can be used for default alignment. 2068 if (Exponent > Value::MaxAlignmentExponent + 1) 2069 return error("Invalid alignment value"); 2070 Alignment = decodeMaybeAlign(Exponent); 2071 return Error::success(); 2072 } 2073 2074 Error BitcodeReader::parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind) { 2075 *Kind = getAttrFromCode(Code); 2076 if (*Kind == Attribute::None) 2077 return error("Unknown attribute kind (" + Twine(Code) + ")"); 2078 return Error::success(); 2079 } 2080 2081 static bool upgradeOldMemoryAttribute(MemoryEffects &ME, uint64_t EncodedKind) { 2082 switch (EncodedKind) { 2083 case bitc::ATTR_KIND_READ_NONE: 2084 ME &= MemoryEffects::none(); 2085 return true; 2086 case bitc::ATTR_KIND_READ_ONLY: 2087 ME &= MemoryEffects::readOnly(); 2088 return true; 2089 case bitc::ATTR_KIND_WRITEONLY: 2090 ME &= MemoryEffects::writeOnly(); 2091 return true; 2092 case bitc::ATTR_KIND_ARGMEMONLY: 2093 ME &= MemoryEffects::argMemOnly(); 2094 return true; 2095 case bitc::ATTR_KIND_INACCESSIBLEMEM_ONLY: 2096 ME &= MemoryEffects::inaccessibleMemOnly(); 2097 return true; 2098 case bitc::ATTR_KIND_INACCESSIBLEMEM_OR_ARGMEMONLY: 2099 ME &= MemoryEffects::inaccessibleOrArgMemOnly(); 2100 return true; 2101 default: 2102 return false; 2103 } 2104 } 2105 2106 Error BitcodeReader::parseAttributeGroupBlock() { 2107 if (Error Err = Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID)) 2108 return Err; 2109 2110 if (!MAttributeGroups.empty()) 2111 return error("Invalid multiple blocks"); 2112 2113 SmallVector<uint64_t, 64> Record; 2114 2115 // Read all the records. 2116 while (true) { 2117 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); 2118 if (!MaybeEntry) 2119 return MaybeEntry.takeError(); 2120 BitstreamEntry Entry = MaybeEntry.get(); 2121 2122 switch (Entry.Kind) { 2123 case BitstreamEntry::SubBlock: // Handled for us already. 2124 case BitstreamEntry::Error: 2125 return error("Malformed block"); 2126 case BitstreamEntry::EndBlock: 2127 return Error::success(); 2128 case BitstreamEntry::Record: 2129 // The interesting case. 2130 break; 2131 } 2132 2133 // Read a record. 2134 Record.clear(); 2135 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record); 2136 if (!MaybeRecord) 2137 return MaybeRecord.takeError(); 2138 switch (MaybeRecord.get()) { 2139 default: // Default behavior: ignore. 2140 break; 2141 case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...] 2142 if (Record.size() < 3) 2143 return error("Invalid grp record"); 2144 2145 uint64_t GrpID = Record[0]; 2146 uint64_t Idx = Record[1]; // Index of the object this attribute refers to. 2147 2148 AttrBuilder B(Context); 2149 MemoryEffects ME = MemoryEffects::unknown(); 2150 for (unsigned i = 2, e = Record.size(); i != e; ++i) { 2151 if (Record[i] == 0) { // Enum attribute 2152 Attribute::AttrKind Kind; 2153 uint64_t EncodedKind = Record[++i]; 2154 if (Idx == AttributeList::FunctionIndex && 2155 upgradeOldMemoryAttribute(ME, EncodedKind)) 2156 continue; 2157 2158 if (Error Err = parseAttrKind(EncodedKind, &Kind)) 2159 return Err; 2160 2161 // Upgrade old-style byval attribute to one with a type, even if it's 2162 // nullptr. We will have to insert the real type when we associate 2163 // this AttributeList with a function. 2164 if (Kind == Attribute::ByVal) 2165 B.addByValAttr(nullptr); 2166 else if (Kind == Attribute::StructRet) 2167 B.addStructRetAttr(nullptr); 2168 else if (Kind == Attribute::InAlloca) 2169 B.addInAllocaAttr(nullptr); 2170 else if (Kind == Attribute::UWTable) 2171 B.addUWTableAttr(UWTableKind::Default); 2172 else if (Attribute::isEnumAttrKind(Kind)) 2173 B.addAttribute(Kind); 2174 else 2175 return error("Not an enum attribute"); 2176 } else if (Record[i] == 1) { // Integer attribute 2177 Attribute::AttrKind Kind; 2178 if (Error Err = parseAttrKind(Record[++i], &Kind)) 2179 return Err; 2180 if (!Attribute::isIntAttrKind(Kind)) 2181 return error("Not an int attribute"); 2182 if (Kind == Attribute::Alignment) 2183 B.addAlignmentAttr(Record[++i]); 2184 else if (Kind == Attribute::StackAlignment) 2185 B.addStackAlignmentAttr(Record[++i]); 2186 else if (Kind == Attribute::Dereferenceable) 2187 B.addDereferenceableAttr(Record[++i]); 2188 else if (Kind == Attribute::DereferenceableOrNull) 2189 B.addDereferenceableOrNullAttr(Record[++i]); 2190 else if (Kind == Attribute::AllocSize) 2191 B.addAllocSizeAttrFromRawRepr(Record[++i]); 2192 else if (Kind == Attribute::VScaleRange) 2193 B.addVScaleRangeAttrFromRawRepr(Record[++i]); 2194 else if (Kind == Attribute::UWTable) 2195 B.addUWTableAttr(UWTableKind(Record[++i])); 2196 else if (Kind == Attribute::AllocKind) 2197 B.addAllocKindAttr(static_cast<AllocFnKind>(Record[++i])); 2198 else if (Kind == Attribute::Memory) 2199 B.addMemoryAttr(MemoryEffects::createFromIntValue(Record[++i])); 2200 else if (Kind == Attribute::NoFPClass) 2201 B.addNoFPClassAttr( 2202 static_cast<FPClassTest>(Record[++i] & fcAllFlags)); 2203 } else if (Record[i] == 3 || Record[i] == 4) { // String attribute 2204 bool HasValue = (Record[i++] == 4); 2205 SmallString<64> KindStr; 2206 SmallString<64> ValStr; 2207 2208 while (Record[i] != 0 && i != e) 2209 KindStr += Record[i++]; 2210 assert(Record[i] == 0 && "Kind string not null terminated"); 2211 2212 if (HasValue) { 2213 // Has a value associated with it. 2214 ++i; // Skip the '0' that terminates the "kind" string. 2215 while (Record[i] != 0 && i != e) 2216 ValStr += Record[i++]; 2217 assert(Record[i] == 0 && "Value string not null terminated"); 2218 } 2219 2220 B.addAttribute(KindStr.str(), ValStr.str()); 2221 } else if (Record[i] == 5 || Record[i] == 6) { 2222 bool HasType = Record[i] == 6; 2223 Attribute::AttrKind Kind; 2224 if (Error Err = parseAttrKind(Record[++i], &Kind)) 2225 return Err; 2226 if (!Attribute::isTypeAttrKind(Kind)) 2227 return error("Not a type attribute"); 2228 2229 B.addTypeAttr(Kind, HasType ? getTypeByID(Record[++i]) : nullptr); 2230 } else { 2231 return error("Invalid attribute group entry"); 2232 } 2233 } 2234 2235 if (ME != MemoryEffects::unknown()) 2236 B.addMemoryAttr(ME); 2237 2238 UpgradeAttributes(B); 2239 MAttributeGroups[GrpID] = AttributeList::get(Context, Idx, B); 2240 break; 2241 } 2242 } 2243 } 2244 } 2245 2246 Error BitcodeReader::parseTypeTable() { 2247 if (Error Err = Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW)) 2248 return Err; 2249 2250 return parseTypeTableBody(); 2251 } 2252 2253 Error BitcodeReader::parseTypeTableBody() { 2254 if (!TypeList.empty()) 2255 return error("Invalid multiple blocks"); 2256 2257 SmallVector<uint64_t, 64> Record; 2258 unsigned NumRecords = 0; 2259 2260 SmallString<64> TypeName; 2261 2262 // Read all the records for this type table. 2263 while (true) { 2264 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); 2265 if (!MaybeEntry) 2266 return MaybeEntry.takeError(); 2267 BitstreamEntry Entry = MaybeEntry.get(); 2268 2269 switch (Entry.Kind) { 2270 case BitstreamEntry::SubBlock: // Handled for us already. 2271 case BitstreamEntry::Error: 2272 return error("Malformed block"); 2273 case BitstreamEntry::EndBlock: 2274 if (NumRecords != TypeList.size()) 2275 return error("Malformed block"); 2276 return Error::success(); 2277 case BitstreamEntry::Record: 2278 // The interesting case. 2279 break; 2280 } 2281 2282 // Read a record. 2283 Record.clear(); 2284 Type *ResultTy = nullptr; 2285 SmallVector<unsigned> ContainedIDs; 2286 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record); 2287 if (!MaybeRecord) 2288 return MaybeRecord.takeError(); 2289 switch (MaybeRecord.get()) { 2290 default: 2291 return error("Invalid value"); 2292 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries] 2293 // TYPE_CODE_NUMENTRY contains a count of the number of types in the 2294 // type list. This allows us to reserve space. 2295 if (Record.empty()) 2296 return error("Invalid numentry record"); 2297 TypeList.resize(Record[0]); 2298 continue; 2299 case bitc::TYPE_CODE_VOID: // VOID 2300 ResultTy = Type::getVoidTy(Context); 2301 break; 2302 case bitc::TYPE_CODE_HALF: // HALF 2303 ResultTy = Type::getHalfTy(Context); 2304 break; 2305 case bitc::TYPE_CODE_BFLOAT: // BFLOAT 2306 ResultTy = Type::getBFloatTy(Context); 2307 break; 2308 case bitc::TYPE_CODE_FLOAT: // FLOAT 2309 ResultTy = Type::getFloatTy(Context); 2310 break; 2311 case bitc::TYPE_CODE_DOUBLE: // DOUBLE 2312 ResultTy = Type::getDoubleTy(Context); 2313 break; 2314 case bitc::TYPE_CODE_X86_FP80: // X86_FP80 2315 ResultTy = Type::getX86_FP80Ty(Context); 2316 break; 2317 case bitc::TYPE_CODE_FP128: // FP128 2318 ResultTy = Type::getFP128Ty(Context); 2319 break; 2320 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128 2321 ResultTy = Type::getPPC_FP128Ty(Context); 2322 break; 2323 case bitc::TYPE_CODE_LABEL: // LABEL 2324 ResultTy = Type::getLabelTy(Context); 2325 break; 2326 case bitc::TYPE_CODE_METADATA: // METADATA 2327 ResultTy = Type::getMetadataTy(Context); 2328 break; 2329 case bitc::TYPE_CODE_X86_MMX: // X86_MMX 2330 ResultTy = Type::getX86_MMXTy(Context); 2331 break; 2332 case bitc::TYPE_CODE_X86_AMX: // X86_AMX 2333 ResultTy = Type::getX86_AMXTy(Context); 2334 break; 2335 case bitc::TYPE_CODE_TOKEN: // TOKEN 2336 ResultTy = Type::getTokenTy(Context); 2337 break; 2338 case bitc::TYPE_CODE_INTEGER: { // INTEGER: [width] 2339 if (Record.empty()) 2340 return error("Invalid integer record"); 2341 2342 uint64_t NumBits = Record[0]; 2343 if (NumBits < IntegerType::MIN_INT_BITS || 2344 NumBits > IntegerType::MAX_INT_BITS) 2345 return error("Bitwidth for integer type out of range"); 2346 ResultTy = IntegerType::get(Context, NumBits); 2347 break; 2348 } 2349 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or 2350 // [pointee type, address space] 2351 if (Record.empty()) 2352 return error("Invalid pointer record"); 2353 unsigned AddressSpace = 0; 2354 if (Record.size() == 2) 2355 AddressSpace = Record[1]; 2356 ResultTy = getTypeByID(Record[0]); 2357 if (!ResultTy || 2358 !PointerType::isValidElementType(ResultTy)) 2359 return error("Invalid type"); 2360 ContainedIDs.push_back(Record[0]); 2361 ResultTy = PointerType::get(ResultTy, AddressSpace); 2362 break; 2363 } 2364 case bitc::TYPE_CODE_OPAQUE_POINTER: { // OPAQUE_POINTER: [addrspace] 2365 if (Record.size() != 1) 2366 return error("Invalid opaque pointer record"); 2367 unsigned AddressSpace = Record[0]; 2368 ResultTy = PointerType::get(Context, AddressSpace); 2369 break; 2370 } 2371 case bitc::TYPE_CODE_FUNCTION_OLD: { 2372 // Deprecated, but still needed to read old bitcode files. 2373 // FUNCTION: [vararg, attrid, retty, paramty x N] 2374 if (Record.size() < 3) 2375 return error("Invalid function record"); 2376 SmallVector<Type*, 8> ArgTys; 2377 for (unsigned i = 3, e = Record.size(); i != e; ++i) { 2378 if (Type *T = getTypeByID(Record[i])) 2379 ArgTys.push_back(T); 2380 else 2381 break; 2382 } 2383 2384 ResultTy = getTypeByID(Record[2]); 2385 if (!ResultTy || ArgTys.size() < Record.size()-3) 2386 return error("Invalid type"); 2387 2388 ContainedIDs.append(Record.begin() + 2, Record.end()); 2389 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]); 2390 break; 2391 } 2392 case bitc::TYPE_CODE_FUNCTION: { 2393 // FUNCTION: [vararg, retty, paramty x N] 2394 if (Record.size() < 2) 2395 return error("Invalid function record"); 2396 SmallVector<Type*, 8> ArgTys; 2397 for (unsigned i = 2, e = Record.size(); i != e; ++i) { 2398 if (Type *T = getTypeByID(Record[i])) { 2399 if (!FunctionType::isValidArgumentType(T)) 2400 return error("Invalid function argument type"); 2401 ArgTys.push_back(T); 2402 } 2403 else 2404 break; 2405 } 2406 2407 ResultTy = getTypeByID(Record[1]); 2408 if (!ResultTy || ArgTys.size() < Record.size()-2) 2409 return error("Invalid type"); 2410 2411 ContainedIDs.append(Record.begin() + 1, Record.end()); 2412 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]); 2413 break; 2414 } 2415 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N] 2416 if (Record.empty()) 2417 return error("Invalid anon struct record"); 2418 SmallVector<Type*, 8> EltTys; 2419 for (unsigned i = 1, e = Record.size(); i != e; ++i) { 2420 if (Type *T = getTypeByID(Record[i])) 2421 EltTys.push_back(T); 2422 else 2423 break; 2424 } 2425 if (EltTys.size() != Record.size()-1) 2426 return error("Invalid type"); 2427 ContainedIDs.append(Record.begin() + 1, Record.end()); 2428 ResultTy = StructType::get(Context, EltTys, Record[0]); 2429 break; 2430 } 2431 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N] 2432 if (convertToString(Record, 0, TypeName)) 2433 return error("Invalid struct name record"); 2434 continue; 2435 2436 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N] 2437 if (Record.empty()) 2438 return error("Invalid named struct record"); 2439 2440 if (NumRecords >= TypeList.size()) 2441 return error("Invalid TYPE table"); 2442 2443 // Check to see if this was forward referenced, if so fill in the temp. 2444 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]); 2445 if (Res) { 2446 Res->setName(TypeName); 2447 TypeList[NumRecords] = nullptr; 2448 } else // Otherwise, create a new struct. 2449 Res = createIdentifiedStructType(Context, TypeName); 2450 TypeName.clear(); 2451 2452 SmallVector<Type*, 8> EltTys; 2453 for (unsigned i = 1, e = Record.size(); i != e; ++i) { 2454 if (Type *T = getTypeByID(Record[i])) 2455 EltTys.push_back(T); 2456 else 2457 break; 2458 } 2459 if (EltTys.size() != Record.size()-1) 2460 return error("Invalid named struct record"); 2461 Res->setBody(EltTys, Record[0]); 2462 ContainedIDs.append(Record.begin() + 1, Record.end()); 2463 ResultTy = Res; 2464 break; 2465 } 2466 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: [] 2467 if (Record.size() != 1) 2468 return error("Invalid opaque type record"); 2469 2470 if (NumRecords >= TypeList.size()) 2471 return error("Invalid TYPE table"); 2472 2473 // Check to see if this was forward referenced, if so fill in the temp. 2474 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]); 2475 if (Res) { 2476 Res->setName(TypeName); 2477 TypeList[NumRecords] = nullptr; 2478 } else // Otherwise, create a new struct with no body. 2479 Res = createIdentifiedStructType(Context, TypeName); 2480 TypeName.clear(); 2481 ResultTy = Res; 2482 break; 2483 } 2484 case bitc::TYPE_CODE_TARGET_TYPE: { // TARGET_TYPE: [NumTy, Tys..., Ints...] 2485 if (Record.size() < 1) 2486 return error("Invalid target extension type record"); 2487 2488 if (NumRecords >= TypeList.size()) 2489 return error("Invalid TYPE table"); 2490 2491 if (Record[0] >= Record.size()) 2492 return error("Too many type parameters"); 2493 2494 unsigned NumTys = Record[0]; 2495 SmallVector<Type *, 4> TypeParams; 2496 SmallVector<unsigned, 8> IntParams; 2497 for (unsigned i = 0; i < NumTys; i++) { 2498 if (Type *T = getTypeByID(Record[i + 1])) 2499 TypeParams.push_back(T); 2500 else 2501 return error("Invalid type"); 2502 } 2503 2504 for (unsigned i = NumTys + 1, e = Record.size(); i < e; i++) { 2505 if (Record[i] > UINT_MAX) 2506 return error("Integer parameter too large"); 2507 IntParams.push_back(Record[i]); 2508 } 2509 ResultTy = TargetExtType::get(Context, TypeName, TypeParams, IntParams); 2510 TypeName.clear(); 2511 break; 2512 } 2513 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty] 2514 if (Record.size() < 2) 2515 return error("Invalid array type record"); 2516 ResultTy = getTypeByID(Record[1]); 2517 if (!ResultTy || !ArrayType::isValidElementType(ResultTy)) 2518 return error("Invalid type"); 2519 ContainedIDs.push_back(Record[1]); 2520 ResultTy = ArrayType::get(ResultTy, Record[0]); 2521 break; 2522 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty] or 2523 // [numelts, eltty, scalable] 2524 if (Record.size() < 2) 2525 return error("Invalid vector type record"); 2526 if (Record[0] == 0) 2527 return error("Invalid vector length"); 2528 ResultTy = getTypeByID(Record[1]); 2529 if (!ResultTy || !VectorType::isValidElementType(ResultTy)) 2530 return error("Invalid type"); 2531 bool Scalable = Record.size() > 2 ? Record[2] : false; 2532 ContainedIDs.push_back(Record[1]); 2533 ResultTy = VectorType::get(ResultTy, Record[0], Scalable); 2534 break; 2535 } 2536 2537 if (NumRecords >= TypeList.size()) 2538 return error("Invalid TYPE table"); 2539 if (TypeList[NumRecords]) 2540 return error( 2541 "Invalid TYPE table: Only named structs can be forward referenced"); 2542 assert(ResultTy && "Didn't read a type?"); 2543 TypeList[NumRecords] = ResultTy; 2544 if (!ContainedIDs.empty()) 2545 ContainedTypeIDs[NumRecords] = std::move(ContainedIDs); 2546 ++NumRecords; 2547 } 2548 } 2549 2550 Error BitcodeReader::parseOperandBundleTags() { 2551 if (Error Err = Stream.EnterSubBlock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID)) 2552 return Err; 2553 2554 if (!BundleTags.empty()) 2555 return error("Invalid multiple blocks"); 2556 2557 SmallVector<uint64_t, 64> Record; 2558 2559 while (true) { 2560 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); 2561 if (!MaybeEntry) 2562 return MaybeEntry.takeError(); 2563 BitstreamEntry Entry = MaybeEntry.get(); 2564 2565 switch (Entry.Kind) { 2566 case BitstreamEntry::SubBlock: // Handled for us already. 2567 case BitstreamEntry::Error: 2568 return error("Malformed block"); 2569 case BitstreamEntry::EndBlock: 2570 return Error::success(); 2571 case BitstreamEntry::Record: 2572 // The interesting case. 2573 break; 2574 } 2575 2576 // Tags are implicitly mapped to integers by their order. 2577 2578 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record); 2579 if (!MaybeRecord) 2580 return MaybeRecord.takeError(); 2581 if (MaybeRecord.get() != bitc::OPERAND_BUNDLE_TAG) 2582 return error("Invalid operand bundle record"); 2583 2584 // OPERAND_BUNDLE_TAG: [strchr x N] 2585 BundleTags.emplace_back(); 2586 if (convertToString(Record, 0, BundleTags.back())) 2587 return error("Invalid operand bundle record"); 2588 Record.clear(); 2589 } 2590 } 2591 2592 Error BitcodeReader::parseSyncScopeNames() { 2593 if (Error Err = Stream.EnterSubBlock(bitc::SYNC_SCOPE_NAMES_BLOCK_ID)) 2594 return Err; 2595 2596 if (!SSIDs.empty()) 2597 return error("Invalid multiple synchronization scope names blocks"); 2598 2599 SmallVector<uint64_t, 64> Record; 2600 while (true) { 2601 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); 2602 if (!MaybeEntry) 2603 return MaybeEntry.takeError(); 2604 BitstreamEntry Entry = MaybeEntry.get(); 2605 2606 switch (Entry.Kind) { 2607 case BitstreamEntry::SubBlock: // Handled for us already. 2608 case BitstreamEntry::Error: 2609 return error("Malformed block"); 2610 case BitstreamEntry::EndBlock: 2611 if (SSIDs.empty()) 2612 return error("Invalid empty synchronization scope names block"); 2613 return Error::success(); 2614 case BitstreamEntry::Record: 2615 // The interesting case. 2616 break; 2617 } 2618 2619 // Synchronization scope names are implicitly mapped to synchronization 2620 // scope IDs by their order. 2621 2622 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record); 2623 if (!MaybeRecord) 2624 return MaybeRecord.takeError(); 2625 if (MaybeRecord.get() != bitc::SYNC_SCOPE_NAME) 2626 return error("Invalid sync scope record"); 2627 2628 SmallString<16> SSN; 2629 if (convertToString(Record, 0, SSN)) 2630 return error("Invalid sync scope record"); 2631 2632 SSIDs.push_back(Context.getOrInsertSyncScopeID(SSN)); 2633 Record.clear(); 2634 } 2635 } 2636 2637 /// Associate a value with its name from the given index in the provided record. 2638 Expected<Value *> BitcodeReader::recordValue(SmallVectorImpl<uint64_t> &Record, 2639 unsigned NameIndex, Triple &TT) { 2640 SmallString<128> ValueName; 2641 if (convertToString(Record, NameIndex, ValueName)) 2642 return error("Invalid record"); 2643 unsigned ValueID = Record[0]; 2644 if (ValueID >= ValueList.size() || !ValueList[ValueID]) 2645 return error("Invalid record"); 2646 Value *V = ValueList[ValueID]; 2647 2648 StringRef NameStr(ValueName.data(), ValueName.size()); 2649 if (NameStr.contains(0)) 2650 return error("Invalid value name"); 2651 V->setName(NameStr); 2652 auto *GO = dyn_cast<GlobalObject>(V); 2653 if (GO && ImplicitComdatObjects.contains(GO) && TT.supportsCOMDAT()) 2654 GO->setComdat(TheModule->getOrInsertComdat(V->getName())); 2655 return V; 2656 } 2657 2658 /// Helper to note and return the current location, and jump to the given 2659 /// offset. 2660 static Expected<uint64_t> jumpToValueSymbolTable(uint64_t Offset, 2661 BitstreamCursor &Stream) { 2662 // Save the current parsing location so we can jump back at the end 2663 // of the VST read. 2664 uint64_t CurrentBit = Stream.GetCurrentBitNo(); 2665 if (Error JumpFailed = Stream.JumpToBit(Offset * 32)) 2666 return std::move(JumpFailed); 2667 Expected<BitstreamEntry> MaybeEntry = Stream.advance(); 2668 if (!MaybeEntry) 2669 return MaybeEntry.takeError(); 2670 if (MaybeEntry.get().Kind != BitstreamEntry::SubBlock || 2671 MaybeEntry.get().ID != bitc::VALUE_SYMTAB_BLOCK_ID) 2672 return error("Expected value symbol table subblock"); 2673 return CurrentBit; 2674 } 2675 2676 void BitcodeReader::setDeferredFunctionInfo(unsigned FuncBitcodeOffsetDelta, 2677 Function *F, 2678 ArrayRef<uint64_t> Record) { 2679 // Note that we subtract 1 here because the offset is relative to one word 2680 // before the start of the identification or module block, which was 2681 // historically always the start of the regular bitcode header. 2682 uint64_t FuncWordOffset = Record[1] - 1; 2683 uint64_t FuncBitOffset = FuncWordOffset * 32; 2684 DeferredFunctionInfo[F] = FuncBitOffset + FuncBitcodeOffsetDelta; 2685 // Set the LastFunctionBlockBit to point to the last function block. 2686 // Later when parsing is resumed after function materialization, 2687 // we can simply skip that last function block. 2688 if (FuncBitOffset > LastFunctionBlockBit) 2689 LastFunctionBlockBit = FuncBitOffset; 2690 } 2691 2692 /// Read a new-style GlobalValue symbol table. 2693 Error BitcodeReader::parseGlobalValueSymbolTable() { 2694 unsigned FuncBitcodeOffsetDelta = 2695 Stream.getAbbrevIDWidth() + bitc::BlockIDWidth; 2696 2697 if (Error Err = Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID)) 2698 return Err; 2699 2700 SmallVector<uint64_t, 64> Record; 2701 while (true) { 2702 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); 2703 if (!MaybeEntry) 2704 return MaybeEntry.takeError(); 2705 BitstreamEntry Entry = MaybeEntry.get(); 2706 2707 switch (Entry.Kind) { 2708 case BitstreamEntry::SubBlock: 2709 case BitstreamEntry::Error: 2710 return error("Malformed block"); 2711 case BitstreamEntry::EndBlock: 2712 return Error::success(); 2713 case BitstreamEntry::Record: 2714 break; 2715 } 2716 2717 Record.clear(); 2718 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record); 2719 if (!MaybeRecord) 2720 return MaybeRecord.takeError(); 2721 switch (MaybeRecord.get()) { 2722 case bitc::VST_CODE_FNENTRY: { // [valueid, offset] 2723 unsigned ValueID = Record[0]; 2724 if (ValueID >= ValueList.size() || !ValueList[ValueID]) 2725 return error("Invalid value reference in symbol table"); 2726 setDeferredFunctionInfo(FuncBitcodeOffsetDelta, 2727 cast<Function>(ValueList[ValueID]), Record); 2728 break; 2729 } 2730 } 2731 } 2732 } 2733 2734 /// Parse the value symbol table at either the current parsing location or 2735 /// at the given bit offset if provided. 2736 Error BitcodeReader::parseValueSymbolTable(uint64_t Offset) { 2737 uint64_t CurrentBit; 2738 // Pass in the Offset to distinguish between calling for the module-level 2739 // VST (where we want to jump to the VST offset) and the function-level 2740 // VST (where we don't). 2741 if (Offset > 0) { 2742 Expected<uint64_t> MaybeCurrentBit = jumpToValueSymbolTable(Offset, Stream); 2743 if (!MaybeCurrentBit) 2744 return MaybeCurrentBit.takeError(); 2745 CurrentBit = MaybeCurrentBit.get(); 2746 // If this module uses a string table, read this as a module-level VST. 2747 if (UseStrtab) { 2748 if (Error Err = parseGlobalValueSymbolTable()) 2749 return Err; 2750 if (Error JumpFailed = Stream.JumpToBit(CurrentBit)) 2751 return JumpFailed; 2752 return Error::success(); 2753 } 2754 // Otherwise, the VST will be in a similar format to a function-level VST, 2755 // and will contain symbol names. 2756 } 2757 2758 // Compute the delta between the bitcode indices in the VST (the word offset 2759 // to the word-aligned ENTER_SUBBLOCK for the function block, and that 2760 // expected by the lazy reader. The reader's EnterSubBlock expects to have 2761 // already read the ENTER_SUBBLOCK code (size getAbbrevIDWidth) and BlockID 2762 // (size BlockIDWidth). Note that we access the stream's AbbrevID width here 2763 // just before entering the VST subblock because: 1) the EnterSubBlock 2764 // changes the AbbrevID width; 2) the VST block is nested within the same 2765 // outer MODULE_BLOCK as the FUNCTION_BLOCKs and therefore have the same 2766 // AbbrevID width before calling EnterSubBlock; and 3) when we want to 2767 // jump to the FUNCTION_BLOCK using this offset later, we don't want 2768 // to rely on the stream's AbbrevID width being that of the MODULE_BLOCK. 2769 unsigned FuncBitcodeOffsetDelta = 2770 Stream.getAbbrevIDWidth() + bitc::BlockIDWidth; 2771 2772 if (Error Err = Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID)) 2773 return Err; 2774 2775 SmallVector<uint64_t, 64> Record; 2776 2777 Triple TT(TheModule->getTargetTriple()); 2778 2779 // Read all the records for this value table. 2780 SmallString<128> ValueName; 2781 2782 while (true) { 2783 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); 2784 if (!MaybeEntry) 2785 return MaybeEntry.takeError(); 2786 BitstreamEntry Entry = MaybeEntry.get(); 2787 2788 switch (Entry.Kind) { 2789 case BitstreamEntry::SubBlock: // Handled for us already. 2790 case BitstreamEntry::Error: 2791 return error("Malformed block"); 2792 case BitstreamEntry::EndBlock: 2793 if (Offset > 0) 2794 if (Error JumpFailed = Stream.JumpToBit(CurrentBit)) 2795 return JumpFailed; 2796 return Error::success(); 2797 case BitstreamEntry::Record: 2798 // The interesting case. 2799 break; 2800 } 2801 2802 // Read a record. 2803 Record.clear(); 2804 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record); 2805 if (!MaybeRecord) 2806 return MaybeRecord.takeError(); 2807 switch (MaybeRecord.get()) { 2808 default: // Default behavior: unknown type. 2809 break; 2810 case bitc::VST_CODE_ENTRY: { // VST_CODE_ENTRY: [valueid, namechar x N] 2811 Expected<Value *> ValOrErr = recordValue(Record, 1, TT); 2812 if (Error Err = ValOrErr.takeError()) 2813 return Err; 2814 ValOrErr.get(); 2815 break; 2816 } 2817 case bitc::VST_CODE_FNENTRY: { 2818 // VST_CODE_FNENTRY: [valueid, offset, namechar x N] 2819 Expected<Value *> ValOrErr = recordValue(Record, 2, TT); 2820 if (Error Err = ValOrErr.takeError()) 2821 return Err; 2822 Value *V = ValOrErr.get(); 2823 2824 // Ignore function offsets emitted for aliases of functions in older 2825 // versions of LLVM. 2826 if (auto *F = dyn_cast<Function>(V)) 2827 setDeferredFunctionInfo(FuncBitcodeOffsetDelta, F, Record); 2828 break; 2829 } 2830 case bitc::VST_CODE_BBENTRY: { 2831 if (convertToString(Record, 1, ValueName)) 2832 return error("Invalid bbentry record"); 2833 BasicBlock *BB = getBasicBlock(Record[0]); 2834 if (!BB) 2835 return error("Invalid bbentry record"); 2836 2837 BB->setName(StringRef(ValueName.data(), ValueName.size())); 2838 ValueName.clear(); 2839 break; 2840 } 2841 } 2842 } 2843 } 2844 2845 /// Decode a signed value stored with the sign bit in the LSB for dense VBR 2846 /// encoding. 2847 uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) { 2848 if ((V & 1) == 0) 2849 return V >> 1; 2850 if (V != 1) 2851 return -(V >> 1); 2852 // There is no such thing as -0 with integers. "-0" really means MININT. 2853 return 1ULL << 63; 2854 } 2855 2856 /// Resolve all of the initializers for global values and aliases that we can. 2857 Error BitcodeReader::resolveGlobalAndIndirectSymbolInits() { 2858 std::vector<std::pair<GlobalVariable *, unsigned>> GlobalInitWorklist; 2859 std::vector<std::pair<GlobalValue *, unsigned>> IndirectSymbolInitWorklist; 2860 std::vector<FunctionOperandInfo> FunctionOperandWorklist; 2861 2862 GlobalInitWorklist.swap(GlobalInits); 2863 IndirectSymbolInitWorklist.swap(IndirectSymbolInits); 2864 FunctionOperandWorklist.swap(FunctionOperands); 2865 2866 while (!GlobalInitWorklist.empty()) { 2867 unsigned ValID = GlobalInitWorklist.back().second; 2868 if (ValID >= ValueList.size()) { 2869 // Not ready to resolve this yet, it requires something later in the file. 2870 GlobalInits.push_back(GlobalInitWorklist.back()); 2871 } else { 2872 Expected<Constant *> MaybeC = getValueForInitializer(ValID); 2873 if (!MaybeC) 2874 return MaybeC.takeError(); 2875 GlobalInitWorklist.back().first->setInitializer(MaybeC.get()); 2876 } 2877 GlobalInitWorklist.pop_back(); 2878 } 2879 2880 while (!IndirectSymbolInitWorklist.empty()) { 2881 unsigned ValID = IndirectSymbolInitWorklist.back().second; 2882 if (ValID >= ValueList.size()) { 2883 IndirectSymbolInits.push_back(IndirectSymbolInitWorklist.back()); 2884 } else { 2885 Expected<Constant *> MaybeC = getValueForInitializer(ValID); 2886 if (!MaybeC) 2887 return MaybeC.takeError(); 2888 Constant *C = MaybeC.get(); 2889 GlobalValue *GV = IndirectSymbolInitWorklist.back().first; 2890 if (auto *GA = dyn_cast<GlobalAlias>(GV)) { 2891 if (C->getType() != GV->getType()) 2892 return error("Alias and aliasee types don't match"); 2893 GA->setAliasee(C); 2894 } else if (auto *GI = dyn_cast<GlobalIFunc>(GV)) { 2895 Type *ResolverFTy = 2896 GlobalIFunc::getResolverFunctionType(GI->getValueType()); 2897 // Transparently fix up the type for compatibility with older bitcode 2898 GI->setResolver(ConstantExpr::getBitCast( 2899 C, ResolverFTy->getPointerTo(GI->getAddressSpace()))); 2900 } else { 2901 return error("Expected an alias or an ifunc"); 2902 } 2903 } 2904 IndirectSymbolInitWorklist.pop_back(); 2905 } 2906 2907 while (!FunctionOperandWorklist.empty()) { 2908 FunctionOperandInfo &Info = FunctionOperandWorklist.back(); 2909 if (Info.PersonalityFn) { 2910 unsigned ValID = Info.PersonalityFn - 1; 2911 if (ValID < ValueList.size()) { 2912 Expected<Constant *> MaybeC = getValueForInitializer(ValID); 2913 if (!MaybeC) 2914 return MaybeC.takeError(); 2915 Info.F->setPersonalityFn(MaybeC.get()); 2916 Info.PersonalityFn = 0; 2917 } 2918 } 2919 if (Info.Prefix) { 2920 unsigned ValID = Info.Prefix - 1; 2921 if (ValID < ValueList.size()) { 2922 Expected<Constant *> MaybeC = getValueForInitializer(ValID); 2923 if (!MaybeC) 2924 return MaybeC.takeError(); 2925 Info.F->setPrefixData(MaybeC.get()); 2926 Info.Prefix = 0; 2927 } 2928 } 2929 if (Info.Prologue) { 2930 unsigned ValID = Info.Prologue - 1; 2931 if (ValID < ValueList.size()) { 2932 Expected<Constant *> MaybeC = getValueForInitializer(ValID); 2933 if (!MaybeC) 2934 return MaybeC.takeError(); 2935 Info.F->setPrologueData(MaybeC.get()); 2936 Info.Prologue = 0; 2937 } 2938 } 2939 if (Info.PersonalityFn || Info.Prefix || Info.Prologue) 2940 FunctionOperands.push_back(Info); 2941 FunctionOperandWorklist.pop_back(); 2942 } 2943 2944 return Error::success(); 2945 } 2946 2947 APInt llvm::readWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) { 2948 SmallVector<uint64_t, 8> Words(Vals.size()); 2949 transform(Vals, Words.begin(), 2950 BitcodeReader::decodeSignRotatedValue); 2951 2952 return APInt(TypeBits, Words); 2953 } 2954 2955 Error BitcodeReader::parseConstants() { 2956 if (Error Err = Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID)) 2957 return Err; 2958 2959 SmallVector<uint64_t, 64> Record; 2960 2961 // Read all the records for this value table. 2962 Type *CurTy = Type::getInt32Ty(Context); 2963 unsigned Int32TyID = getVirtualTypeID(CurTy); 2964 unsigned CurTyID = Int32TyID; 2965 Type *CurElemTy = nullptr; 2966 unsigned NextCstNo = ValueList.size(); 2967 2968 while (true) { 2969 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); 2970 if (!MaybeEntry) 2971 return MaybeEntry.takeError(); 2972 BitstreamEntry Entry = MaybeEntry.get(); 2973 2974 switch (Entry.Kind) { 2975 case BitstreamEntry::SubBlock: // Handled for us already. 2976 case BitstreamEntry::Error: 2977 return error("Malformed block"); 2978 case BitstreamEntry::EndBlock: 2979 if (NextCstNo != ValueList.size()) 2980 return error("Invalid constant reference"); 2981 return Error::success(); 2982 case BitstreamEntry::Record: 2983 // The interesting case. 2984 break; 2985 } 2986 2987 // Read a record. 2988 Record.clear(); 2989 Type *VoidType = Type::getVoidTy(Context); 2990 Value *V = nullptr; 2991 Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record); 2992 if (!MaybeBitCode) 2993 return MaybeBitCode.takeError(); 2994 switch (unsigned BitCode = MaybeBitCode.get()) { 2995 default: // Default behavior: unknown constant 2996 case bitc::CST_CODE_UNDEF: // UNDEF 2997 V = UndefValue::get(CurTy); 2998 break; 2999 case bitc::CST_CODE_POISON: // POISON 3000 V = PoisonValue::get(CurTy); 3001 break; 3002 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid] 3003 if (Record.empty()) 3004 return error("Invalid settype record"); 3005 if (Record[0] >= TypeList.size() || !TypeList[Record[0]]) 3006 return error("Invalid settype record"); 3007 if (TypeList[Record[0]] == VoidType) 3008 return error("Invalid constant type"); 3009 CurTyID = Record[0]; 3010 CurTy = TypeList[CurTyID]; 3011 CurElemTy = getPtrElementTypeByID(CurTyID); 3012 continue; // Skip the ValueList manipulation. 3013 case bitc::CST_CODE_NULL: // NULL 3014 if (CurTy->isVoidTy() || CurTy->isFunctionTy() || CurTy->isLabelTy()) 3015 return error("Invalid type for a constant null value"); 3016 if (auto *TETy = dyn_cast<TargetExtType>(CurTy)) 3017 if (!TETy->hasProperty(TargetExtType::HasZeroInit)) 3018 return error("Invalid type for a constant null value"); 3019 V = Constant::getNullValue(CurTy); 3020 break; 3021 case bitc::CST_CODE_INTEGER: // INTEGER: [intval] 3022 if (!CurTy->isIntegerTy() || Record.empty()) 3023 return error("Invalid integer const record"); 3024 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0])); 3025 break; 3026 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval] 3027 if (!CurTy->isIntegerTy() || Record.empty()) 3028 return error("Invalid wide integer const record"); 3029 3030 APInt VInt = 3031 readWideAPInt(Record, cast<IntegerType>(CurTy)->getBitWidth()); 3032 V = ConstantInt::get(Context, VInt); 3033 3034 break; 3035 } 3036 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval] 3037 if (Record.empty()) 3038 return error("Invalid float const record"); 3039 if (CurTy->isHalfTy()) 3040 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf(), 3041 APInt(16, (uint16_t)Record[0]))); 3042 else if (CurTy->isBFloatTy()) 3043 V = ConstantFP::get(Context, APFloat(APFloat::BFloat(), 3044 APInt(16, (uint32_t)Record[0]))); 3045 else if (CurTy->isFloatTy()) 3046 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle(), 3047 APInt(32, (uint32_t)Record[0]))); 3048 else if (CurTy->isDoubleTy()) 3049 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble(), 3050 APInt(64, Record[0]))); 3051 else if (CurTy->isX86_FP80Ty()) { 3052 // Bits are not stored the same way as a normal i80 APInt, compensate. 3053 uint64_t Rearrange[2]; 3054 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16); 3055 Rearrange[1] = Record[0] >> 48; 3056 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended(), 3057 APInt(80, Rearrange))); 3058 } else if (CurTy->isFP128Ty()) 3059 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad(), 3060 APInt(128, Record))); 3061 else if (CurTy->isPPC_FP128Ty()) 3062 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble(), 3063 APInt(128, Record))); 3064 else 3065 V = UndefValue::get(CurTy); 3066 break; 3067 } 3068 3069 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number] 3070 if (Record.empty()) 3071 return error("Invalid aggregate record"); 3072 3073 unsigned Size = Record.size(); 3074 SmallVector<unsigned, 16> Elts; 3075 for (unsigned i = 0; i != Size; ++i) 3076 Elts.push_back(Record[i]); 3077 3078 if (isa<StructType>(CurTy)) { 3079 V = BitcodeConstant::create( 3080 Alloc, CurTy, BitcodeConstant::ConstantStructOpcode, Elts); 3081 } else if (isa<ArrayType>(CurTy)) { 3082 V = BitcodeConstant::create(Alloc, CurTy, 3083 BitcodeConstant::ConstantArrayOpcode, Elts); 3084 } else if (isa<VectorType>(CurTy)) { 3085 V = BitcodeConstant::create( 3086 Alloc, CurTy, BitcodeConstant::ConstantVectorOpcode, Elts); 3087 } else { 3088 V = UndefValue::get(CurTy); 3089 } 3090 break; 3091 } 3092 case bitc::CST_CODE_STRING: // STRING: [values] 3093 case bitc::CST_CODE_CSTRING: { // CSTRING: [values] 3094 if (Record.empty()) 3095 return error("Invalid string record"); 3096 3097 SmallString<16> Elts(Record.begin(), Record.end()); 3098 V = ConstantDataArray::getString(Context, Elts, 3099 BitCode == bitc::CST_CODE_CSTRING); 3100 break; 3101 } 3102 case bitc::CST_CODE_DATA: {// DATA: [n x value] 3103 if (Record.empty()) 3104 return error("Invalid data record"); 3105 3106 Type *EltTy; 3107 if (auto *Array = dyn_cast<ArrayType>(CurTy)) 3108 EltTy = Array->getElementType(); 3109 else 3110 EltTy = cast<VectorType>(CurTy)->getElementType(); 3111 if (EltTy->isIntegerTy(8)) { 3112 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end()); 3113 if (isa<VectorType>(CurTy)) 3114 V = ConstantDataVector::get(Context, Elts); 3115 else 3116 V = ConstantDataArray::get(Context, Elts); 3117 } else if (EltTy->isIntegerTy(16)) { 3118 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end()); 3119 if (isa<VectorType>(CurTy)) 3120 V = ConstantDataVector::get(Context, Elts); 3121 else 3122 V = ConstantDataArray::get(Context, Elts); 3123 } else if (EltTy->isIntegerTy(32)) { 3124 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end()); 3125 if (isa<VectorType>(CurTy)) 3126 V = ConstantDataVector::get(Context, Elts); 3127 else 3128 V = ConstantDataArray::get(Context, Elts); 3129 } else if (EltTy->isIntegerTy(64)) { 3130 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end()); 3131 if (isa<VectorType>(CurTy)) 3132 V = ConstantDataVector::get(Context, Elts); 3133 else 3134 V = ConstantDataArray::get(Context, Elts); 3135 } else if (EltTy->isHalfTy()) { 3136 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end()); 3137 if (isa<VectorType>(CurTy)) 3138 V = ConstantDataVector::getFP(EltTy, Elts); 3139 else 3140 V = ConstantDataArray::getFP(EltTy, Elts); 3141 } else if (EltTy->isBFloatTy()) { 3142 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end()); 3143 if (isa<VectorType>(CurTy)) 3144 V = ConstantDataVector::getFP(EltTy, Elts); 3145 else 3146 V = ConstantDataArray::getFP(EltTy, Elts); 3147 } else if (EltTy->isFloatTy()) { 3148 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end()); 3149 if (isa<VectorType>(CurTy)) 3150 V = ConstantDataVector::getFP(EltTy, Elts); 3151 else 3152 V = ConstantDataArray::getFP(EltTy, Elts); 3153 } else if (EltTy->isDoubleTy()) { 3154 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end()); 3155 if (isa<VectorType>(CurTy)) 3156 V = ConstantDataVector::getFP(EltTy, Elts); 3157 else 3158 V = ConstantDataArray::getFP(EltTy, Elts); 3159 } else { 3160 return error("Invalid type for value"); 3161 } 3162 break; 3163 } 3164 case bitc::CST_CODE_CE_UNOP: { // CE_UNOP: [opcode, opval] 3165 if (Record.size() < 2) 3166 return error("Invalid unary op constexpr record"); 3167 int Opc = getDecodedUnaryOpcode(Record[0], CurTy); 3168 if (Opc < 0) { 3169 V = UndefValue::get(CurTy); // Unknown unop. 3170 } else { 3171 V = BitcodeConstant::create(Alloc, CurTy, Opc, (unsigned)Record[1]); 3172 } 3173 break; 3174 } 3175 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval] 3176 if (Record.size() < 3) 3177 return error("Invalid binary op constexpr record"); 3178 int Opc = getDecodedBinaryOpcode(Record[0], CurTy); 3179 if (Opc < 0) { 3180 V = UndefValue::get(CurTy); // Unknown binop. 3181 } else { 3182 uint8_t Flags = 0; 3183 if (Record.size() >= 4) { 3184 if (Opc == Instruction::Add || 3185 Opc == Instruction::Sub || 3186 Opc == Instruction::Mul || 3187 Opc == Instruction::Shl) { 3188 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP)) 3189 Flags |= OverflowingBinaryOperator::NoSignedWrap; 3190 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP)) 3191 Flags |= OverflowingBinaryOperator::NoUnsignedWrap; 3192 } else if (Opc == Instruction::SDiv || 3193 Opc == Instruction::UDiv || 3194 Opc == Instruction::LShr || 3195 Opc == Instruction::AShr) { 3196 if (Record[3] & (1 << bitc::PEO_EXACT)) 3197 Flags |= PossiblyExactOperator::IsExact; 3198 } 3199 } 3200 V = BitcodeConstant::create(Alloc, CurTy, {(uint8_t)Opc, Flags}, 3201 {(unsigned)Record[1], (unsigned)Record[2]}); 3202 } 3203 break; 3204 } 3205 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval] 3206 if (Record.size() < 3) 3207 return error("Invalid cast constexpr record"); 3208 int Opc = getDecodedCastOpcode(Record[0]); 3209 if (Opc < 0) { 3210 V = UndefValue::get(CurTy); // Unknown cast. 3211 } else { 3212 unsigned OpTyID = Record[1]; 3213 Type *OpTy = getTypeByID(OpTyID); 3214 if (!OpTy) 3215 return error("Invalid cast constexpr record"); 3216 V = BitcodeConstant::create(Alloc, CurTy, Opc, (unsigned)Record[2]); 3217 } 3218 break; 3219 } 3220 case bitc::CST_CODE_CE_INBOUNDS_GEP: // [ty, n x operands] 3221 case bitc::CST_CODE_CE_GEP: // [ty, n x operands] 3222 case bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX: { // [ty, flags, n x 3223 // operands] 3224 if (Record.size() < 2) 3225 return error("Constant GEP record must have at least two elements"); 3226 unsigned OpNum = 0; 3227 Type *PointeeType = nullptr; 3228 if (BitCode == bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX || 3229 Record.size() % 2) 3230 PointeeType = getTypeByID(Record[OpNum++]); 3231 3232 bool InBounds = false; 3233 std::optional<unsigned> InRangeIndex; 3234 if (BitCode == bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX) { 3235 uint64_t Op = Record[OpNum++]; 3236 InBounds = Op & 1; 3237 InRangeIndex = Op >> 1; 3238 } else if (BitCode == bitc::CST_CODE_CE_INBOUNDS_GEP) 3239 InBounds = true; 3240 3241 SmallVector<unsigned, 16> Elts; 3242 unsigned BaseTypeID = Record[OpNum]; 3243 while (OpNum != Record.size()) { 3244 unsigned ElTyID = Record[OpNum++]; 3245 Type *ElTy = getTypeByID(ElTyID); 3246 if (!ElTy) 3247 return error("Invalid getelementptr constexpr record"); 3248 Elts.push_back(Record[OpNum++]); 3249 } 3250 3251 if (Elts.size() < 1) 3252 return error("Invalid gep with no operands"); 3253 3254 Type *BaseType = getTypeByID(BaseTypeID); 3255 if (isa<VectorType>(BaseType)) { 3256 BaseTypeID = getContainedTypeID(BaseTypeID, 0); 3257 BaseType = getTypeByID(BaseTypeID); 3258 } 3259 3260 PointerType *OrigPtrTy = dyn_cast_or_null<PointerType>(BaseType); 3261 if (!OrigPtrTy) 3262 return error("GEP base operand must be pointer or vector of pointer"); 3263 3264 if (!PointeeType) { 3265 PointeeType = getPtrElementTypeByID(BaseTypeID); 3266 if (!PointeeType) 3267 return error("Missing element type for old-style constant GEP"); 3268 } 3269 3270 V = BitcodeConstant::create(Alloc, CurTy, 3271 {Instruction::GetElementPtr, InBounds, 3272 InRangeIndex.value_or(-1), PointeeType}, 3273 Elts); 3274 break; 3275 } 3276 case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#] 3277 if (Record.size() < 3) 3278 return error("Invalid select constexpr record"); 3279 3280 V = BitcodeConstant::create( 3281 Alloc, CurTy, Instruction::Select, 3282 {(unsigned)Record[0], (unsigned)Record[1], (unsigned)Record[2]}); 3283 break; 3284 } 3285 case bitc::CST_CODE_CE_EXTRACTELT 3286 : { // CE_EXTRACTELT: [opty, opval, opty, opval] 3287 if (Record.size() < 3) 3288 return error("Invalid extractelement constexpr record"); 3289 unsigned OpTyID = Record[0]; 3290 VectorType *OpTy = 3291 dyn_cast_or_null<VectorType>(getTypeByID(OpTyID)); 3292 if (!OpTy) 3293 return error("Invalid extractelement constexpr record"); 3294 unsigned IdxRecord; 3295 if (Record.size() == 4) { 3296 unsigned IdxTyID = Record[2]; 3297 Type *IdxTy = getTypeByID(IdxTyID); 3298 if (!IdxTy) 3299 return error("Invalid extractelement constexpr record"); 3300 IdxRecord = Record[3]; 3301 } else { 3302 // Deprecated, but still needed to read old bitcode files. 3303 IdxRecord = Record[2]; 3304 } 3305 V = BitcodeConstant::create(Alloc, CurTy, Instruction::ExtractElement, 3306 {(unsigned)Record[1], IdxRecord}); 3307 break; 3308 } 3309 case bitc::CST_CODE_CE_INSERTELT 3310 : { // CE_INSERTELT: [opval, opval, opty, opval] 3311 VectorType *OpTy = dyn_cast<VectorType>(CurTy); 3312 if (Record.size() < 3 || !OpTy) 3313 return error("Invalid insertelement constexpr record"); 3314 unsigned IdxRecord; 3315 if (Record.size() == 4) { 3316 unsigned IdxTyID = Record[2]; 3317 Type *IdxTy = getTypeByID(IdxTyID); 3318 if (!IdxTy) 3319 return error("Invalid insertelement constexpr record"); 3320 IdxRecord = Record[3]; 3321 } else { 3322 // Deprecated, but still needed to read old bitcode files. 3323 IdxRecord = Record[2]; 3324 } 3325 V = BitcodeConstant::create( 3326 Alloc, CurTy, Instruction::InsertElement, 3327 {(unsigned)Record[0], (unsigned)Record[1], IdxRecord}); 3328 break; 3329 } 3330 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval] 3331 VectorType *OpTy = dyn_cast<VectorType>(CurTy); 3332 if (Record.size() < 3 || !OpTy) 3333 return error("Invalid shufflevector constexpr record"); 3334 V = BitcodeConstant::create( 3335 Alloc, CurTy, Instruction::ShuffleVector, 3336 {(unsigned)Record[0], (unsigned)Record[1], (unsigned)Record[2]}); 3337 break; 3338 } 3339 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval] 3340 VectorType *RTy = dyn_cast<VectorType>(CurTy); 3341 VectorType *OpTy = 3342 dyn_cast_or_null<VectorType>(getTypeByID(Record[0])); 3343 if (Record.size() < 4 || !RTy || !OpTy) 3344 return error("Invalid shufflevector constexpr record"); 3345 V = BitcodeConstant::create( 3346 Alloc, CurTy, Instruction::ShuffleVector, 3347 {(unsigned)Record[1], (unsigned)Record[2], (unsigned)Record[3]}); 3348 break; 3349 } 3350 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred] 3351 if (Record.size() < 4) 3352 return error("Invalid cmp constexpt record"); 3353 unsigned OpTyID = Record[0]; 3354 Type *OpTy = getTypeByID(OpTyID); 3355 if (!OpTy) 3356 return error("Invalid cmp constexpr record"); 3357 V = BitcodeConstant::create( 3358 Alloc, CurTy, 3359 {(uint8_t)(OpTy->isFPOrFPVectorTy() ? Instruction::FCmp 3360 : Instruction::ICmp), 3361 (uint8_t)Record[3]}, 3362 {(unsigned)Record[1], (unsigned)Record[2]}); 3363 break; 3364 } 3365 // This maintains backward compatibility, pre-asm dialect keywords. 3366 // Deprecated, but still needed to read old bitcode files. 3367 case bitc::CST_CODE_INLINEASM_OLD: { 3368 if (Record.size() < 2) 3369 return error("Invalid inlineasm record"); 3370 std::string AsmStr, ConstrStr; 3371 bool HasSideEffects = Record[0] & 1; 3372 bool IsAlignStack = Record[0] >> 1; 3373 unsigned AsmStrSize = Record[1]; 3374 if (2+AsmStrSize >= Record.size()) 3375 return error("Invalid inlineasm record"); 3376 unsigned ConstStrSize = Record[2+AsmStrSize]; 3377 if (3+AsmStrSize+ConstStrSize > Record.size()) 3378 return error("Invalid inlineasm record"); 3379 3380 for (unsigned i = 0; i != AsmStrSize; ++i) 3381 AsmStr += (char)Record[2+i]; 3382 for (unsigned i = 0; i != ConstStrSize; ++i) 3383 ConstrStr += (char)Record[3+AsmStrSize+i]; 3384 UpgradeInlineAsmString(&AsmStr); 3385 if (!CurElemTy) 3386 return error("Missing element type for old-style inlineasm"); 3387 V = InlineAsm::get(cast<FunctionType>(CurElemTy), AsmStr, ConstrStr, 3388 HasSideEffects, IsAlignStack); 3389 break; 3390 } 3391 // This version adds support for the asm dialect keywords (e.g., 3392 // inteldialect). 3393 case bitc::CST_CODE_INLINEASM_OLD2: { 3394 if (Record.size() < 2) 3395 return error("Invalid inlineasm record"); 3396 std::string AsmStr, ConstrStr; 3397 bool HasSideEffects = Record[0] & 1; 3398 bool IsAlignStack = (Record[0] >> 1) & 1; 3399 unsigned AsmDialect = Record[0] >> 2; 3400 unsigned AsmStrSize = Record[1]; 3401 if (2+AsmStrSize >= Record.size()) 3402 return error("Invalid inlineasm record"); 3403 unsigned ConstStrSize = Record[2+AsmStrSize]; 3404 if (3+AsmStrSize+ConstStrSize > Record.size()) 3405 return error("Invalid inlineasm record"); 3406 3407 for (unsigned i = 0; i != AsmStrSize; ++i) 3408 AsmStr += (char)Record[2+i]; 3409 for (unsigned i = 0; i != ConstStrSize; ++i) 3410 ConstrStr += (char)Record[3+AsmStrSize+i]; 3411 UpgradeInlineAsmString(&AsmStr); 3412 if (!CurElemTy) 3413 return error("Missing element type for old-style inlineasm"); 3414 V = InlineAsm::get(cast<FunctionType>(CurElemTy), AsmStr, ConstrStr, 3415 HasSideEffects, IsAlignStack, 3416 InlineAsm::AsmDialect(AsmDialect)); 3417 break; 3418 } 3419 // This version adds support for the unwind keyword. 3420 case bitc::CST_CODE_INLINEASM_OLD3: { 3421 if (Record.size() < 2) 3422 return error("Invalid inlineasm record"); 3423 unsigned OpNum = 0; 3424 std::string AsmStr, ConstrStr; 3425 bool HasSideEffects = Record[OpNum] & 1; 3426 bool IsAlignStack = (Record[OpNum] >> 1) & 1; 3427 unsigned AsmDialect = (Record[OpNum] >> 2) & 1; 3428 bool CanThrow = (Record[OpNum] >> 3) & 1; 3429 ++OpNum; 3430 unsigned AsmStrSize = Record[OpNum]; 3431 ++OpNum; 3432 if (OpNum + AsmStrSize >= Record.size()) 3433 return error("Invalid inlineasm record"); 3434 unsigned ConstStrSize = Record[OpNum + AsmStrSize]; 3435 if (OpNum + 1 + AsmStrSize + ConstStrSize > Record.size()) 3436 return error("Invalid inlineasm record"); 3437 3438 for (unsigned i = 0; i != AsmStrSize; ++i) 3439 AsmStr += (char)Record[OpNum + i]; 3440 ++OpNum; 3441 for (unsigned i = 0; i != ConstStrSize; ++i) 3442 ConstrStr += (char)Record[OpNum + AsmStrSize + i]; 3443 UpgradeInlineAsmString(&AsmStr); 3444 if (!CurElemTy) 3445 return error("Missing element type for old-style inlineasm"); 3446 V = InlineAsm::get(cast<FunctionType>(CurElemTy), AsmStr, ConstrStr, 3447 HasSideEffects, IsAlignStack, 3448 InlineAsm::AsmDialect(AsmDialect), CanThrow); 3449 break; 3450 } 3451 // This version adds explicit function type. 3452 case bitc::CST_CODE_INLINEASM: { 3453 if (Record.size() < 3) 3454 return error("Invalid inlineasm record"); 3455 unsigned OpNum = 0; 3456 auto *FnTy = dyn_cast_or_null<FunctionType>(getTypeByID(Record[OpNum])); 3457 ++OpNum; 3458 if (!FnTy) 3459 return error("Invalid inlineasm record"); 3460 std::string AsmStr, ConstrStr; 3461 bool HasSideEffects = Record[OpNum] & 1; 3462 bool IsAlignStack = (Record[OpNum] >> 1) & 1; 3463 unsigned AsmDialect = (Record[OpNum] >> 2) & 1; 3464 bool CanThrow = (Record[OpNum] >> 3) & 1; 3465 ++OpNum; 3466 unsigned AsmStrSize = Record[OpNum]; 3467 ++OpNum; 3468 if (OpNum + AsmStrSize >= Record.size()) 3469 return error("Invalid inlineasm record"); 3470 unsigned ConstStrSize = Record[OpNum + AsmStrSize]; 3471 if (OpNum + 1 + AsmStrSize + ConstStrSize > Record.size()) 3472 return error("Invalid inlineasm record"); 3473 3474 for (unsigned i = 0; i != AsmStrSize; ++i) 3475 AsmStr += (char)Record[OpNum + i]; 3476 ++OpNum; 3477 for (unsigned i = 0; i != ConstStrSize; ++i) 3478 ConstrStr += (char)Record[OpNum + AsmStrSize + i]; 3479 UpgradeInlineAsmString(&AsmStr); 3480 V = InlineAsm::get(FnTy, AsmStr, ConstrStr, HasSideEffects, IsAlignStack, 3481 InlineAsm::AsmDialect(AsmDialect), CanThrow); 3482 break; 3483 } 3484 case bitc::CST_CODE_BLOCKADDRESS:{ 3485 if (Record.size() < 3) 3486 return error("Invalid blockaddress record"); 3487 unsigned FnTyID = Record[0]; 3488 Type *FnTy = getTypeByID(FnTyID); 3489 if (!FnTy) 3490 return error("Invalid blockaddress record"); 3491 V = BitcodeConstant::create( 3492 Alloc, CurTy, 3493 {BitcodeConstant::BlockAddressOpcode, 0, (unsigned)Record[2]}, 3494 Record[1]); 3495 break; 3496 } 3497 case bitc::CST_CODE_DSO_LOCAL_EQUIVALENT: { 3498 if (Record.size() < 2) 3499 return error("Invalid dso_local record"); 3500 unsigned GVTyID = Record[0]; 3501 Type *GVTy = getTypeByID(GVTyID); 3502 if (!GVTy) 3503 return error("Invalid dso_local record"); 3504 V = BitcodeConstant::create( 3505 Alloc, CurTy, BitcodeConstant::DSOLocalEquivalentOpcode, Record[1]); 3506 break; 3507 } 3508 case bitc::CST_CODE_NO_CFI_VALUE: { 3509 if (Record.size() < 2) 3510 return error("Invalid no_cfi record"); 3511 unsigned GVTyID = Record[0]; 3512 Type *GVTy = getTypeByID(GVTyID); 3513 if (!GVTy) 3514 return error("Invalid no_cfi record"); 3515 V = BitcodeConstant::create(Alloc, CurTy, BitcodeConstant::NoCFIOpcode, 3516 Record[1]); 3517 break; 3518 } 3519 } 3520 3521 assert(V->getType() == getTypeByID(CurTyID) && "Incorrect result type ID"); 3522 if (Error Err = ValueList.assignValue(NextCstNo, V, CurTyID)) 3523 return Err; 3524 ++NextCstNo; 3525 } 3526 } 3527 3528 Error BitcodeReader::parseUseLists() { 3529 if (Error Err = Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID)) 3530 return Err; 3531 3532 // Read all the records. 3533 SmallVector<uint64_t, 64> Record; 3534 3535 while (true) { 3536 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); 3537 if (!MaybeEntry) 3538 return MaybeEntry.takeError(); 3539 BitstreamEntry Entry = MaybeEntry.get(); 3540 3541 switch (Entry.Kind) { 3542 case BitstreamEntry::SubBlock: // Handled for us already. 3543 case BitstreamEntry::Error: 3544 return error("Malformed block"); 3545 case BitstreamEntry::EndBlock: 3546 return Error::success(); 3547 case BitstreamEntry::Record: 3548 // The interesting case. 3549 break; 3550 } 3551 3552 // Read a use list record. 3553 Record.clear(); 3554 bool IsBB = false; 3555 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record); 3556 if (!MaybeRecord) 3557 return MaybeRecord.takeError(); 3558 switch (MaybeRecord.get()) { 3559 default: // Default behavior: unknown type. 3560 break; 3561 case bitc::USELIST_CODE_BB: 3562 IsBB = true; 3563 [[fallthrough]]; 3564 case bitc::USELIST_CODE_DEFAULT: { 3565 unsigned RecordLength = Record.size(); 3566 if (RecordLength < 3) 3567 // Records should have at least an ID and two indexes. 3568 return error("Invalid record"); 3569 unsigned ID = Record.pop_back_val(); 3570 3571 Value *V; 3572 if (IsBB) { 3573 assert(ID < FunctionBBs.size() && "Basic block not found"); 3574 V = FunctionBBs[ID]; 3575 } else 3576 V = ValueList[ID]; 3577 unsigned NumUses = 0; 3578 SmallDenseMap<const Use *, unsigned, 16> Order; 3579 for (const Use &U : V->materialized_uses()) { 3580 if (++NumUses > Record.size()) 3581 break; 3582 Order[&U] = Record[NumUses - 1]; 3583 } 3584 if (Order.size() != Record.size() || NumUses > Record.size()) 3585 // Mismatches can happen if the functions are being materialized lazily 3586 // (out-of-order), or a value has been upgraded. 3587 break; 3588 3589 V->sortUseList([&](const Use &L, const Use &R) { 3590 return Order.lookup(&L) < Order.lookup(&R); 3591 }); 3592 break; 3593 } 3594 } 3595 } 3596 } 3597 3598 /// When we see the block for metadata, remember where it is and then skip it. 3599 /// This lets us lazily deserialize the metadata. 3600 Error BitcodeReader::rememberAndSkipMetadata() { 3601 // Save the current stream state. 3602 uint64_t CurBit = Stream.GetCurrentBitNo(); 3603 DeferredMetadataInfo.push_back(CurBit); 3604 3605 // Skip over the block for now. 3606 if (Error Err = Stream.SkipBlock()) 3607 return Err; 3608 return Error::success(); 3609 } 3610 3611 Error BitcodeReader::materializeMetadata() { 3612 for (uint64_t BitPos : DeferredMetadataInfo) { 3613 // Move the bit stream to the saved position. 3614 if (Error JumpFailed = Stream.JumpToBit(BitPos)) 3615 return JumpFailed; 3616 if (Error Err = MDLoader->parseModuleMetadata()) 3617 return Err; 3618 } 3619 3620 // Upgrade "Linker Options" module flag to "llvm.linker.options" module-level 3621 // metadata. Only upgrade if the new option doesn't exist to avoid upgrade 3622 // multiple times. 3623 if (!TheModule->getNamedMetadata("llvm.linker.options")) { 3624 if (Metadata *Val = TheModule->getModuleFlag("Linker Options")) { 3625 NamedMDNode *LinkerOpts = 3626 TheModule->getOrInsertNamedMetadata("llvm.linker.options"); 3627 for (const MDOperand &MDOptions : cast<MDNode>(Val)->operands()) 3628 LinkerOpts->addOperand(cast<MDNode>(MDOptions)); 3629 } 3630 } 3631 3632 DeferredMetadataInfo.clear(); 3633 return Error::success(); 3634 } 3635 3636 void BitcodeReader::setStripDebugInfo() { StripDebugInfo = true; } 3637 3638 /// When we see the block for a function body, remember where it is and then 3639 /// skip it. This lets us lazily deserialize the functions. 3640 Error BitcodeReader::rememberAndSkipFunctionBody() { 3641 // Get the function we are talking about. 3642 if (FunctionsWithBodies.empty()) 3643 return error("Insufficient function protos"); 3644 3645 Function *Fn = FunctionsWithBodies.back(); 3646 FunctionsWithBodies.pop_back(); 3647 3648 // Save the current stream state. 3649 uint64_t CurBit = Stream.GetCurrentBitNo(); 3650 assert( 3651 (DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo[Fn] == CurBit) && 3652 "Mismatch between VST and scanned function offsets"); 3653 DeferredFunctionInfo[Fn] = CurBit; 3654 3655 // Skip over the function block for now. 3656 if (Error Err = Stream.SkipBlock()) 3657 return Err; 3658 return Error::success(); 3659 } 3660 3661 Error BitcodeReader::globalCleanup() { 3662 // Patch the initializers for globals and aliases up. 3663 if (Error Err = resolveGlobalAndIndirectSymbolInits()) 3664 return Err; 3665 if (!GlobalInits.empty() || !IndirectSymbolInits.empty()) 3666 return error("Malformed global initializer set"); 3667 3668 // Look for intrinsic functions which need to be upgraded at some point 3669 // and functions that need to have their function attributes upgraded. 3670 for (Function &F : *TheModule) { 3671 MDLoader->upgradeDebugIntrinsics(F); 3672 Function *NewFn; 3673 if (UpgradeIntrinsicFunction(&F, NewFn)) 3674 UpgradedIntrinsics[&F] = NewFn; 3675 // Look for functions that rely on old function attribute behavior. 3676 UpgradeFunctionAttributes(F); 3677 } 3678 3679 // Look for global variables which need to be renamed. 3680 std::vector<std::pair<GlobalVariable *, GlobalVariable *>> UpgradedVariables; 3681 for (GlobalVariable &GV : TheModule->globals()) 3682 if (GlobalVariable *Upgraded = UpgradeGlobalVariable(&GV)) 3683 UpgradedVariables.emplace_back(&GV, Upgraded); 3684 for (auto &Pair : UpgradedVariables) { 3685 Pair.first->eraseFromParent(); 3686 TheModule->insertGlobalVariable(Pair.second); 3687 } 3688 3689 // Force deallocation of memory for these vectors to favor the client that 3690 // want lazy deserialization. 3691 std::vector<std::pair<GlobalVariable *, unsigned>>().swap(GlobalInits); 3692 std::vector<std::pair<GlobalValue *, unsigned>>().swap(IndirectSymbolInits); 3693 return Error::success(); 3694 } 3695 3696 /// Support for lazy parsing of function bodies. This is required if we 3697 /// either have an old bitcode file without a VST forward declaration record, 3698 /// or if we have an anonymous function being materialized, since anonymous 3699 /// functions do not have a name and are therefore not in the VST. 3700 Error BitcodeReader::rememberAndSkipFunctionBodies() { 3701 if (Error JumpFailed = Stream.JumpToBit(NextUnreadBit)) 3702 return JumpFailed; 3703 3704 if (Stream.AtEndOfStream()) 3705 return error("Could not find function in stream"); 3706 3707 if (!SeenFirstFunctionBody) 3708 return error("Trying to materialize functions before seeing function blocks"); 3709 3710 // An old bitcode file with the symbol table at the end would have 3711 // finished the parse greedily. 3712 assert(SeenValueSymbolTable); 3713 3714 SmallVector<uint64_t, 64> Record; 3715 3716 while (true) { 3717 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance(); 3718 if (!MaybeEntry) 3719 return MaybeEntry.takeError(); 3720 llvm::BitstreamEntry Entry = MaybeEntry.get(); 3721 3722 switch (Entry.Kind) { 3723 default: 3724 return error("Expect SubBlock"); 3725 case BitstreamEntry::SubBlock: 3726 switch (Entry.ID) { 3727 default: 3728 return error("Expect function block"); 3729 case bitc::FUNCTION_BLOCK_ID: 3730 if (Error Err = rememberAndSkipFunctionBody()) 3731 return Err; 3732 NextUnreadBit = Stream.GetCurrentBitNo(); 3733 return Error::success(); 3734 } 3735 } 3736 } 3737 } 3738 3739 Error BitcodeReaderBase::readBlockInfo() { 3740 Expected<std::optional<BitstreamBlockInfo>> MaybeNewBlockInfo = 3741 Stream.ReadBlockInfoBlock(); 3742 if (!MaybeNewBlockInfo) 3743 return MaybeNewBlockInfo.takeError(); 3744 std::optional<BitstreamBlockInfo> NewBlockInfo = 3745 std::move(MaybeNewBlockInfo.get()); 3746 if (!NewBlockInfo) 3747 return error("Malformed block"); 3748 BlockInfo = std::move(*NewBlockInfo); 3749 return Error::success(); 3750 } 3751 3752 Error BitcodeReader::parseComdatRecord(ArrayRef<uint64_t> Record) { 3753 // v1: [selection_kind, name] 3754 // v2: [strtab_offset, strtab_size, selection_kind] 3755 StringRef Name; 3756 std::tie(Name, Record) = readNameFromStrtab(Record); 3757 3758 if (Record.empty()) 3759 return error("Invalid record"); 3760 Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]); 3761 std::string OldFormatName; 3762 if (!UseStrtab) { 3763 if (Record.size() < 2) 3764 return error("Invalid record"); 3765 unsigned ComdatNameSize = Record[1]; 3766 if (ComdatNameSize > Record.size() - 2) 3767 return error("Comdat name size too large"); 3768 OldFormatName.reserve(ComdatNameSize); 3769 for (unsigned i = 0; i != ComdatNameSize; ++i) 3770 OldFormatName += (char)Record[2 + i]; 3771 Name = OldFormatName; 3772 } 3773 Comdat *C = TheModule->getOrInsertComdat(Name); 3774 C->setSelectionKind(SK); 3775 ComdatList.push_back(C); 3776 return Error::success(); 3777 } 3778 3779 static void inferDSOLocal(GlobalValue *GV) { 3780 // infer dso_local from linkage and visibility if it is not encoded. 3781 if (GV->hasLocalLinkage() || 3782 (!GV->hasDefaultVisibility() && !GV->hasExternalWeakLinkage())) 3783 GV->setDSOLocal(true); 3784 } 3785 3786 GlobalValue::SanitizerMetadata deserializeSanitizerMetadata(unsigned V) { 3787 GlobalValue::SanitizerMetadata Meta; 3788 if (V & (1 << 0)) 3789 Meta.NoAddress = true; 3790 if (V & (1 << 1)) 3791 Meta.NoHWAddress = true; 3792 if (V & (1 << 2)) 3793 Meta.Memtag = true; 3794 if (V & (1 << 3)) 3795 Meta.IsDynInit = true; 3796 return Meta; 3797 } 3798 3799 Error BitcodeReader::parseGlobalVarRecord(ArrayRef<uint64_t> Record) { 3800 // v1: [pointer type, isconst, initid, linkage, alignment, section, 3801 // visibility, threadlocal, unnamed_addr, externally_initialized, 3802 // dllstorageclass, comdat, attributes, preemption specifier, 3803 // partition strtab offset, partition strtab size] (name in VST) 3804 // v2: [strtab_offset, strtab_size, v1] 3805 StringRef Name; 3806 std::tie(Name, Record) = readNameFromStrtab(Record); 3807 3808 if (Record.size() < 6) 3809 return error("Invalid record"); 3810 unsigned TyID = Record[0]; 3811 Type *Ty = getTypeByID(TyID); 3812 if (!Ty) 3813 return error("Invalid record"); 3814 bool isConstant = Record[1] & 1; 3815 bool explicitType = Record[1] & 2; 3816 unsigned AddressSpace; 3817 if (explicitType) { 3818 AddressSpace = Record[1] >> 2; 3819 } else { 3820 if (!Ty->isPointerTy()) 3821 return error("Invalid type for value"); 3822 AddressSpace = cast<PointerType>(Ty)->getAddressSpace(); 3823 TyID = getContainedTypeID(TyID); 3824 Ty = getTypeByID(TyID); 3825 if (!Ty) 3826 return error("Missing element type for old-style global"); 3827 } 3828 3829 uint64_t RawLinkage = Record[3]; 3830 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage); 3831 MaybeAlign Alignment; 3832 if (Error Err = parseAlignmentValue(Record[4], Alignment)) 3833 return Err; 3834 std::string Section; 3835 if (Record[5]) { 3836 if (Record[5] - 1 >= SectionTable.size()) 3837 return error("Invalid ID"); 3838 Section = SectionTable[Record[5] - 1]; 3839 } 3840 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility; 3841 // Local linkage must have default visibility. 3842 // auto-upgrade `hidden` and `protected` for old bitcode. 3843 if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage)) 3844 Visibility = getDecodedVisibility(Record[6]); 3845 3846 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal; 3847 if (Record.size() > 7) 3848 TLM = getDecodedThreadLocalMode(Record[7]); 3849 3850 GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None; 3851 if (Record.size() > 8) 3852 UnnamedAddr = getDecodedUnnamedAddrType(Record[8]); 3853 3854 bool ExternallyInitialized = false; 3855 if (Record.size() > 9) 3856 ExternallyInitialized = Record[9]; 3857 3858 GlobalVariable *NewGV = 3859 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, Name, 3860 nullptr, TLM, AddressSpace, ExternallyInitialized); 3861 if (Alignment) 3862 NewGV->setAlignment(*Alignment); 3863 if (!Section.empty()) 3864 NewGV->setSection(Section); 3865 NewGV->setVisibility(Visibility); 3866 NewGV->setUnnamedAddr(UnnamedAddr); 3867 3868 if (Record.size() > 10) { 3869 // A GlobalValue with local linkage cannot have a DLL storage class. 3870 if (!NewGV->hasLocalLinkage()) { 3871 NewGV->setDLLStorageClass(getDecodedDLLStorageClass(Record[10])); 3872 } 3873 } else { 3874 upgradeDLLImportExportLinkage(NewGV, RawLinkage); 3875 } 3876 3877 ValueList.push_back(NewGV, getVirtualTypeID(NewGV->getType(), TyID)); 3878 3879 // Remember which value to use for the global initializer. 3880 if (unsigned InitID = Record[2]) 3881 GlobalInits.push_back(std::make_pair(NewGV, InitID - 1)); 3882 3883 if (Record.size() > 11) { 3884 if (unsigned ComdatID = Record[11]) { 3885 if (ComdatID > ComdatList.size()) 3886 return error("Invalid global variable comdat ID"); 3887 NewGV->setComdat(ComdatList[ComdatID - 1]); 3888 } 3889 } else if (hasImplicitComdat(RawLinkage)) { 3890 ImplicitComdatObjects.insert(NewGV); 3891 } 3892 3893 if (Record.size() > 12) { 3894 auto AS = getAttributes(Record[12]).getFnAttrs(); 3895 NewGV->setAttributes(AS); 3896 } 3897 3898 if (Record.size() > 13) { 3899 NewGV->setDSOLocal(getDecodedDSOLocal(Record[13])); 3900 } 3901 inferDSOLocal(NewGV); 3902 3903 // Check whether we have enough values to read a partition name. 3904 if (Record.size() > 15) 3905 NewGV->setPartition(StringRef(Strtab.data() + Record[14], Record[15])); 3906 3907 if (Record.size() > 16 && Record[16]) { 3908 llvm::GlobalValue::SanitizerMetadata Meta = 3909 deserializeSanitizerMetadata(Record[16]); 3910 NewGV->setSanitizerMetadata(Meta); 3911 } 3912 3913 return Error::success(); 3914 } 3915 3916 void BitcodeReader::callValueTypeCallback(Value *F, unsigned TypeID) { 3917 if (ValueTypeCallback) { 3918 (*ValueTypeCallback)( 3919 F, TypeID, [this](unsigned I) { return getTypeByID(I); }, 3920 [this](unsigned I, unsigned J) { return getContainedTypeID(I, J); }); 3921 } 3922 } 3923 3924 Error BitcodeReader::parseFunctionRecord(ArrayRef<uint64_t> Record) { 3925 // v1: [type, callingconv, isproto, linkage, paramattr, alignment, section, 3926 // visibility, gc, unnamed_addr, prologuedata, dllstorageclass, comdat, 3927 // prefixdata, personalityfn, preemption specifier, addrspace] (name in VST) 3928 // v2: [strtab_offset, strtab_size, v1] 3929 StringRef Name; 3930 std::tie(Name, Record) = readNameFromStrtab(Record); 3931 3932 if (Record.size() < 8) 3933 return error("Invalid record"); 3934 unsigned FTyID = Record[0]; 3935 Type *FTy = getTypeByID(FTyID); 3936 if (!FTy) 3937 return error("Invalid record"); 3938 if (isa<PointerType>(FTy)) { 3939 FTyID = getContainedTypeID(FTyID, 0); 3940 FTy = getTypeByID(FTyID); 3941 if (!FTy) 3942 return error("Missing element type for old-style function"); 3943 } 3944 3945 if (!isa<FunctionType>(FTy)) 3946 return error("Invalid type for value"); 3947 auto CC = static_cast<CallingConv::ID>(Record[1]); 3948 if (CC & ~CallingConv::MaxID) 3949 return error("Invalid calling convention ID"); 3950 3951 unsigned AddrSpace = TheModule->getDataLayout().getProgramAddressSpace(); 3952 if (Record.size() > 16) 3953 AddrSpace = Record[16]; 3954 3955 Function *Func = 3956 Function::Create(cast<FunctionType>(FTy), GlobalValue::ExternalLinkage, 3957 AddrSpace, Name, TheModule); 3958 3959 assert(Func->getFunctionType() == FTy && 3960 "Incorrect fully specified type provided for function"); 3961 FunctionTypeIDs[Func] = FTyID; 3962 3963 Func->setCallingConv(CC); 3964 bool isProto = Record[2]; 3965 uint64_t RawLinkage = Record[3]; 3966 Func->setLinkage(getDecodedLinkage(RawLinkage)); 3967 Func->setAttributes(getAttributes(Record[4])); 3968 callValueTypeCallback(Func, FTyID); 3969 3970 // Upgrade any old-style byval or sret without a type by propagating the 3971 // argument's pointee type. There should be no opaque pointers where the byval 3972 // type is implicit. 3973 for (unsigned i = 0; i != Func->arg_size(); ++i) { 3974 for (Attribute::AttrKind Kind : {Attribute::ByVal, Attribute::StructRet, 3975 Attribute::InAlloca}) { 3976 if (!Func->hasParamAttribute(i, Kind)) 3977 continue; 3978 3979 if (Func->getParamAttribute(i, Kind).getValueAsType()) 3980 continue; 3981 3982 Func->removeParamAttr(i, Kind); 3983 3984 unsigned ParamTypeID = getContainedTypeID(FTyID, i + 1); 3985 Type *PtrEltTy = getPtrElementTypeByID(ParamTypeID); 3986 if (!PtrEltTy) 3987 return error("Missing param element type for attribute upgrade"); 3988 3989 Attribute NewAttr; 3990 switch (Kind) { 3991 case Attribute::ByVal: 3992 NewAttr = Attribute::getWithByValType(Context, PtrEltTy); 3993 break; 3994 case Attribute::StructRet: 3995 NewAttr = Attribute::getWithStructRetType(Context, PtrEltTy); 3996 break; 3997 case Attribute::InAlloca: 3998 NewAttr = Attribute::getWithInAllocaType(Context, PtrEltTy); 3999 break; 4000 default: 4001 llvm_unreachable("not an upgraded type attribute"); 4002 } 4003 4004 Func->addParamAttr(i, NewAttr); 4005 } 4006 } 4007 4008 if (Func->getCallingConv() == CallingConv::X86_INTR && 4009 !Func->arg_empty() && !Func->hasParamAttribute(0, Attribute::ByVal)) { 4010 unsigned ParamTypeID = getContainedTypeID(FTyID, 1); 4011 Type *ByValTy = getPtrElementTypeByID(ParamTypeID); 4012 if (!ByValTy) 4013 return error("Missing param element type for x86_intrcc upgrade"); 4014 Attribute NewAttr = Attribute::getWithByValType(Context, ByValTy); 4015 Func->addParamAttr(0, NewAttr); 4016 } 4017 4018 MaybeAlign Alignment; 4019 if (Error Err = parseAlignmentValue(Record[5], Alignment)) 4020 return Err; 4021 if (Alignment) 4022 Func->setAlignment(*Alignment); 4023 if (Record[6]) { 4024 if (Record[6] - 1 >= SectionTable.size()) 4025 return error("Invalid ID"); 4026 Func->setSection(SectionTable[Record[6] - 1]); 4027 } 4028 // Local linkage must have default visibility. 4029 // auto-upgrade `hidden` and `protected` for old bitcode. 4030 if (!Func->hasLocalLinkage()) 4031 Func->setVisibility(getDecodedVisibility(Record[7])); 4032 if (Record.size() > 8 && Record[8]) { 4033 if (Record[8] - 1 >= GCTable.size()) 4034 return error("Invalid ID"); 4035 Func->setGC(GCTable[Record[8] - 1]); 4036 } 4037 GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None; 4038 if (Record.size() > 9) 4039 UnnamedAddr = getDecodedUnnamedAddrType(Record[9]); 4040 Func->setUnnamedAddr(UnnamedAddr); 4041 4042 FunctionOperandInfo OperandInfo = {Func, 0, 0, 0}; 4043 if (Record.size() > 10) 4044 OperandInfo.Prologue = Record[10]; 4045 4046 if (Record.size() > 11) { 4047 // A GlobalValue with local linkage cannot have a DLL storage class. 4048 if (!Func->hasLocalLinkage()) { 4049 Func->setDLLStorageClass(getDecodedDLLStorageClass(Record[11])); 4050 } 4051 } else { 4052 upgradeDLLImportExportLinkage(Func, RawLinkage); 4053 } 4054 4055 if (Record.size() > 12) { 4056 if (unsigned ComdatID = Record[12]) { 4057 if (ComdatID > ComdatList.size()) 4058 return error("Invalid function comdat ID"); 4059 Func->setComdat(ComdatList[ComdatID - 1]); 4060 } 4061 } else if (hasImplicitComdat(RawLinkage)) { 4062 ImplicitComdatObjects.insert(Func); 4063 } 4064 4065 if (Record.size() > 13) 4066 OperandInfo.Prefix = Record[13]; 4067 4068 if (Record.size() > 14) 4069 OperandInfo.PersonalityFn = Record[14]; 4070 4071 if (Record.size() > 15) { 4072 Func->setDSOLocal(getDecodedDSOLocal(Record[15])); 4073 } 4074 inferDSOLocal(Func); 4075 4076 // Record[16] is the address space number. 4077 4078 // Check whether we have enough values to read a partition name. Also make 4079 // sure Strtab has enough values. 4080 if (Record.size() > 18 && Strtab.data() && 4081 Record[17] + Record[18] <= Strtab.size()) { 4082 Func->setPartition(StringRef(Strtab.data() + Record[17], Record[18])); 4083 } 4084 4085 ValueList.push_back(Func, getVirtualTypeID(Func->getType(), FTyID)); 4086 4087 if (OperandInfo.PersonalityFn || OperandInfo.Prefix || OperandInfo.Prologue) 4088 FunctionOperands.push_back(OperandInfo); 4089 4090 // If this is a function with a body, remember the prototype we are 4091 // creating now, so that we can match up the body with them later. 4092 if (!isProto) { 4093 Func->setIsMaterializable(true); 4094 FunctionsWithBodies.push_back(Func); 4095 DeferredFunctionInfo[Func] = 0; 4096 } 4097 return Error::success(); 4098 } 4099 4100 Error BitcodeReader::parseGlobalIndirectSymbolRecord( 4101 unsigned BitCode, ArrayRef<uint64_t> Record) { 4102 // v1 ALIAS_OLD: [alias type, aliasee val#, linkage] (name in VST) 4103 // v1 ALIAS: [alias type, addrspace, aliasee val#, linkage, visibility, 4104 // dllstorageclass, threadlocal, unnamed_addr, 4105 // preemption specifier] (name in VST) 4106 // v1 IFUNC: [alias type, addrspace, aliasee val#, linkage, 4107 // visibility, dllstorageclass, threadlocal, unnamed_addr, 4108 // preemption specifier] (name in VST) 4109 // v2: [strtab_offset, strtab_size, v1] 4110 StringRef Name; 4111 std::tie(Name, Record) = readNameFromStrtab(Record); 4112 4113 bool NewRecord = BitCode != bitc::MODULE_CODE_ALIAS_OLD; 4114 if (Record.size() < (3 + (unsigned)NewRecord)) 4115 return error("Invalid record"); 4116 unsigned OpNum = 0; 4117 unsigned TypeID = Record[OpNum++]; 4118 Type *Ty = getTypeByID(TypeID); 4119 if (!Ty) 4120 return error("Invalid record"); 4121 4122 unsigned AddrSpace; 4123 if (!NewRecord) { 4124 auto *PTy = dyn_cast<PointerType>(Ty); 4125 if (!PTy) 4126 return error("Invalid type for value"); 4127 AddrSpace = PTy->getAddressSpace(); 4128 TypeID = getContainedTypeID(TypeID); 4129 Ty = getTypeByID(TypeID); 4130 if (!Ty) 4131 return error("Missing element type for old-style indirect symbol"); 4132 } else { 4133 AddrSpace = Record[OpNum++]; 4134 } 4135 4136 auto Val = Record[OpNum++]; 4137 auto Linkage = Record[OpNum++]; 4138 GlobalValue *NewGA; 4139 if (BitCode == bitc::MODULE_CODE_ALIAS || 4140 BitCode == bitc::MODULE_CODE_ALIAS_OLD) 4141 NewGA = GlobalAlias::create(Ty, AddrSpace, getDecodedLinkage(Linkage), Name, 4142 TheModule); 4143 else 4144 NewGA = GlobalIFunc::create(Ty, AddrSpace, getDecodedLinkage(Linkage), Name, 4145 nullptr, TheModule); 4146 4147 // Local linkage must have default visibility. 4148 // auto-upgrade `hidden` and `protected` for old bitcode. 4149 if (OpNum != Record.size()) { 4150 auto VisInd = OpNum++; 4151 if (!NewGA->hasLocalLinkage()) 4152 NewGA->setVisibility(getDecodedVisibility(Record[VisInd])); 4153 } 4154 if (BitCode == bitc::MODULE_CODE_ALIAS || 4155 BitCode == bitc::MODULE_CODE_ALIAS_OLD) { 4156 if (OpNum != Record.size()) { 4157 auto S = Record[OpNum++]; 4158 // A GlobalValue with local linkage cannot have a DLL storage class. 4159 if (!NewGA->hasLocalLinkage()) 4160 NewGA->setDLLStorageClass(getDecodedDLLStorageClass(S)); 4161 } 4162 else 4163 upgradeDLLImportExportLinkage(NewGA, Linkage); 4164 if (OpNum != Record.size()) 4165 NewGA->setThreadLocalMode(getDecodedThreadLocalMode(Record[OpNum++])); 4166 if (OpNum != Record.size()) 4167 NewGA->setUnnamedAddr(getDecodedUnnamedAddrType(Record[OpNum++])); 4168 } 4169 if (OpNum != Record.size()) 4170 NewGA->setDSOLocal(getDecodedDSOLocal(Record[OpNum++])); 4171 inferDSOLocal(NewGA); 4172 4173 // Check whether we have enough values to read a partition name. 4174 if (OpNum + 1 < Record.size()) { 4175 NewGA->setPartition( 4176 StringRef(Strtab.data() + Record[OpNum], Record[OpNum + 1])); 4177 OpNum += 2; 4178 } 4179 4180 ValueList.push_back(NewGA, getVirtualTypeID(NewGA->getType(), TypeID)); 4181 IndirectSymbolInits.push_back(std::make_pair(NewGA, Val)); 4182 return Error::success(); 4183 } 4184 4185 Error BitcodeReader::parseModule(uint64_t ResumeBit, 4186 bool ShouldLazyLoadMetadata, 4187 ParserCallbacks Callbacks) { 4188 this->ValueTypeCallback = std::move(Callbacks.ValueType); 4189 if (ResumeBit) { 4190 if (Error JumpFailed = Stream.JumpToBit(ResumeBit)) 4191 return JumpFailed; 4192 } else if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID)) 4193 return Err; 4194 4195 SmallVector<uint64_t, 64> Record; 4196 4197 // Parts of bitcode parsing depend on the datalayout. Make sure we 4198 // finalize the datalayout before we run any of that code. 4199 bool ResolvedDataLayout = false; 4200 // In order to support importing modules with illegal data layout strings, 4201 // delay parsing the data layout string until after upgrades and overrides 4202 // have been applied, allowing to fix illegal data layout strings. 4203 // Initialize to the current module's layout string in case none is specified. 4204 std::string TentativeDataLayoutStr = TheModule->getDataLayoutStr(); 4205 4206 auto ResolveDataLayout = [&]() -> Error { 4207 if (ResolvedDataLayout) 4208 return Error::success(); 4209 4210 // Datalayout and triple can't be parsed after this point. 4211 ResolvedDataLayout = true; 4212 4213 // Auto-upgrade the layout string 4214 TentativeDataLayoutStr = llvm::UpgradeDataLayoutString( 4215 TentativeDataLayoutStr, TheModule->getTargetTriple()); 4216 4217 // Apply override 4218 if (Callbacks.DataLayout) { 4219 if (auto LayoutOverride = (*Callbacks.DataLayout)( 4220 TheModule->getTargetTriple(), TentativeDataLayoutStr)) 4221 TentativeDataLayoutStr = *LayoutOverride; 4222 } 4223 4224 // Now the layout string is finalized in TentativeDataLayoutStr. Parse it. 4225 Expected<DataLayout> MaybeDL = DataLayout::parse(TentativeDataLayoutStr); 4226 if (!MaybeDL) 4227 return MaybeDL.takeError(); 4228 4229 TheModule->setDataLayout(MaybeDL.get()); 4230 return Error::success(); 4231 }; 4232 4233 // Read all the records for this module. 4234 while (true) { 4235 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance(); 4236 if (!MaybeEntry) 4237 return MaybeEntry.takeError(); 4238 llvm::BitstreamEntry Entry = MaybeEntry.get(); 4239 4240 switch (Entry.Kind) { 4241 case BitstreamEntry::Error: 4242 return error("Malformed block"); 4243 case BitstreamEntry::EndBlock: 4244 if (Error Err = ResolveDataLayout()) 4245 return Err; 4246 return globalCleanup(); 4247 4248 case BitstreamEntry::SubBlock: 4249 switch (Entry.ID) { 4250 default: // Skip unknown content. 4251 if (Error Err = Stream.SkipBlock()) 4252 return Err; 4253 break; 4254 case bitc::BLOCKINFO_BLOCK_ID: 4255 if (Error Err = readBlockInfo()) 4256 return Err; 4257 break; 4258 case bitc::PARAMATTR_BLOCK_ID: 4259 if (Error Err = parseAttributeBlock()) 4260 return Err; 4261 break; 4262 case bitc::PARAMATTR_GROUP_BLOCK_ID: 4263 if (Error Err = parseAttributeGroupBlock()) 4264 return Err; 4265 break; 4266 case bitc::TYPE_BLOCK_ID_NEW: 4267 if (Error Err = parseTypeTable()) 4268 return Err; 4269 break; 4270 case bitc::VALUE_SYMTAB_BLOCK_ID: 4271 if (!SeenValueSymbolTable) { 4272 // Either this is an old form VST without function index and an 4273 // associated VST forward declaration record (which would have caused 4274 // the VST to be jumped to and parsed before it was encountered 4275 // normally in the stream), or there were no function blocks to 4276 // trigger an earlier parsing of the VST. 4277 assert(VSTOffset == 0 || FunctionsWithBodies.empty()); 4278 if (Error Err = parseValueSymbolTable()) 4279 return Err; 4280 SeenValueSymbolTable = true; 4281 } else { 4282 // We must have had a VST forward declaration record, which caused 4283 // the parser to jump to and parse the VST earlier. 4284 assert(VSTOffset > 0); 4285 if (Error Err = Stream.SkipBlock()) 4286 return Err; 4287 } 4288 break; 4289 case bitc::CONSTANTS_BLOCK_ID: 4290 if (Error Err = parseConstants()) 4291 return Err; 4292 if (Error Err = resolveGlobalAndIndirectSymbolInits()) 4293 return Err; 4294 break; 4295 case bitc::METADATA_BLOCK_ID: 4296 if (ShouldLazyLoadMetadata) { 4297 if (Error Err = rememberAndSkipMetadata()) 4298 return Err; 4299 break; 4300 } 4301 assert(DeferredMetadataInfo.empty() && "Unexpected deferred metadata"); 4302 if (Error Err = MDLoader->parseModuleMetadata()) 4303 return Err; 4304 break; 4305 case bitc::METADATA_KIND_BLOCK_ID: 4306 if (Error Err = MDLoader->parseMetadataKinds()) 4307 return Err; 4308 break; 4309 case bitc::FUNCTION_BLOCK_ID: 4310 if (Error Err = ResolveDataLayout()) 4311 return Err; 4312 4313 // If this is the first function body we've seen, reverse the 4314 // FunctionsWithBodies list. 4315 if (!SeenFirstFunctionBody) { 4316 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end()); 4317 if (Error Err = globalCleanup()) 4318 return Err; 4319 SeenFirstFunctionBody = true; 4320 } 4321 4322 if (VSTOffset > 0) { 4323 // If we have a VST forward declaration record, make sure we 4324 // parse the VST now if we haven't already. It is needed to 4325 // set up the DeferredFunctionInfo vector for lazy reading. 4326 if (!SeenValueSymbolTable) { 4327 if (Error Err = BitcodeReader::parseValueSymbolTable(VSTOffset)) 4328 return Err; 4329 SeenValueSymbolTable = true; 4330 // Fall through so that we record the NextUnreadBit below. 4331 // This is necessary in case we have an anonymous function that 4332 // is later materialized. Since it will not have a VST entry we 4333 // need to fall back to the lazy parse to find its offset. 4334 } else { 4335 // If we have a VST forward declaration record, but have already 4336 // parsed the VST (just above, when the first function body was 4337 // encountered here), then we are resuming the parse after 4338 // materializing functions. The ResumeBit points to the 4339 // start of the last function block recorded in the 4340 // DeferredFunctionInfo map. Skip it. 4341 if (Error Err = Stream.SkipBlock()) 4342 return Err; 4343 continue; 4344 } 4345 } 4346 4347 // Support older bitcode files that did not have the function 4348 // index in the VST, nor a VST forward declaration record, as 4349 // well as anonymous functions that do not have VST entries. 4350 // Build the DeferredFunctionInfo vector on the fly. 4351 if (Error Err = rememberAndSkipFunctionBody()) 4352 return Err; 4353 4354 // Suspend parsing when we reach the function bodies. Subsequent 4355 // materialization calls will resume it when necessary. If the bitcode 4356 // file is old, the symbol table will be at the end instead and will not 4357 // have been seen yet. In this case, just finish the parse now. 4358 if (SeenValueSymbolTable) { 4359 NextUnreadBit = Stream.GetCurrentBitNo(); 4360 // After the VST has been parsed, we need to make sure intrinsic name 4361 // are auto-upgraded. 4362 return globalCleanup(); 4363 } 4364 break; 4365 case bitc::USELIST_BLOCK_ID: 4366 if (Error Err = parseUseLists()) 4367 return Err; 4368 break; 4369 case bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID: 4370 if (Error Err = parseOperandBundleTags()) 4371 return Err; 4372 break; 4373 case bitc::SYNC_SCOPE_NAMES_BLOCK_ID: 4374 if (Error Err = parseSyncScopeNames()) 4375 return Err; 4376 break; 4377 } 4378 continue; 4379 4380 case BitstreamEntry::Record: 4381 // The interesting case. 4382 break; 4383 } 4384 4385 // Read a record. 4386 Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record); 4387 if (!MaybeBitCode) 4388 return MaybeBitCode.takeError(); 4389 switch (unsigned BitCode = MaybeBitCode.get()) { 4390 default: break; // Default behavior, ignore unknown content. 4391 case bitc::MODULE_CODE_VERSION: { 4392 Expected<unsigned> VersionOrErr = parseVersionRecord(Record); 4393 if (!VersionOrErr) 4394 return VersionOrErr.takeError(); 4395 UseRelativeIDs = *VersionOrErr >= 1; 4396 break; 4397 } 4398 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N] 4399 if (ResolvedDataLayout) 4400 return error("target triple too late in module"); 4401 std::string S; 4402 if (convertToString(Record, 0, S)) 4403 return error("Invalid record"); 4404 TheModule->setTargetTriple(S); 4405 break; 4406 } 4407 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N] 4408 if (ResolvedDataLayout) 4409 return error("datalayout too late in module"); 4410 if (convertToString(Record, 0, TentativeDataLayoutStr)) 4411 return error("Invalid record"); 4412 break; 4413 } 4414 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N] 4415 std::string S; 4416 if (convertToString(Record, 0, S)) 4417 return error("Invalid record"); 4418 TheModule->setModuleInlineAsm(S); 4419 break; 4420 } 4421 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N] 4422 // Deprecated, but still needed to read old bitcode files. 4423 std::string S; 4424 if (convertToString(Record, 0, S)) 4425 return error("Invalid record"); 4426 // Ignore value. 4427 break; 4428 } 4429 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N] 4430 std::string S; 4431 if (convertToString(Record, 0, S)) 4432 return error("Invalid record"); 4433 SectionTable.push_back(S); 4434 break; 4435 } 4436 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N] 4437 std::string S; 4438 if (convertToString(Record, 0, S)) 4439 return error("Invalid record"); 4440 GCTable.push_back(S); 4441 break; 4442 } 4443 case bitc::MODULE_CODE_COMDAT: 4444 if (Error Err = parseComdatRecord(Record)) 4445 return Err; 4446 break; 4447 // FIXME: BitcodeReader should handle {GLOBALVAR, FUNCTION, ALIAS, IFUNC} 4448 // written by ThinLinkBitcodeWriter. See 4449 // `ThinLinkBitcodeWriter::writeSimplifiedModuleInfo` for the format of each 4450 // record 4451 // (https://github.com/llvm/llvm-project/blob/b6a93967d9c11e79802b5e75cec1584d6c8aa472/llvm/lib/Bitcode/Writer/BitcodeWriter.cpp#L4714) 4452 case bitc::MODULE_CODE_GLOBALVAR: 4453 if (Error Err = parseGlobalVarRecord(Record)) 4454 return Err; 4455 break; 4456 case bitc::MODULE_CODE_FUNCTION: 4457 if (Error Err = ResolveDataLayout()) 4458 return Err; 4459 if (Error Err = parseFunctionRecord(Record)) 4460 return Err; 4461 break; 4462 case bitc::MODULE_CODE_IFUNC: 4463 case bitc::MODULE_CODE_ALIAS: 4464 case bitc::MODULE_CODE_ALIAS_OLD: 4465 if (Error Err = parseGlobalIndirectSymbolRecord(BitCode, Record)) 4466 return Err; 4467 break; 4468 /// MODULE_CODE_VSTOFFSET: [offset] 4469 case bitc::MODULE_CODE_VSTOFFSET: 4470 if (Record.empty()) 4471 return error("Invalid record"); 4472 // Note that we subtract 1 here because the offset is relative to one word 4473 // before the start of the identification or module block, which was 4474 // historically always the start of the regular bitcode header. 4475 VSTOffset = Record[0] - 1; 4476 break; 4477 /// MODULE_CODE_SOURCE_FILENAME: [namechar x N] 4478 case bitc::MODULE_CODE_SOURCE_FILENAME: 4479 SmallString<128> ValueName; 4480 if (convertToString(Record, 0, ValueName)) 4481 return error("Invalid record"); 4482 TheModule->setSourceFileName(ValueName); 4483 break; 4484 } 4485 Record.clear(); 4486 } 4487 this->ValueTypeCallback = std::nullopt; 4488 return Error::success(); 4489 } 4490 4491 Error BitcodeReader::parseBitcodeInto(Module *M, bool ShouldLazyLoadMetadata, 4492 bool IsImporting, 4493 ParserCallbacks Callbacks) { 4494 TheModule = M; 4495 MetadataLoaderCallbacks MDCallbacks; 4496 MDCallbacks.GetTypeByID = [&](unsigned ID) { return getTypeByID(ID); }; 4497 MDCallbacks.GetContainedTypeID = [&](unsigned I, unsigned J) { 4498 return getContainedTypeID(I, J); 4499 }; 4500 MDCallbacks.MDType = Callbacks.MDType; 4501 MDLoader = MetadataLoader(Stream, *M, ValueList, IsImporting, MDCallbacks); 4502 return parseModule(0, ShouldLazyLoadMetadata, Callbacks); 4503 } 4504 4505 Error BitcodeReader::typeCheckLoadStoreInst(Type *ValType, Type *PtrType) { 4506 if (!isa<PointerType>(PtrType)) 4507 return error("Load/Store operand is not a pointer type"); 4508 if (!PointerType::isLoadableOrStorableType(ValType)) 4509 return error("Cannot load/store from pointer"); 4510 return Error::success(); 4511 } 4512 4513 Error BitcodeReader::propagateAttributeTypes(CallBase *CB, 4514 ArrayRef<unsigned> ArgTyIDs) { 4515 AttributeList Attrs = CB->getAttributes(); 4516 for (unsigned i = 0; i != CB->arg_size(); ++i) { 4517 for (Attribute::AttrKind Kind : {Attribute::ByVal, Attribute::StructRet, 4518 Attribute::InAlloca}) { 4519 if (!Attrs.hasParamAttr(i, Kind) || 4520 Attrs.getParamAttr(i, Kind).getValueAsType()) 4521 continue; 4522 4523 Type *PtrEltTy = getPtrElementTypeByID(ArgTyIDs[i]); 4524 if (!PtrEltTy) 4525 return error("Missing element type for typed attribute upgrade"); 4526 4527 Attribute NewAttr; 4528 switch (Kind) { 4529 case Attribute::ByVal: 4530 NewAttr = Attribute::getWithByValType(Context, PtrEltTy); 4531 break; 4532 case Attribute::StructRet: 4533 NewAttr = Attribute::getWithStructRetType(Context, PtrEltTy); 4534 break; 4535 case Attribute::InAlloca: 4536 NewAttr = Attribute::getWithInAllocaType(Context, PtrEltTy); 4537 break; 4538 default: 4539 llvm_unreachable("not an upgraded type attribute"); 4540 } 4541 4542 Attrs = Attrs.addParamAttribute(Context, i, NewAttr); 4543 } 4544 } 4545 4546 if (CB->isInlineAsm()) { 4547 const InlineAsm *IA = cast<InlineAsm>(CB->getCalledOperand()); 4548 unsigned ArgNo = 0; 4549 for (const InlineAsm::ConstraintInfo &CI : IA->ParseConstraints()) { 4550 if (!CI.hasArg()) 4551 continue; 4552 4553 if (CI.isIndirect && !Attrs.getParamElementType(ArgNo)) { 4554 Type *ElemTy = getPtrElementTypeByID(ArgTyIDs[ArgNo]); 4555 if (!ElemTy) 4556 return error("Missing element type for inline asm upgrade"); 4557 Attrs = Attrs.addParamAttribute( 4558 Context, ArgNo, 4559 Attribute::get(Context, Attribute::ElementType, ElemTy)); 4560 } 4561 4562 ArgNo++; 4563 } 4564 } 4565 4566 switch (CB->getIntrinsicID()) { 4567 case Intrinsic::preserve_array_access_index: 4568 case Intrinsic::preserve_struct_access_index: 4569 case Intrinsic::aarch64_ldaxr: 4570 case Intrinsic::aarch64_ldxr: 4571 case Intrinsic::aarch64_stlxr: 4572 case Intrinsic::aarch64_stxr: 4573 case Intrinsic::arm_ldaex: 4574 case Intrinsic::arm_ldrex: 4575 case Intrinsic::arm_stlex: 4576 case Intrinsic::arm_strex: { 4577 unsigned ArgNo; 4578 switch (CB->getIntrinsicID()) { 4579 case Intrinsic::aarch64_stlxr: 4580 case Intrinsic::aarch64_stxr: 4581 case Intrinsic::arm_stlex: 4582 case Intrinsic::arm_strex: 4583 ArgNo = 1; 4584 break; 4585 default: 4586 ArgNo = 0; 4587 break; 4588 } 4589 if (!Attrs.getParamElementType(ArgNo)) { 4590 Type *ElTy = getPtrElementTypeByID(ArgTyIDs[ArgNo]); 4591 if (!ElTy) 4592 return error("Missing element type for elementtype upgrade"); 4593 Attribute NewAttr = Attribute::get(Context, Attribute::ElementType, ElTy); 4594 Attrs = Attrs.addParamAttribute(Context, ArgNo, NewAttr); 4595 } 4596 break; 4597 } 4598 default: 4599 break; 4600 } 4601 4602 CB->setAttributes(Attrs); 4603 return Error::success(); 4604 } 4605 4606 /// Lazily parse the specified function body block. 4607 Error BitcodeReader::parseFunctionBody(Function *F) { 4608 if (Error Err = Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID)) 4609 return Err; 4610 4611 // Unexpected unresolved metadata when parsing function. 4612 if (MDLoader->hasFwdRefs()) 4613 return error("Invalid function metadata: incoming forward references"); 4614 4615 InstructionList.clear(); 4616 unsigned ModuleValueListSize = ValueList.size(); 4617 unsigned ModuleMDLoaderSize = MDLoader->size(); 4618 4619 // Add all the function arguments to the value table. 4620 unsigned ArgNo = 0; 4621 unsigned FTyID = FunctionTypeIDs[F]; 4622 for (Argument &I : F->args()) { 4623 unsigned ArgTyID = getContainedTypeID(FTyID, ArgNo + 1); 4624 assert(I.getType() == getTypeByID(ArgTyID) && 4625 "Incorrect fully specified type for Function Argument"); 4626 ValueList.push_back(&I, ArgTyID); 4627 ++ArgNo; 4628 } 4629 unsigned NextValueNo = ValueList.size(); 4630 BasicBlock *CurBB = nullptr; 4631 unsigned CurBBNo = 0; 4632 // Block into which constant expressions from phi nodes are materialized. 4633 BasicBlock *PhiConstExprBB = nullptr; 4634 // Edge blocks for phi nodes into which constant expressions have been 4635 // expanded. 4636 SmallMapVector<std::pair<BasicBlock *, BasicBlock *>, BasicBlock *, 4> 4637 ConstExprEdgeBBs; 4638 4639 DebugLoc LastLoc; 4640 auto getLastInstruction = [&]() -> Instruction * { 4641 if (CurBB && !CurBB->empty()) 4642 return &CurBB->back(); 4643 else if (CurBBNo && FunctionBBs[CurBBNo - 1] && 4644 !FunctionBBs[CurBBNo - 1]->empty()) 4645 return &FunctionBBs[CurBBNo - 1]->back(); 4646 return nullptr; 4647 }; 4648 4649 std::vector<OperandBundleDef> OperandBundles; 4650 4651 // Read all the records. 4652 SmallVector<uint64_t, 64> Record; 4653 4654 while (true) { 4655 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance(); 4656 if (!MaybeEntry) 4657 return MaybeEntry.takeError(); 4658 llvm::BitstreamEntry Entry = MaybeEntry.get(); 4659 4660 switch (Entry.Kind) { 4661 case BitstreamEntry::Error: 4662 return error("Malformed block"); 4663 case BitstreamEntry::EndBlock: 4664 goto OutOfRecordLoop; 4665 4666 case BitstreamEntry::SubBlock: 4667 switch (Entry.ID) { 4668 default: // Skip unknown content. 4669 if (Error Err = Stream.SkipBlock()) 4670 return Err; 4671 break; 4672 case bitc::CONSTANTS_BLOCK_ID: 4673 if (Error Err = parseConstants()) 4674 return Err; 4675 NextValueNo = ValueList.size(); 4676 break; 4677 case bitc::VALUE_SYMTAB_BLOCK_ID: 4678 if (Error Err = parseValueSymbolTable()) 4679 return Err; 4680 break; 4681 case bitc::METADATA_ATTACHMENT_ID: 4682 if (Error Err = MDLoader->parseMetadataAttachment(*F, InstructionList)) 4683 return Err; 4684 break; 4685 case bitc::METADATA_BLOCK_ID: 4686 assert(DeferredMetadataInfo.empty() && 4687 "Must read all module-level metadata before function-level"); 4688 if (Error Err = MDLoader->parseFunctionMetadata()) 4689 return Err; 4690 break; 4691 case bitc::USELIST_BLOCK_ID: 4692 if (Error Err = parseUseLists()) 4693 return Err; 4694 break; 4695 } 4696 continue; 4697 4698 case BitstreamEntry::Record: 4699 // The interesting case. 4700 break; 4701 } 4702 4703 // Read a record. 4704 Record.clear(); 4705 Instruction *I = nullptr; 4706 unsigned ResTypeID = InvalidTypeID; 4707 Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record); 4708 if (!MaybeBitCode) 4709 return MaybeBitCode.takeError(); 4710 switch (unsigned BitCode = MaybeBitCode.get()) { 4711 default: // Default behavior: reject 4712 return error("Invalid value"); 4713 case bitc::FUNC_CODE_DECLAREBLOCKS: { // DECLAREBLOCKS: [nblocks] 4714 if (Record.empty() || Record[0] == 0) 4715 return error("Invalid record"); 4716 // Create all the basic blocks for the function. 4717 FunctionBBs.resize(Record[0]); 4718 4719 // See if anything took the address of blocks in this function. 4720 auto BBFRI = BasicBlockFwdRefs.find(F); 4721 if (BBFRI == BasicBlockFwdRefs.end()) { 4722 for (BasicBlock *&BB : FunctionBBs) 4723 BB = BasicBlock::Create(Context, "", F); 4724 } else { 4725 auto &BBRefs = BBFRI->second; 4726 // Check for invalid basic block references. 4727 if (BBRefs.size() > FunctionBBs.size()) 4728 return error("Invalid ID"); 4729 assert(!BBRefs.empty() && "Unexpected empty array"); 4730 assert(!BBRefs.front() && "Invalid reference to entry block"); 4731 for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E; 4732 ++I) 4733 if (I < RE && BBRefs[I]) { 4734 BBRefs[I]->insertInto(F); 4735 FunctionBBs[I] = BBRefs[I]; 4736 } else { 4737 FunctionBBs[I] = BasicBlock::Create(Context, "", F); 4738 } 4739 4740 // Erase from the table. 4741 BasicBlockFwdRefs.erase(BBFRI); 4742 } 4743 4744 CurBB = FunctionBBs[0]; 4745 continue; 4746 } 4747 4748 case bitc::FUNC_CODE_BLOCKADDR_USERS: // BLOCKADDR_USERS: [vals...] 4749 // The record should not be emitted if it's an empty list. 4750 if (Record.empty()) 4751 return error("Invalid record"); 4752 // When we have the RARE case of a BlockAddress Constant that is not 4753 // scoped to the Function it refers to, we need to conservatively 4754 // materialize the referred to Function, regardless of whether or not 4755 // that Function will ultimately be linked, otherwise users of 4756 // BitcodeReader might start splicing out Function bodies such that we 4757 // might no longer be able to materialize the BlockAddress since the 4758 // BasicBlock (and entire body of the Function) the BlockAddress refers 4759 // to may have been moved. In the case that the user of BitcodeReader 4760 // decides ultimately not to link the Function body, materializing here 4761 // could be considered wasteful, but it's better than a deserialization 4762 // failure as described. This keeps BitcodeReader unaware of complex 4763 // linkage policy decisions such as those use by LTO, leaving those 4764 // decisions "one layer up." 4765 for (uint64_t ValID : Record) 4766 if (auto *F = dyn_cast<Function>(ValueList[ValID])) 4767 BackwardRefFunctions.push_back(F); 4768 else 4769 return error("Invalid record"); 4770 4771 continue; 4772 4773 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN 4774 // This record indicates that the last instruction is at the same 4775 // location as the previous instruction with a location. 4776 I = getLastInstruction(); 4777 4778 if (!I) 4779 return error("Invalid record"); 4780 I->setDebugLoc(LastLoc); 4781 I = nullptr; 4782 continue; 4783 4784 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia] 4785 I = getLastInstruction(); 4786 if (!I || Record.size() < 4) 4787 return error("Invalid record"); 4788 4789 unsigned Line = Record[0], Col = Record[1]; 4790 unsigned ScopeID = Record[2], IAID = Record[3]; 4791 bool isImplicitCode = Record.size() == 5 && Record[4]; 4792 4793 MDNode *Scope = nullptr, *IA = nullptr; 4794 if (ScopeID) { 4795 Scope = dyn_cast_or_null<MDNode>( 4796 MDLoader->getMetadataFwdRefOrLoad(ScopeID - 1)); 4797 if (!Scope) 4798 return error("Invalid record"); 4799 } 4800 if (IAID) { 4801 IA = dyn_cast_or_null<MDNode>( 4802 MDLoader->getMetadataFwdRefOrLoad(IAID - 1)); 4803 if (!IA) 4804 return error("Invalid record"); 4805 } 4806 LastLoc = DILocation::get(Scope->getContext(), Line, Col, Scope, IA, 4807 isImplicitCode); 4808 I->setDebugLoc(LastLoc); 4809 I = nullptr; 4810 continue; 4811 } 4812 case bitc::FUNC_CODE_INST_UNOP: { // UNOP: [opval, ty, opcode] 4813 unsigned OpNum = 0; 4814 Value *LHS; 4815 unsigned TypeID; 4816 if (getValueTypePair(Record, OpNum, NextValueNo, LHS, TypeID, CurBB) || 4817 OpNum+1 > Record.size()) 4818 return error("Invalid record"); 4819 4820 int Opc = getDecodedUnaryOpcode(Record[OpNum++], LHS->getType()); 4821 if (Opc == -1) 4822 return error("Invalid record"); 4823 I = UnaryOperator::Create((Instruction::UnaryOps)Opc, LHS); 4824 ResTypeID = TypeID; 4825 InstructionList.push_back(I); 4826 if (OpNum < Record.size()) { 4827 if (isa<FPMathOperator>(I)) { 4828 FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]); 4829 if (FMF.any()) 4830 I->setFastMathFlags(FMF); 4831 } 4832 } 4833 break; 4834 } 4835 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode] 4836 unsigned OpNum = 0; 4837 Value *LHS, *RHS; 4838 unsigned TypeID; 4839 if (getValueTypePair(Record, OpNum, NextValueNo, LHS, TypeID, CurBB) || 4840 popValue(Record, OpNum, NextValueNo, LHS->getType(), TypeID, RHS, 4841 CurBB) || 4842 OpNum+1 > Record.size()) 4843 return error("Invalid record"); 4844 4845 int Opc = getDecodedBinaryOpcode(Record[OpNum++], LHS->getType()); 4846 if (Opc == -1) 4847 return error("Invalid record"); 4848 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS); 4849 ResTypeID = TypeID; 4850 InstructionList.push_back(I); 4851 if (OpNum < Record.size()) { 4852 if (Opc == Instruction::Add || 4853 Opc == Instruction::Sub || 4854 Opc == Instruction::Mul || 4855 Opc == Instruction::Shl) { 4856 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP)) 4857 cast<BinaryOperator>(I)->setHasNoSignedWrap(true); 4858 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP)) 4859 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true); 4860 } else if (Opc == Instruction::SDiv || 4861 Opc == Instruction::UDiv || 4862 Opc == Instruction::LShr || 4863 Opc == Instruction::AShr) { 4864 if (Record[OpNum] & (1 << bitc::PEO_EXACT)) 4865 cast<BinaryOperator>(I)->setIsExact(true); 4866 } else if (isa<FPMathOperator>(I)) { 4867 FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]); 4868 if (FMF.any()) 4869 I->setFastMathFlags(FMF); 4870 } 4871 4872 } 4873 break; 4874 } 4875 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc] 4876 unsigned OpNum = 0; 4877 Value *Op; 4878 unsigned OpTypeID; 4879 if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB) || 4880 OpNum + 1 > Record.size()) 4881 return error("Invalid record"); 4882 4883 ResTypeID = Record[OpNum++]; 4884 Type *ResTy = getTypeByID(ResTypeID); 4885 int Opc = getDecodedCastOpcode(Record[OpNum++]); 4886 4887 if (Opc == -1 || !ResTy) 4888 return error("Invalid record"); 4889 Instruction *Temp = nullptr; 4890 if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) { 4891 if (Temp) { 4892 InstructionList.push_back(Temp); 4893 assert(CurBB && "No current BB?"); 4894 Temp->insertInto(CurBB, CurBB->end()); 4895 } 4896 } else { 4897 auto CastOp = (Instruction::CastOps)Opc; 4898 if (!CastInst::castIsValid(CastOp, Op, ResTy)) 4899 return error("Invalid cast"); 4900 I = CastInst::Create(CastOp, Op, ResTy); 4901 } 4902 if (OpNum < Record.size() && isa<PossiblyNonNegInst>(I) && 4903 (Record[OpNum] & (1 << bitc::PNNI_NON_NEG))) 4904 I->setNonNeg(true); 4905 InstructionList.push_back(I); 4906 break; 4907 } 4908 case bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD: 4909 case bitc::FUNC_CODE_INST_GEP_OLD: 4910 case bitc::FUNC_CODE_INST_GEP: { // GEP: type, [n x operands] 4911 unsigned OpNum = 0; 4912 4913 unsigned TyID; 4914 Type *Ty; 4915 bool InBounds; 4916 4917 if (BitCode == bitc::FUNC_CODE_INST_GEP) { 4918 InBounds = Record[OpNum++]; 4919 TyID = Record[OpNum++]; 4920 Ty = getTypeByID(TyID); 4921 } else { 4922 InBounds = BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD; 4923 TyID = InvalidTypeID; 4924 Ty = nullptr; 4925 } 4926 4927 Value *BasePtr; 4928 unsigned BasePtrTypeID; 4929 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr, BasePtrTypeID, 4930 CurBB)) 4931 return error("Invalid record"); 4932 4933 if (!Ty) { 4934 TyID = getContainedTypeID(BasePtrTypeID); 4935 if (BasePtr->getType()->isVectorTy()) 4936 TyID = getContainedTypeID(TyID); 4937 Ty = getTypeByID(TyID); 4938 } 4939 4940 SmallVector<Value*, 16> GEPIdx; 4941 while (OpNum != Record.size()) { 4942 Value *Op; 4943 unsigned OpTypeID; 4944 if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB)) 4945 return error("Invalid record"); 4946 GEPIdx.push_back(Op); 4947 } 4948 4949 I = GetElementPtrInst::Create(Ty, BasePtr, GEPIdx); 4950 4951 ResTypeID = TyID; 4952 if (cast<GEPOperator>(I)->getNumIndices() != 0) { 4953 auto GTI = std::next(gep_type_begin(I)); 4954 for (Value *Idx : drop_begin(cast<GEPOperator>(I)->indices())) { 4955 unsigned SubType = 0; 4956 if (GTI.isStruct()) { 4957 ConstantInt *IdxC = 4958 Idx->getType()->isVectorTy() 4959 ? cast<ConstantInt>(cast<Constant>(Idx)->getSplatValue()) 4960 : cast<ConstantInt>(Idx); 4961 SubType = IdxC->getZExtValue(); 4962 } 4963 ResTypeID = getContainedTypeID(ResTypeID, SubType); 4964 ++GTI; 4965 } 4966 } 4967 4968 // At this point ResTypeID is the result element type. We need a pointer 4969 // or vector of pointer to it. 4970 ResTypeID = getVirtualTypeID(I->getType()->getScalarType(), ResTypeID); 4971 if (I->getType()->isVectorTy()) 4972 ResTypeID = getVirtualTypeID(I->getType(), ResTypeID); 4973 4974 InstructionList.push_back(I); 4975 if (InBounds) 4976 cast<GetElementPtrInst>(I)->setIsInBounds(true); 4977 break; 4978 } 4979 4980 case bitc::FUNC_CODE_INST_EXTRACTVAL: { 4981 // EXTRACTVAL: [opty, opval, n x indices] 4982 unsigned OpNum = 0; 4983 Value *Agg; 4984 unsigned AggTypeID; 4985 if (getValueTypePair(Record, OpNum, NextValueNo, Agg, AggTypeID, CurBB)) 4986 return error("Invalid record"); 4987 Type *Ty = Agg->getType(); 4988 4989 unsigned RecSize = Record.size(); 4990 if (OpNum == RecSize) 4991 return error("EXTRACTVAL: Invalid instruction with 0 indices"); 4992 4993 SmallVector<unsigned, 4> EXTRACTVALIdx; 4994 ResTypeID = AggTypeID; 4995 for (; OpNum != RecSize; ++OpNum) { 4996 bool IsArray = Ty->isArrayTy(); 4997 bool IsStruct = Ty->isStructTy(); 4998 uint64_t Index = Record[OpNum]; 4999 5000 if (!IsStruct && !IsArray) 5001 return error("EXTRACTVAL: Invalid type"); 5002 if ((unsigned)Index != Index) 5003 return error("Invalid value"); 5004 if (IsStruct && Index >= Ty->getStructNumElements()) 5005 return error("EXTRACTVAL: Invalid struct index"); 5006 if (IsArray && Index >= Ty->getArrayNumElements()) 5007 return error("EXTRACTVAL: Invalid array index"); 5008 EXTRACTVALIdx.push_back((unsigned)Index); 5009 5010 if (IsStruct) { 5011 Ty = Ty->getStructElementType(Index); 5012 ResTypeID = getContainedTypeID(ResTypeID, Index); 5013 } else { 5014 Ty = Ty->getArrayElementType(); 5015 ResTypeID = getContainedTypeID(ResTypeID); 5016 } 5017 } 5018 5019 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx); 5020 InstructionList.push_back(I); 5021 break; 5022 } 5023 5024 case bitc::FUNC_CODE_INST_INSERTVAL: { 5025 // INSERTVAL: [opty, opval, opty, opval, n x indices] 5026 unsigned OpNum = 0; 5027 Value *Agg; 5028 unsigned AggTypeID; 5029 if (getValueTypePair(Record, OpNum, NextValueNo, Agg, AggTypeID, CurBB)) 5030 return error("Invalid record"); 5031 Value *Val; 5032 unsigned ValTypeID; 5033 if (getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID, CurBB)) 5034 return error("Invalid record"); 5035 5036 unsigned RecSize = Record.size(); 5037 if (OpNum == RecSize) 5038 return error("INSERTVAL: Invalid instruction with 0 indices"); 5039 5040 SmallVector<unsigned, 4> INSERTVALIdx; 5041 Type *CurTy = Agg->getType(); 5042 for (; OpNum != RecSize; ++OpNum) { 5043 bool IsArray = CurTy->isArrayTy(); 5044 bool IsStruct = CurTy->isStructTy(); 5045 uint64_t Index = Record[OpNum]; 5046 5047 if (!IsStruct && !IsArray) 5048 return error("INSERTVAL: Invalid type"); 5049 if ((unsigned)Index != Index) 5050 return error("Invalid value"); 5051 if (IsStruct && Index >= CurTy->getStructNumElements()) 5052 return error("INSERTVAL: Invalid struct index"); 5053 if (IsArray && Index >= CurTy->getArrayNumElements()) 5054 return error("INSERTVAL: Invalid array index"); 5055 5056 INSERTVALIdx.push_back((unsigned)Index); 5057 if (IsStruct) 5058 CurTy = CurTy->getStructElementType(Index); 5059 else 5060 CurTy = CurTy->getArrayElementType(); 5061 } 5062 5063 if (CurTy != Val->getType()) 5064 return error("Inserted value type doesn't match aggregate type"); 5065 5066 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx); 5067 ResTypeID = AggTypeID; 5068 InstructionList.push_back(I); 5069 break; 5070 } 5071 5072 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval] 5073 // obsolete form of select 5074 // handles select i1 ... in old bitcode 5075 unsigned OpNum = 0; 5076 Value *TrueVal, *FalseVal, *Cond; 5077 unsigned TypeID; 5078 Type *CondType = Type::getInt1Ty(Context); 5079 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal, TypeID, 5080 CurBB) || 5081 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), TypeID, 5082 FalseVal, CurBB) || 5083 popValue(Record, OpNum, NextValueNo, CondType, 5084 getVirtualTypeID(CondType), Cond, CurBB)) 5085 return error("Invalid record"); 5086 5087 I = SelectInst::Create(Cond, TrueVal, FalseVal); 5088 ResTypeID = TypeID; 5089 InstructionList.push_back(I); 5090 break; 5091 } 5092 5093 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred] 5094 // new form of select 5095 // handles select i1 or select [N x i1] 5096 unsigned OpNum = 0; 5097 Value *TrueVal, *FalseVal, *Cond; 5098 unsigned ValTypeID, CondTypeID; 5099 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal, ValTypeID, 5100 CurBB) || 5101 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), ValTypeID, 5102 FalseVal, CurBB) || 5103 getValueTypePair(Record, OpNum, NextValueNo, Cond, CondTypeID, CurBB)) 5104 return error("Invalid record"); 5105 5106 // select condition can be either i1 or [N x i1] 5107 if (VectorType* vector_type = 5108 dyn_cast<VectorType>(Cond->getType())) { 5109 // expect <n x i1> 5110 if (vector_type->getElementType() != Type::getInt1Ty(Context)) 5111 return error("Invalid type for value"); 5112 } else { 5113 // expect i1 5114 if (Cond->getType() != Type::getInt1Ty(Context)) 5115 return error("Invalid type for value"); 5116 } 5117 5118 I = SelectInst::Create(Cond, TrueVal, FalseVal); 5119 ResTypeID = ValTypeID; 5120 InstructionList.push_back(I); 5121 if (OpNum < Record.size() && isa<FPMathOperator>(I)) { 5122 FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]); 5123 if (FMF.any()) 5124 I->setFastMathFlags(FMF); 5125 } 5126 break; 5127 } 5128 5129 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval] 5130 unsigned OpNum = 0; 5131 Value *Vec, *Idx; 5132 unsigned VecTypeID, IdxTypeID; 5133 if (getValueTypePair(Record, OpNum, NextValueNo, Vec, VecTypeID, CurBB) || 5134 getValueTypePair(Record, OpNum, NextValueNo, Idx, IdxTypeID, CurBB)) 5135 return error("Invalid record"); 5136 if (!Vec->getType()->isVectorTy()) 5137 return error("Invalid type for value"); 5138 I = ExtractElementInst::Create(Vec, Idx); 5139 ResTypeID = getContainedTypeID(VecTypeID); 5140 InstructionList.push_back(I); 5141 break; 5142 } 5143 5144 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval] 5145 unsigned OpNum = 0; 5146 Value *Vec, *Elt, *Idx; 5147 unsigned VecTypeID, IdxTypeID; 5148 if (getValueTypePair(Record, OpNum, NextValueNo, Vec, VecTypeID, CurBB)) 5149 return error("Invalid record"); 5150 if (!Vec->getType()->isVectorTy()) 5151 return error("Invalid type for value"); 5152 if (popValue(Record, OpNum, NextValueNo, 5153 cast<VectorType>(Vec->getType())->getElementType(), 5154 getContainedTypeID(VecTypeID), Elt, CurBB) || 5155 getValueTypePair(Record, OpNum, NextValueNo, Idx, IdxTypeID, CurBB)) 5156 return error("Invalid record"); 5157 I = InsertElementInst::Create(Vec, Elt, Idx); 5158 ResTypeID = VecTypeID; 5159 InstructionList.push_back(I); 5160 break; 5161 } 5162 5163 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval] 5164 unsigned OpNum = 0; 5165 Value *Vec1, *Vec2, *Mask; 5166 unsigned Vec1TypeID; 5167 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1, Vec1TypeID, 5168 CurBB) || 5169 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec1TypeID, 5170 Vec2, CurBB)) 5171 return error("Invalid record"); 5172 5173 unsigned MaskTypeID; 5174 if (getValueTypePair(Record, OpNum, NextValueNo, Mask, MaskTypeID, CurBB)) 5175 return error("Invalid record"); 5176 if (!Vec1->getType()->isVectorTy() || !Vec2->getType()->isVectorTy()) 5177 return error("Invalid type for value"); 5178 5179 I = new ShuffleVectorInst(Vec1, Vec2, Mask); 5180 ResTypeID = 5181 getVirtualTypeID(I->getType(), getContainedTypeID(Vec1TypeID)); 5182 InstructionList.push_back(I); 5183 break; 5184 } 5185 5186 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred] 5187 // Old form of ICmp/FCmp returning bool 5188 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were 5189 // both legal on vectors but had different behaviour. 5190 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred] 5191 // FCmp/ICmp returning bool or vector of bool 5192 5193 unsigned OpNum = 0; 5194 Value *LHS, *RHS; 5195 unsigned LHSTypeID; 5196 if (getValueTypePair(Record, OpNum, NextValueNo, LHS, LHSTypeID, CurBB) || 5197 popValue(Record, OpNum, NextValueNo, LHS->getType(), LHSTypeID, RHS, 5198 CurBB)) 5199 return error("Invalid record"); 5200 5201 if (OpNum >= Record.size()) 5202 return error( 5203 "Invalid record: operand number exceeded available operands"); 5204 5205 unsigned PredVal = Record[OpNum]; 5206 bool IsFP = LHS->getType()->isFPOrFPVectorTy(); 5207 FastMathFlags FMF; 5208 if (IsFP && Record.size() > OpNum+1) 5209 FMF = getDecodedFastMathFlags(Record[++OpNum]); 5210 5211 if (OpNum+1 != Record.size()) 5212 return error("Invalid record"); 5213 5214 if (LHS->getType()->isFPOrFPVectorTy()) 5215 I = new FCmpInst((FCmpInst::Predicate)PredVal, LHS, RHS); 5216 else 5217 I = new ICmpInst((ICmpInst::Predicate)PredVal, LHS, RHS); 5218 5219 ResTypeID = getVirtualTypeID(I->getType()->getScalarType()); 5220 if (LHS->getType()->isVectorTy()) 5221 ResTypeID = getVirtualTypeID(I->getType(), ResTypeID); 5222 5223 if (FMF.any()) 5224 I->setFastMathFlags(FMF); 5225 InstructionList.push_back(I); 5226 break; 5227 } 5228 5229 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>] 5230 { 5231 unsigned Size = Record.size(); 5232 if (Size == 0) { 5233 I = ReturnInst::Create(Context); 5234 InstructionList.push_back(I); 5235 break; 5236 } 5237 5238 unsigned OpNum = 0; 5239 Value *Op = nullptr; 5240 unsigned OpTypeID; 5241 if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB)) 5242 return error("Invalid record"); 5243 if (OpNum != Record.size()) 5244 return error("Invalid record"); 5245 5246 I = ReturnInst::Create(Context, Op); 5247 InstructionList.push_back(I); 5248 break; 5249 } 5250 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#] 5251 if (Record.size() != 1 && Record.size() != 3) 5252 return error("Invalid record"); 5253 BasicBlock *TrueDest = getBasicBlock(Record[0]); 5254 if (!TrueDest) 5255 return error("Invalid record"); 5256 5257 if (Record.size() == 1) { 5258 I = BranchInst::Create(TrueDest); 5259 InstructionList.push_back(I); 5260 } 5261 else { 5262 BasicBlock *FalseDest = getBasicBlock(Record[1]); 5263 Type *CondType = Type::getInt1Ty(Context); 5264 Value *Cond = getValue(Record, 2, NextValueNo, CondType, 5265 getVirtualTypeID(CondType), CurBB); 5266 if (!FalseDest || !Cond) 5267 return error("Invalid record"); 5268 I = BranchInst::Create(TrueDest, FalseDest, Cond); 5269 InstructionList.push_back(I); 5270 } 5271 break; 5272 } 5273 case bitc::FUNC_CODE_INST_CLEANUPRET: { // CLEANUPRET: [val] or [val,bb#] 5274 if (Record.size() != 1 && Record.size() != 2) 5275 return error("Invalid record"); 5276 unsigned Idx = 0; 5277 Type *TokenTy = Type::getTokenTy(Context); 5278 Value *CleanupPad = getValue(Record, Idx++, NextValueNo, TokenTy, 5279 getVirtualTypeID(TokenTy), CurBB); 5280 if (!CleanupPad) 5281 return error("Invalid record"); 5282 BasicBlock *UnwindDest = nullptr; 5283 if (Record.size() == 2) { 5284 UnwindDest = getBasicBlock(Record[Idx++]); 5285 if (!UnwindDest) 5286 return error("Invalid record"); 5287 } 5288 5289 I = CleanupReturnInst::Create(CleanupPad, UnwindDest); 5290 InstructionList.push_back(I); 5291 break; 5292 } 5293 case bitc::FUNC_CODE_INST_CATCHRET: { // CATCHRET: [val,bb#] 5294 if (Record.size() != 2) 5295 return error("Invalid record"); 5296 unsigned Idx = 0; 5297 Type *TokenTy = Type::getTokenTy(Context); 5298 Value *CatchPad = getValue(Record, Idx++, NextValueNo, TokenTy, 5299 getVirtualTypeID(TokenTy), CurBB); 5300 if (!CatchPad) 5301 return error("Invalid record"); 5302 BasicBlock *BB = getBasicBlock(Record[Idx++]); 5303 if (!BB) 5304 return error("Invalid record"); 5305 5306 I = CatchReturnInst::Create(CatchPad, BB); 5307 InstructionList.push_back(I); 5308 break; 5309 } 5310 case bitc::FUNC_CODE_INST_CATCHSWITCH: { // CATCHSWITCH: [tok,num,(bb)*,bb?] 5311 // We must have, at minimum, the outer scope and the number of arguments. 5312 if (Record.size() < 2) 5313 return error("Invalid record"); 5314 5315 unsigned Idx = 0; 5316 5317 Type *TokenTy = Type::getTokenTy(Context); 5318 Value *ParentPad = getValue(Record, Idx++, NextValueNo, TokenTy, 5319 getVirtualTypeID(TokenTy), CurBB); 5320 5321 unsigned NumHandlers = Record[Idx++]; 5322 5323 SmallVector<BasicBlock *, 2> Handlers; 5324 for (unsigned Op = 0; Op != NumHandlers; ++Op) { 5325 BasicBlock *BB = getBasicBlock(Record[Idx++]); 5326 if (!BB) 5327 return error("Invalid record"); 5328 Handlers.push_back(BB); 5329 } 5330 5331 BasicBlock *UnwindDest = nullptr; 5332 if (Idx + 1 == Record.size()) { 5333 UnwindDest = getBasicBlock(Record[Idx++]); 5334 if (!UnwindDest) 5335 return error("Invalid record"); 5336 } 5337 5338 if (Record.size() != Idx) 5339 return error("Invalid record"); 5340 5341 auto *CatchSwitch = 5342 CatchSwitchInst::Create(ParentPad, UnwindDest, NumHandlers); 5343 for (BasicBlock *Handler : Handlers) 5344 CatchSwitch->addHandler(Handler); 5345 I = CatchSwitch; 5346 ResTypeID = getVirtualTypeID(I->getType()); 5347 InstructionList.push_back(I); 5348 break; 5349 } 5350 case bitc::FUNC_CODE_INST_CATCHPAD: 5351 case bitc::FUNC_CODE_INST_CLEANUPPAD: { // [tok,num,(ty,val)*] 5352 // We must have, at minimum, the outer scope and the number of arguments. 5353 if (Record.size() < 2) 5354 return error("Invalid record"); 5355 5356 unsigned Idx = 0; 5357 5358 Type *TokenTy = Type::getTokenTy(Context); 5359 Value *ParentPad = getValue(Record, Idx++, NextValueNo, TokenTy, 5360 getVirtualTypeID(TokenTy), CurBB); 5361 5362 unsigned NumArgOperands = Record[Idx++]; 5363 5364 SmallVector<Value *, 2> Args; 5365 for (unsigned Op = 0; Op != NumArgOperands; ++Op) { 5366 Value *Val; 5367 unsigned ValTypeID; 5368 if (getValueTypePair(Record, Idx, NextValueNo, Val, ValTypeID, nullptr)) 5369 return error("Invalid record"); 5370 Args.push_back(Val); 5371 } 5372 5373 if (Record.size() != Idx) 5374 return error("Invalid record"); 5375 5376 if (BitCode == bitc::FUNC_CODE_INST_CLEANUPPAD) 5377 I = CleanupPadInst::Create(ParentPad, Args); 5378 else 5379 I = CatchPadInst::Create(ParentPad, Args); 5380 ResTypeID = getVirtualTypeID(I->getType()); 5381 InstructionList.push_back(I); 5382 break; 5383 } 5384 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...] 5385 // Check magic 5386 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) { 5387 // "New" SwitchInst format with case ranges. The changes to write this 5388 // format were reverted but we still recognize bitcode that uses it. 5389 // Hopefully someday we will have support for case ranges and can use 5390 // this format again. 5391 5392 unsigned OpTyID = Record[1]; 5393 Type *OpTy = getTypeByID(OpTyID); 5394 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth(); 5395 5396 Value *Cond = getValue(Record, 2, NextValueNo, OpTy, OpTyID, CurBB); 5397 BasicBlock *Default = getBasicBlock(Record[3]); 5398 if (!OpTy || !Cond || !Default) 5399 return error("Invalid record"); 5400 5401 unsigned NumCases = Record[4]; 5402 5403 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases); 5404 InstructionList.push_back(SI); 5405 5406 unsigned CurIdx = 5; 5407 for (unsigned i = 0; i != NumCases; ++i) { 5408 SmallVector<ConstantInt*, 1> CaseVals; 5409 unsigned NumItems = Record[CurIdx++]; 5410 for (unsigned ci = 0; ci != NumItems; ++ci) { 5411 bool isSingleNumber = Record[CurIdx++]; 5412 5413 APInt Low; 5414 unsigned ActiveWords = 1; 5415 if (ValueBitWidth > 64) 5416 ActiveWords = Record[CurIdx++]; 5417 Low = readWideAPInt(ArrayRef(&Record[CurIdx], ActiveWords), 5418 ValueBitWidth); 5419 CurIdx += ActiveWords; 5420 5421 if (!isSingleNumber) { 5422 ActiveWords = 1; 5423 if (ValueBitWidth > 64) 5424 ActiveWords = Record[CurIdx++]; 5425 APInt High = readWideAPInt(ArrayRef(&Record[CurIdx], ActiveWords), 5426 ValueBitWidth); 5427 CurIdx += ActiveWords; 5428 5429 // FIXME: It is not clear whether values in the range should be 5430 // compared as signed or unsigned values. The partially 5431 // implemented changes that used this format in the past used 5432 // unsigned comparisons. 5433 for ( ; Low.ule(High); ++Low) 5434 CaseVals.push_back(ConstantInt::get(Context, Low)); 5435 } else 5436 CaseVals.push_back(ConstantInt::get(Context, Low)); 5437 } 5438 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]); 5439 for (ConstantInt *Cst : CaseVals) 5440 SI->addCase(Cst, DestBB); 5441 } 5442 I = SI; 5443 break; 5444 } 5445 5446 // Old SwitchInst format without case ranges. 5447 5448 if (Record.size() < 3 || (Record.size() & 1) == 0) 5449 return error("Invalid record"); 5450 unsigned OpTyID = Record[0]; 5451 Type *OpTy = getTypeByID(OpTyID); 5452 Value *Cond = getValue(Record, 1, NextValueNo, OpTy, OpTyID, CurBB); 5453 BasicBlock *Default = getBasicBlock(Record[2]); 5454 if (!OpTy || !Cond || !Default) 5455 return error("Invalid record"); 5456 unsigned NumCases = (Record.size()-3)/2; 5457 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases); 5458 InstructionList.push_back(SI); 5459 for (unsigned i = 0, e = NumCases; i != e; ++i) { 5460 ConstantInt *CaseVal = dyn_cast_or_null<ConstantInt>( 5461 getFnValueByID(Record[3+i*2], OpTy, OpTyID, nullptr)); 5462 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]); 5463 if (!CaseVal || !DestBB) { 5464 delete SI; 5465 return error("Invalid record"); 5466 } 5467 SI->addCase(CaseVal, DestBB); 5468 } 5469 I = SI; 5470 break; 5471 } 5472 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...] 5473 if (Record.size() < 2) 5474 return error("Invalid record"); 5475 unsigned OpTyID = Record[0]; 5476 Type *OpTy = getTypeByID(OpTyID); 5477 Value *Address = getValue(Record, 1, NextValueNo, OpTy, OpTyID, CurBB); 5478 if (!OpTy || !Address) 5479 return error("Invalid record"); 5480 unsigned NumDests = Record.size()-2; 5481 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests); 5482 InstructionList.push_back(IBI); 5483 for (unsigned i = 0, e = NumDests; i != e; ++i) { 5484 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) { 5485 IBI->addDestination(DestBB); 5486 } else { 5487 delete IBI; 5488 return error("Invalid record"); 5489 } 5490 } 5491 I = IBI; 5492 break; 5493 } 5494 5495 case bitc::FUNC_CODE_INST_INVOKE: { 5496 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...] 5497 if (Record.size() < 4) 5498 return error("Invalid record"); 5499 unsigned OpNum = 0; 5500 AttributeList PAL = getAttributes(Record[OpNum++]); 5501 unsigned CCInfo = Record[OpNum++]; 5502 BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]); 5503 BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]); 5504 5505 unsigned FTyID = InvalidTypeID; 5506 FunctionType *FTy = nullptr; 5507 if ((CCInfo >> 13) & 1) { 5508 FTyID = Record[OpNum++]; 5509 FTy = dyn_cast<FunctionType>(getTypeByID(FTyID)); 5510 if (!FTy) 5511 return error("Explicit invoke type is not a function type"); 5512 } 5513 5514 Value *Callee; 5515 unsigned CalleeTypeID; 5516 if (getValueTypePair(Record, OpNum, NextValueNo, Callee, CalleeTypeID, 5517 CurBB)) 5518 return error("Invalid record"); 5519 5520 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType()); 5521 if (!CalleeTy) 5522 return error("Callee is not a pointer"); 5523 if (!FTy) { 5524 FTyID = getContainedTypeID(CalleeTypeID); 5525 FTy = dyn_cast_or_null<FunctionType>(getTypeByID(FTyID)); 5526 if (!FTy) 5527 return error("Callee is not of pointer to function type"); 5528 } 5529 if (Record.size() < FTy->getNumParams() + OpNum) 5530 return error("Insufficient operands to call"); 5531 5532 SmallVector<Value*, 16> Ops; 5533 SmallVector<unsigned, 16> ArgTyIDs; 5534 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) { 5535 unsigned ArgTyID = getContainedTypeID(FTyID, i + 1); 5536 Ops.push_back(getValue(Record, OpNum, NextValueNo, FTy->getParamType(i), 5537 ArgTyID, CurBB)); 5538 ArgTyIDs.push_back(ArgTyID); 5539 if (!Ops.back()) 5540 return error("Invalid record"); 5541 } 5542 5543 if (!FTy->isVarArg()) { 5544 if (Record.size() != OpNum) 5545 return error("Invalid record"); 5546 } else { 5547 // Read type/value pairs for varargs params. 5548 while (OpNum != Record.size()) { 5549 Value *Op; 5550 unsigned OpTypeID; 5551 if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB)) 5552 return error("Invalid record"); 5553 Ops.push_back(Op); 5554 ArgTyIDs.push_back(OpTypeID); 5555 } 5556 } 5557 5558 // Upgrade the bundles if needed. 5559 if (!OperandBundles.empty()) 5560 UpgradeOperandBundles(OperandBundles); 5561 5562 I = InvokeInst::Create(FTy, Callee, NormalBB, UnwindBB, Ops, 5563 OperandBundles); 5564 ResTypeID = getContainedTypeID(FTyID); 5565 OperandBundles.clear(); 5566 InstructionList.push_back(I); 5567 cast<InvokeInst>(I)->setCallingConv( 5568 static_cast<CallingConv::ID>(CallingConv::MaxID & CCInfo)); 5569 cast<InvokeInst>(I)->setAttributes(PAL); 5570 if (Error Err = propagateAttributeTypes(cast<CallBase>(I), ArgTyIDs)) { 5571 I->deleteValue(); 5572 return Err; 5573 } 5574 5575 break; 5576 } 5577 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval] 5578 unsigned Idx = 0; 5579 Value *Val = nullptr; 5580 unsigned ValTypeID; 5581 if (getValueTypePair(Record, Idx, NextValueNo, Val, ValTypeID, CurBB)) 5582 return error("Invalid record"); 5583 I = ResumeInst::Create(Val); 5584 InstructionList.push_back(I); 5585 break; 5586 } 5587 case bitc::FUNC_CODE_INST_CALLBR: { 5588 // CALLBR: [attr, cc, norm, transfs, fty, fnid, args] 5589 unsigned OpNum = 0; 5590 AttributeList PAL = getAttributes(Record[OpNum++]); 5591 unsigned CCInfo = Record[OpNum++]; 5592 5593 BasicBlock *DefaultDest = getBasicBlock(Record[OpNum++]); 5594 unsigned NumIndirectDests = Record[OpNum++]; 5595 SmallVector<BasicBlock *, 16> IndirectDests; 5596 for (unsigned i = 0, e = NumIndirectDests; i != e; ++i) 5597 IndirectDests.push_back(getBasicBlock(Record[OpNum++])); 5598 5599 unsigned FTyID = InvalidTypeID; 5600 FunctionType *FTy = nullptr; 5601 if ((CCInfo >> bitc::CALL_EXPLICIT_TYPE) & 1) { 5602 FTyID = Record[OpNum++]; 5603 FTy = dyn_cast_or_null<FunctionType>(getTypeByID(FTyID)); 5604 if (!FTy) 5605 return error("Explicit call type is not a function type"); 5606 } 5607 5608 Value *Callee; 5609 unsigned CalleeTypeID; 5610 if (getValueTypePair(Record, OpNum, NextValueNo, Callee, CalleeTypeID, 5611 CurBB)) 5612 return error("Invalid record"); 5613 5614 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType()); 5615 if (!OpTy) 5616 return error("Callee is not a pointer type"); 5617 if (!FTy) { 5618 FTyID = getContainedTypeID(CalleeTypeID); 5619 FTy = dyn_cast_or_null<FunctionType>(getTypeByID(FTyID)); 5620 if (!FTy) 5621 return error("Callee is not of pointer to function type"); 5622 } 5623 if (Record.size() < FTy->getNumParams() + OpNum) 5624 return error("Insufficient operands to call"); 5625 5626 SmallVector<Value*, 16> Args; 5627 SmallVector<unsigned, 16> ArgTyIDs; 5628 // Read the fixed params. 5629 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) { 5630 Value *Arg; 5631 unsigned ArgTyID = getContainedTypeID(FTyID, i + 1); 5632 if (FTy->getParamType(i)->isLabelTy()) 5633 Arg = getBasicBlock(Record[OpNum]); 5634 else 5635 Arg = getValue(Record, OpNum, NextValueNo, FTy->getParamType(i), 5636 ArgTyID, CurBB); 5637 if (!Arg) 5638 return error("Invalid record"); 5639 Args.push_back(Arg); 5640 ArgTyIDs.push_back(ArgTyID); 5641 } 5642 5643 // Read type/value pairs for varargs params. 5644 if (!FTy->isVarArg()) { 5645 if (OpNum != Record.size()) 5646 return error("Invalid record"); 5647 } else { 5648 while (OpNum != Record.size()) { 5649 Value *Op; 5650 unsigned OpTypeID; 5651 if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB)) 5652 return error("Invalid record"); 5653 Args.push_back(Op); 5654 ArgTyIDs.push_back(OpTypeID); 5655 } 5656 } 5657 5658 // Upgrade the bundles if needed. 5659 if (!OperandBundles.empty()) 5660 UpgradeOperandBundles(OperandBundles); 5661 5662 if (auto *IA = dyn_cast<InlineAsm>(Callee)) { 5663 InlineAsm::ConstraintInfoVector ConstraintInfo = IA->ParseConstraints(); 5664 auto IsLabelConstraint = [](const InlineAsm::ConstraintInfo &CI) { 5665 return CI.Type == InlineAsm::isLabel; 5666 }; 5667 if (none_of(ConstraintInfo, IsLabelConstraint)) { 5668 // Upgrade explicit blockaddress arguments to label constraints. 5669 // Verify that the last arguments are blockaddress arguments that 5670 // match the indirect destinations. Clang always generates callbr 5671 // in this form. We could support reordering with more effort. 5672 unsigned FirstBlockArg = Args.size() - IndirectDests.size(); 5673 for (unsigned ArgNo = FirstBlockArg; ArgNo < Args.size(); ++ArgNo) { 5674 unsigned LabelNo = ArgNo - FirstBlockArg; 5675 auto *BA = dyn_cast<BlockAddress>(Args[ArgNo]); 5676 if (!BA || BA->getFunction() != F || 5677 LabelNo > IndirectDests.size() || 5678 BA->getBasicBlock() != IndirectDests[LabelNo]) 5679 return error("callbr argument does not match indirect dest"); 5680 } 5681 5682 // Remove blockaddress arguments. 5683 Args.erase(Args.begin() + FirstBlockArg, Args.end()); 5684 ArgTyIDs.erase(ArgTyIDs.begin() + FirstBlockArg, ArgTyIDs.end()); 5685 5686 // Recreate the function type with less arguments. 5687 SmallVector<Type *> ArgTys; 5688 for (Value *Arg : Args) 5689 ArgTys.push_back(Arg->getType()); 5690 FTy = 5691 FunctionType::get(FTy->getReturnType(), ArgTys, FTy->isVarArg()); 5692 5693 // Update constraint string to use label constraints. 5694 std::string Constraints = IA->getConstraintString(); 5695 unsigned ArgNo = 0; 5696 size_t Pos = 0; 5697 for (const auto &CI : ConstraintInfo) { 5698 if (CI.hasArg()) { 5699 if (ArgNo >= FirstBlockArg) 5700 Constraints.insert(Pos, "!"); 5701 ++ArgNo; 5702 } 5703 5704 // Go to next constraint in string. 5705 Pos = Constraints.find(',', Pos); 5706 if (Pos == std::string::npos) 5707 break; 5708 ++Pos; 5709 } 5710 5711 Callee = InlineAsm::get(FTy, IA->getAsmString(), Constraints, 5712 IA->hasSideEffects(), IA->isAlignStack(), 5713 IA->getDialect(), IA->canThrow()); 5714 } 5715 } 5716 5717 I = CallBrInst::Create(FTy, Callee, DefaultDest, IndirectDests, Args, 5718 OperandBundles); 5719 ResTypeID = getContainedTypeID(FTyID); 5720 OperandBundles.clear(); 5721 InstructionList.push_back(I); 5722 cast<CallBrInst>(I)->setCallingConv( 5723 static_cast<CallingConv::ID>((0x7ff & CCInfo) >> bitc::CALL_CCONV)); 5724 cast<CallBrInst>(I)->setAttributes(PAL); 5725 if (Error Err = propagateAttributeTypes(cast<CallBase>(I), ArgTyIDs)) { 5726 I->deleteValue(); 5727 return Err; 5728 } 5729 break; 5730 } 5731 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE 5732 I = new UnreachableInst(Context); 5733 InstructionList.push_back(I); 5734 break; 5735 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...] 5736 if (Record.empty()) 5737 return error("Invalid phi record"); 5738 // The first record specifies the type. 5739 unsigned TyID = Record[0]; 5740 Type *Ty = getTypeByID(TyID); 5741 if (!Ty) 5742 return error("Invalid phi record"); 5743 5744 // Phi arguments are pairs of records of [value, basic block]. 5745 // There is an optional final record for fast-math-flags if this phi has a 5746 // floating-point type. 5747 size_t NumArgs = (Record.size() - 1) / 2; 5748 PHINode *PN = PHINode::Create(Ty, NumArgs); 5749 if ((Record.size() - 1) % 2 == 1 && !isa<FPMathOperator>(PN)) { 5750 PN->deleteValue(); 5751 return error("Invalid phi record"); 5752 } 5753 InstructionList.push_back(PN); 5754 5755 SmallDenseMap<BasicBlock *, Value *> Args; 5756 for (unsigned i = 0; i != NumArgs; i++) { 5757 BasicBlock *BB = getBasicBlock(Record[i * 2 + 2]); 5758 if (!BB) { 5759 PN->deleteValue(); 5760 return error("Invalid phi BB"); 5761 } 5762 5763 // Phi nodes may contain the same predecessor multiple times, in which 5764 // case the incoming value must be identical. Directly reuse the already 5765 // seen value here, to avoid expanding a constant expression multiple 5766 // times. 5767 auto It = Args.find(BB); 5768 if (It != Args.end()) { 5769 PN->addIncoming(It->second, BB); 5770 continue; 5771 } 5772 5773 // If there already is a block for this edge (from a different phi), 5774 // use it. 5775 BasicBlock *EdgeBB = ConstExprEdgeBBs.lookup({BB, CurBB}); 5776 if (!EdgeBB) { 5777 // Otherwise, use a temporary block (that we will discard if it 5778 // turns out to be unnecessary). 5779 if (!PhiConstExprBB) 5780 PhiConstExprBB = BasicBlock::Create(Context, "phi.constexpr", F); 5781 EdgeBB = PhiConstExprBB; 5782 } 5783 5784 // With the new function encoding, it is possible that operands have 5785 // negative IDs (for forward references). Use a signed VBR 5786 // representation to keep the encoding small. 5787 Value *V; 5788 if (UseRelativeIDs) 5789 V = getValueSigned(Record, i * 2 + 1, NextValueNo, Ty, TyID, EdgeBB); 5790 else 5791 V = getValue(Record, i * 2 + 1, NextValueNo, Ty, TyID, EdgeBB); 5792 if (!V) { 5793 PN->deleteValue(); 5794 PhiConstExprBB->eraseFromParent(); 5795 return error("Invalid phi record"); 5796 } 5797 5798 if (EdgeBB == PhiConstExprBB && !EdgeBB->empty()) { 5799 ConstExprEdgeBBs.insert({{BB, CurBB}, EdgeBB}); 5800 PhiConstExprBB = nullptr; 5801 } 5802 PN->addIncoming(V, BB); 5803 Args.insert({BB, V}); 5804 } 5805 I = PN; 5806 ResTypeID = TyID; 5807 5808 // If there are an even number of records, the final record must be FMF. 5809 if (Record.size() % 2 == 0) { 5810 assert(isa<FPMathOperator>(I) && "Unexpected phi type"); 5811 FastMathFlags FMF = getDecodedFastMathFlags(Record[Record.size() - 1]); 5812 if (FMF.any()) 5813 I->setFastMathFlags(FMF); 5814 } 5815 5816 break; 5817 } 5818 5819 case bitc::FUNC_CODE_INST_LANDINGPAD: 5820 case bitc::FUNC_CODE_INST_LANDINGPAD_OLD: { 5821 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?] 5822 unsigned Idx = 0; 5823 if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD) { 5824 if (Record.size() < 3) 5825 return error("Invalid record"); 5826 } else { 5827 assert(BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD); 5828 if (Record.size() < 4) 5829 return error("Invalid record"); 5830 } 5831 ResTypeID = Record[Idx++]; 5832 Type *Ty = getTypeByID(ResTypeID); 5833 if (!Ty) 5834 return error("Invalid record"); 5835 if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD) { 5836 Value *PersFn = nullptr; 5837 unsigned PersFnTypeID; 5838 if (getValueTypePair(Record, Idx, NextValueNo, PersFn, PersFnTypeID, 5839 nullptr)) 5840 return error("Invalid record"); 5841 5842 if (!F->hasPersonalityFn()) 5843 F->setPersonalityFn(cast<Constant>(PersFn)); 5844 else if (F->getPersonalityFn() != cast<Constant>(PersFn)) 5845 return error("Personality function mismatch"); 5846 } 5847 5848 bool IsCleanup = !!Record[Idx++]; 5849 unsigned NumClauses = Record[Idx++]; 5850 LandingPadInst *LP = LandingPadInst::Create(Ty, NumClauses); 5851 LP->setCleanup(IsCleanup); 5852 for (unsigned J = 0; J != NumClauses; ++J) { 5853 LandingPadInst::ClauseType CT = 5854 LandingPadInst::ClauseType(Record[Idx++]); (void)CT; 5855 Value *Val; 5856 unsigned ValTypeID; 5857 5858 if (getValueTypePair(Record, Idx, NextValueNo, Val, ValTypeID, 5859 nullptr)) { 5860 delete LP; 5861 return error("Invalid record"); 5862 } 5863 5864 assert((CT != LandingPadInst::Catch || 5865 !isa<ArrayType>(Val->getType())) && 5866 "Catch clause has a invalid type!"); 5867 assert((CT != LandingPadInst::Filter || 5868 isa<ArrayType>(Val->getType())) && 5869 "Filter clause has invalid type!"); 5870 LP->addClause(cast<Constant>(Val)); 5871 } 5872 5873 I = LP; 5874 InstructionList.push_back(I); 5875 break; 5876 } 5877 5878 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align] 5879 if (Record.size() != 4 && Record.size() != 5) 5880 return error("Invalid record"); 5881 using APV = AllocaPackedValues; 5882 const uint64_t Rec = Record[3]; 5883 const bool InAlloca = Bitfield::get<APV::UsedWithInAlloca>(Rec); 5884 const bool SwiftError = Bitfield::get<APV::SwiftError>(Rec); 5885 unsigned TyID = Record[0]; 5886 Type *Ty = getTypeByID(TyID); 5887 if (!Bitfield::get<APV::ExplicitType>(Rec)) { 5888 TyID = getContainedTypeID(TyID); 5889 Ty = getTypeByID(TyID); 5890 if (!Ty) 5891 return error("Missing element type for old-style alloca"); 5892 } 5893 unsigned OpTyID = Record[1]; 5894 Type *OpTy = getTypeByID(OpTyID); 5895 Value *Size = getFnValueByID(Record[2], OpTy, OpTyID, CurBB); 5896 MaybeAlign Align; 5897 uint64_t AlignExp = 5898 Bitfield::get<APV::AlignLower>(Rec) | 5899 (Bitfield::get<APV::AlignUpper>(Rec) << APV::AlignLower::Bits); 5900 if (Error Err = parseAlignmentValue(AlignExp, Align)) { 5901 return Err; 5902 } 5903 if (!Ty || !Size) 5904 return error("Invalid record"); 5905 5906 const DataLayout &DL = TheModule->getDataLayout(); 5907 unsigned AS = Record.size() == 5 ? Record[4] : DL.getAllocaAddrSpace(); 5908 5909 SmallPtrSet<Type *, 4> Visited; 5910 if (!Align && !Ty->isSized(&Visited)) 5911 return error("alloca of unsized type"); 5912 if (!Align) 5913 Align = DL.getPrefTypeAlign(Ty); 5914 5915 AllocaInst *AI = new AllocaInst(Ty, AS, Size, *Align); 5916 AI->setUsedWithInAlloca(InAlloca); 5917 AI->setSwiftError(SwiftError); 5918 I = AI; 5919 ResTypeID = getVirtualTypeID(AI->getType(), TyID); 5920 InstructionList.push_back(I); 5921 break; 5922 } 5923 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol] 5924 unsigned OpNum = 0; 5925 Value *Op; 5926 unsigned OpTypeID; 5927 if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB) || 5928 (OpNum + 2 != Record.size() && OpNum + 3 != Record.size())) 5929 return error("Invalid record"); 5930 5931 if (!isa<PointerType>(Op->getType())) 5932 return error("Load operand is not a pointer type"); 5933 5934 Type *Ty = nullptr; 5935 if (OpNum + 3 == Record.size()) { 5936 ResTypeID = Record[OpNum++]; 5937 Ty = getTypeByID(ResTypeID); 5938 } else { 5939 ResTypeID = getContainedTypeID(OpTypeID); 5940 Ty = getTypeByID(ResTypeID); 5941 if (!Ty) 5942 return error("Missing element type for old-style load"); 5943 } 5944 5945 if (Error Err = typeCheckLoadStoreInst(Ty, Op->getType())) 5946 return Err; 5947 5948 MaybeAlign Align; 5949 if (Error Err = parseAlignmentValue(Record[OpNum], Align)) 5950 return Err; 5951 SmallPtrSet<Type *, 4> Visited; 5952 if (!Align && !Ty->isSized(&Visited)) 5953 return error("load of unsized type"); 5954 if (!Align) 5955 Align = TheModule->getDataLayout().getABITypeAlign(Ty); 5956 I = new LoadInst(Ty, Op, "", Record[OpNum + 1], *Align); 5957 InstructionList.push_back(I); 5958 break; 5959 } 5960 case bitc::FUNC_CODE_INST_LOADATOMIC: { 5961 // LOADATOMIC: [opty, op, align, vol, ordering, ssid] 5962 unsigned OpNum = 0; 5963 Value *Op; 5964 unsigned OpTypeID; 5965 if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB) || 5966 (OpNum + 4 != Record.size() && OpNum + 5 != Record.size())) 5967 return error("Invalid record"); 5968 5969 if (!isa<PointerType>(Op->getType())) 5970 return error("Load operand is not a pointer type"); 5971 5972 Type *Ty = nullptr; 5973 if (OpNum + 5 == Record.size()) { 5974 ResTypeID = Record[OpNum++]; 5975 Ty = getTypeByID(ResTypeID); 5976 } else { 5977 ResTypeID = getContainedTypeID(OpTypeID); 5978 Ty = getTypeByID(ResTypeID); 5979 if (!Ty) 5980 return error("Missing element type for old style atomic load"); 5981 } 5982 5983 if (Error Err = typeCheckLoadStoreInst(Ty, Op->getType())) 5984 return Err; 5985 5986 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]); 5987 if (Ordering == AtomicOrdering::NotAtomic || 5988 Ordering == AtomicOrdering::Release || 5989 Ordering == AtomicOrdering::AcquireRelease) 5990 return error("Invalid record"); 5991 if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0) 5992 return error("Invalid record"); 5993 SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]); 5994 5995 MaybeAlign Align; 5996 if (Error Err = parseAlignmentValue(Record[OpNum], Align)) 5997 return Err; 5998 if (!Align) 5999 return error("Alignment missing from atomic load"); 6000 I = new LoadInst(Ty, Op, "", Record[OpNum + 1], *Align, Ordering, SSID); 6001 InstructionList.push_back(I); 6002 break; 6003 } 6004 case bitc::FUNC_CODE_INST_STORE: 6005 case bitc::FUNC_CODE_INST_STORE_OLD: { // STORE2:[ptrty, ptr, val, align, vol] 6006 unsigned OpNum = 0; 6007 Value *Val, *Ptr; 6008 unsigned PtrTypeID, ValTypeID; 6009 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB)) 6010 return error("Invalid record"); 6011 6012 if (BitCode == bitc::FUNC_CODE_INST_STORE) { 6013 if (getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID, CurBB)) 6014 return error("Invalid record"); 6015 } else { 6016 ValTypeID = getContainedTypeID(PtrTypeID); 6017 if (popValue(Record, OpNum, NextValueNo, getTypeByID(ValTypeID), 6018 ValTypeID, Val, CurBB)) 6019 return error("Invalid record"); 6020 } 6021 6022 if (OpNum + 2 != Record.size()) 6023 return error("Invalid record"); 6024 6025 if (Error Err = typeCheckLoadStoreInst(Val->getType(), Ptr->getType())) 6026 return Err; 6027 MaybeAlign Align; 6028 if (Error Err = parseAlignmentValue(Record[OpNum], Align)) 6029 return Err; 6030 SmallPtrSet<Type *, 4> Visited; 6031 if (!Align && !Val->getType()->isSized(&Visited)) 6032 return error("store of unsized type"); 6033 if (!Align) 6034 Align = TheModule->getDataLayout().getABITypeAlign(Val->getType()); 6035 I = new StoreInst(Val, Ptr, Record[OpNum + 1], *Align); 6036 InstructionList.push_back(I); 6037 break; 6038 } 6039 case bitc::FUNC_CODE_INST_STOREATOMIC: 6040 case bitc::FUNC_CODE_INST_STOREATOMIC_OLD: { 6041 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, ssid] 6042 unsigned OpNum = 0; 6043 Value *Val, *Ptr; 6044 unsigned PtrTypeID, ValTypeID; 6045 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB) || 6046 !isa<PointerType>(Ptr->getType())) 6047 return error("Invalid record"); 6048 if (BitCode == bitc::FUNC_CODE_INST_STOREATOMIC) { 6049 if (getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID, CurBB)) 6050 return error("Invalid record"); 6051 } else { 6052 ValTypeID = getContainedTypeID(PtrTypeID); 6053 if (popValue(Record, OpNum, NextValueNo, getTypeByID(ValTypeID), 6054 ValTypeID, Val, CurBB)) 6055 return error("Invalid record"); 6056 } 6057 6058 if (OpNum + 4 != Record.size()) 6059 return error("Invalid record"); 6060 6061 if (Error Err = typeCheckLoadStoreInst(Val->getType(), Ptr->getType())) 6062 return Err; 6063 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]); 6064 if (Ordering == AtomicOrdering::NotAtomic || 6065 Ordering == AtomicOrdering::Acquire || 6066 Ordering == AtomicOrdering::AcquireRelease) 6067 return error("Invalid record"); 6068 SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]); 6069 if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0) 6070 return error("Invalid record"); 6071 6072 MaybeAlign Align; 6073 if (Error Err = parseAlignmentValue(Record[OpNum], Align)) 6074 return Err; 6075 if (!Align) 6076 return error("Alignment missing from atomic store"); 6077 I = new StoreInst(Val, Ptr, Record[OpNum + 1], *Align, Ordering, SSID); 6078 InstructionList.push_back(I); 6079 break; 6080 } 6081 case bitc::FUNC_CODE_INST_CMPXCHG_OLD: { 6082 // CMPXCHG_OLD: [ptrty, ptr, cmp, val, vol, ordering, synchscope, 6083 // failure_ordering?, weak?] 6084 const size_t NumRecords = Record.size(); 6085 unsigned OpNum = 0; 6086 Value *Ptr = nullptr; 6087 unsigned PtrTypeID; 6088 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB)) 6089 return error("Invalid record"); 6090 6091 if (!isa<PointerType>(Ptr->getType())) 6092 return error("Cmpxchg operand is not a pointer type"); 6093 6094 Value *Cmp = nullptr; 6095 unsigned CmpTypeID = getContainedTypeID(PtrTypeID); 6096 if (popValue(Record, OpNum, NextValueNo, getTypeByID(CmpTypeID), 6097 CmpTypeID, Cmp, CurBB)) 6098 return error("Invalid record"); 6099 6100 Value *New = nullptr; 6101 if (popValue(Record, OpNum, NextValueNo, Cmp->getType(), CmpTypeID, 6102 New, CurBB) || 6103 NumRecords < OpNum + 3 || NumRecords > OpNum + 5) 6104 return error("Invalid record"); 6105 6106 const AtomicOrdering SuccessOrdering = 6107 getDecodedOrdering(Record[OpNum + 1]); 6108 if (SuccessOrdering == AtomicOrdering::NotAtomic || 6109 SuccessOrdering == AtomicOrdering::Unordered) 6110 return error("Invalid record"); 6111 6112 const SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 2]); 6113 6114 if (Error Err = typeCheckLoadStoreInst(Cmp->getType(), Ptr->getType())) 6115 return Err; 6116 6117 const AtomicOrdering FailureOrdering = 6118 NumRecords < 7 6119 ? AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering) 6120 : getDecodedOrdering(Record[OpNum + 3]); 6121 6122 if (FailureOrdering == AtomicOrdering::NotAtomic || 6123 FailureOrdering == AtomicOrdering::Unordered) 6124 return error("Invalid record"); 6125 6126 const Align Alignment( 6127 TheModule->getDataLayout().getTypeStoreSize(Cmp->getType())); 6128 6129 I = new AtomicCmpXchgInst(Ptr, Cmp, New, Alignment, SuccessOrdering, 6130 FailureOrdering, SSID); 6131 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]); 6132 6133 if (NumRecords < 8) { 6134 // Before weak cmpxchgs existed, the instruction simply returned the 6135 // value loaded from memory, so bitcode files from that era will be 6136 // expecting the first component of a modern cmpxchg. 6137 I->insertInto(CurBB, CurBB->end()); 6138 I = ExtractValueInst::Create(I, 0); 6139 ResTypeID = CmpTypeID; 6140 } else { 6141 cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum + 4]); 6142 unsigned I1TypeID = getVirtualTypeID(Type::getInt1Ty(Context)); 6143 ResTypeID = getVirtualTypeID(I->getType(), {CmpTypeID, I1TypeID}); 6144 } 6145 6146 InstructionList.push_back(I); 6147 break; 6148 } 6149 case bitc::FUNC_CODE_INST_CMPXCHG: { 6150 // CMPXCHG: [ptrty, ptr, cmp, val, vol, success_ordering, synchscope, 6151 // failure_ordering, weak, align?] 6152 const size_t NumRecords = Record.size(); 6153 unsigned OpNum = 0; 6154 Value *Ptr = nullptr; 6155 unsigned PtrTypeID; 6156 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB)) 6157 return error("Invalid record"); 6158 6159 if (!isa<PointerType>(Ptr->getType())) 6160 return error("Cmpxchg operand is not a pointer type"); 6161 6162 Value *Cmp = nullptr; 6163 unsigned CmpTypeID; 6164 if (getValueTypePair(Record, OpNum, NextValueNo, Cmp, CmpTypeID, CurBB)) 6165 return error("Invalid record"); 6166 6167 Value *Val = nullptr; 6168 if (popValue(Record, OpNum, NextValueNo, Cmp->getType(), CmpTypeID, Val, 6169 CurBB)) 6170 return error("Invalid record"); 6171 6172 if (NumRecords < OpNum + 3 || NumRecords > OpNum + 6) 6173 return error("Invalid record"); 6174 6175 const bool IsVol = Record[OpNum]; 6176 6177 const AtomicOrdering SuccessOrdering = 6178 getDecodedOrdering(Record[OpNum + 1]); 6179 if (!AtomicCmpXchgInst::isValidSuccessOrdering(SuccessOrdering)) 6180 return error("Invalid cmpxchg success ordering"); 6181 6182 const SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 2]); 6183 6184 if (Error Err = typeCheckLoadStoreInst(Cmp->getType(), Ptr->getType())) 6185 return Err; 6186 6187 const AtomicOrdering FailureOrdering = 6188 getDecodedOrdering(Record[OpNum + 3]); 6189 if (!AtomicCmpXchgInst::isValidFailureOrdering(FailureOrdering)) 6190 return error("Invalid cmpxchg failure ordering"); 6191 6192 const bool IsWeak = Record[OpNum + 4]; 6193 6194 MaybeAlign Alignment; 6195 6196 if (NumRecords == (OpNum + 6)) { 6197 if (Error Err = parseAlignmentValue(Record[OpNum + 5], Alignment)) 6198 return Err; 6199 } 6200 if (!Alignment) 6201 Alignment = 6202 Align(TheModule->getDataLayout().getTypeStoreSize(Cmp->getType())); 6203 6204 I = new AtomicCmpXchgInst(Ptr, Cmp, Val, *Alignment, SuccessOrdering, 6205 FailureOrdering, SSID); 6206 cast<AtomicCmpXchgInst>(I)->setVolatile(IsVol); 6207 cast<AtomicCmpXchgInst>(I)->setWeak(IsWeak); 6208 6209 unsigned I1TypeID = getVirtualTypeID(Type::getInt1Ty(Context)); 6210 ResTypeID = getVirtualTypeID(I->getType(), {CmpTypeID, I1TypeID}); 6211 6212 InstructionList.push_back(I); 6213 break; 6214 } 6215 case bitc::FUNC_CODE_INST_ATOMICRMW_OLD: 6216 case bitc::FUNC_CODE_INST_ATOMICRMW: { 6217 // ATOMICRMW_OLD: [ptrty, ptr, val, op, vol, ordering, ssid, align?] 6218 // ATOMICRMW: [ptrty, ptr, valty, val, op, vol, ordering, ssid, align?] 6219 const size_t NumRecords = Record.size(); 6220 unsigned OpNum = 0; 6221 6222 Value *Ptr = nullptr; 6223 unsigned PtrTypeID; 6224 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB)) 6225 return error("Invalid record"); 6226 6227 if (!isa<PointerType>(Ptr->getType())) 6228 return error("Invalid record"); 6229 6230 Value *Val = nullptr; 6231 unsigned ValTypeID = InvalidTypeID; 6232 if (BitCode == bitc::FUNC_CODE_INST_ATOMICRMW_OLD) { 6233 ValTypeID = getContainedTypeID(PtrTypeID); 6234 if (popValue(Record, OpNum, NextValueNo, 6235 getTypeByID(ValTypeID), ValTypeID, Val, CurBB)) 6236 return error("Invalid record"); 6237 } else { 6238 if (getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID, CurBB)) 6239 return error("Invalid record"); 6240 } 6241 6242 if (!(NumRecords == (OpNum + 4) || NumRecords == (OpNum + 5))) 6243 return error("Invalid record"); 6244 6245 const AtomicRMWInst::BinOp Operation = 6246 getDecodedRMWOperation(Record[OpNum]); 6247 if (Operation < AtomicRMWInst::FIRST_BINOP || 6248 Operation > AtomicRMWInst::LAST_BINOP) 6249 return error("Invalid record"); 6250 6251 const bool IsVol = Record[OpNum + 1]; 6252 6253 const AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]); 6254 if (Ordering == AtomicOrdering::NotAtomic || 6255 Ordering == AtomicOrdering::Unordered) 6256 return error("Invalid record"); 6257 6258 const SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]); 6259 6260 MaybeAlign Alignment; 6261 6262 if (NumRecords == (OpNum + 5)) { 6263 if (Error Err = parseAlignmentValue(Record[OpNum + 4], Alignment)) 6264 return Err; 6265 } 6266 6267 if (!Alignment) 6268 Alignment = 6269 Align(TheModule->getDataLayout().getTypeStoreSize(Val->getType())); 6270 6271 I = new AtomicRMWInst(Operation, Ptr, Val, *Alignment, Ordering, SSID); 6272 ResTypeID = ValTypeID; 6273 cast<AtomicRMWInst>(I)->setVolatile(IsVol); 6274 6275 InstructionList.push_back(I); 6276 break; 6277 } 6278 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, ssid] 6279 if (2 != Record.size()) 6280 return error("Invalid record"); 6281 AtomicOrdering Ordering = getDecodedOrdering(Record[0]); 6282 if (Ordering == AtomicOrdering::NotAtomic || 6283 Ordering == AtomicOrdering::Unordered || 6284 Ordering == AtomicOrdering::Monotonic) 6285 return error("Invalid record"); 6286 SyncScope::ID SSID = getDecodedSyncScopeID(Record[1]); 6287 I = new FenceInst(Context, Ordering, SSID); 6288 InstructionList.push_back(I); 6289 break; 6290 } 6291 case bitc::FUNC_CODE_INST_CALL: { 6292 // CALL: [paramattrs, cc, fmf, fnty, fnid, arg0, arg1...] 6293 if (Record.size() < 3) 6294 return error("Invalid record"); 6295 6296 unsigned OpNum = 0; 6297 AttributeList PAL = getAttributes(Record[OpNum++]); 6298 unsigned CCInfo = Record[OpNum++]; 6299 6300 FastMathFlags FMF; 6301 if ((CCInfo >> bitc::CALL_FMF) & 1) { 6302 FMF = getDecodedFastMathFlags(Record[OpNum++]); 6303 if (!FMF.any()) 6304 return error("Fast math flags indicator set for call with no FMF"); 6305 } 6306 6307 unsigned FTyID = InvalidTypeID; 6308 FunctionType *FTy = nullptr; 6309 if ((CCInfo >> bitc::CALL_EXPLICIT_TYPE) & 1) { 6310 FTyID = Record[OpNum++]; 6311 FTy = dyn_cast_or_null<FunctionType>(getTypeByID(FTyID)); 6312 if (!FTy) 6313 return error("Explicit call type is not a function type"); 6314 } 6315 6316 Value *Callee; 6317 unsigned CalleeTypeID; 6318 if (getValueTypePair(Record, OpNum, NextValueNo, Callee, CalleeTypeID, 6319 CurBB)) 6320 return error("Invalid record"); 6321 6322 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType()); 6323 if (!OpTy) 6324 return error("Callee is not a pointer type"); 6325 if (!FTy) { 6326 FTyID = getContainedTypeID(CalleeTypeID); 6327 FTy = dyn_cast_or_null<FunctionType>(getTypeByID(FTyID)); 6328 if (!FTy) 6329 return error("Callee is not of pointer to function type"); 6330 } 6331 if (Record.size() < FTy->getNumParams() + OpNum) 6332 return error("Insufficient operands to call"); 6333 6334 SmallVector<Value*, 16> Args; 6335 SmallVector<unsigned, 16> ArgTyIDs; 6336 // Read the fixed params. 6337 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) { 6338 unsigned ArgTyID = getContainedTypeID(FTyID, i + 1); 6339 if (FTy->getParamType(i)->isLabelTy()) 6340 Args.push_back(getBasicBlock(Record[OpNum])); 6341 else 6342 Args.push_back(getValue(Record, OpNum, NextValueNo, 6343 FTy->getParamType(i), ArgTyID, CurBB)); 6344 ArgTyIDs.push_back(ArgTyID); 6345 if (!Args.back()) 6346 return error("Invalid record"); 6347 } 6348 6349 // Read type/value pairs for varargs params. 6350 if (!FTy->isVarArg()) { 6351 if (OpNum != Record.size()) 6352 return error("Invalid record"); 6353 } else { 6354 while (OpNum != Record.size()) { 6355 Value *Op; 6356 unsigned OpTypeID; 6357 if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB)) 6358 return error("Invalid record"); 6359 Args.push_back(Op); 6360 ArgTyIDs.push_back(OpTypeID); 6361 } 6362 } 6363 6364 // Upgrade the bundles if needed. 6365 if (!OperandBundles.empty()) 6366 UpgradeOperandBundles(OperandBundles); 6367 6368 I = CallInst::Create(FTy, Callee, Args, OperandBundles); 6369 ResTypeID = getContainedTypeID(FTyID); 6370 OperandBundles.clear(); 6371 InstructionList.push_back(I); 6372 cast<CallInst>(I)->setCallingConv( 6373 static_cast<CallingConv::ID>((0x7ff & CCInfo) >> bitc::CALL_CCONV)); 6374 CallInst::TailCallKind TCK = CallInst::TCK_None; 6375 if (CCInfo & (1 << bitc::CALL_TAIL)) 6376 TCK = CallInst::TCK_Tail; 6377 if (CCInfo & (1 << bitc::CALL_MUSTTAIL)) 6378 TCK = CallInst::TCK_MustTail; 6379 if (CCInfo & (1 << bitc::CALL_NOTAIL)) 6380 TCK = CallInst::TCK_NoTail; 6381 cast<CallInst>(I)->setTailCallKind(TCK); 6382 cast<CallInst>(I)->setAttributes(PAL); 6383 if (Error Err = propagateAttributeTypes(cast<CallBase>(I), ArgTyIDs)) { 6384 I->deleteValue(); 6385 return Err; 6386 } 6387 if (FMF.any()) { 6388 if (!isa<FPMathOperator>(I)) 6389 return error("Fast-math-flags specified for call without " 6390 "floating-point scalar or vector return type"); 6391 I->setFastMathFlags(FMF); 6392 } 6393 break; 6394 } 6395 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty] 6396 if (Record.size() < 3) 6397 return error("Invalid record"); 6398 unsigned OpTyID = Record[0]; 6399 Type *OpTy = getTypeByID(OpTyID); 6400 Value *Op = getValue(Record, 1, NextValueNo, OpTy, OpTyID, CurBB); 6401 ResTypeID = Record[2]; 6402 Type *ResTy = getTypeByID(ResTypeID); 6403 if (!OpTy || !Op || !ResTy) 6404 return error("Invalid record"); 6405 I = new VAArgInst(Op, ResTy); 6406 InstructionList.push_back(I); 6407 break; 6408 } 6409 6410 case bitc::FUNC_CODE_OPERAND_BUNDLE: { 6411 // A call or an invoke can be optionally prefixed with some variable 6412 // number of operand bundle blocks. These blocks are read into 6413 // OperandBundles and consumed at the next call or invoke instruction. 6414 6415 if (Record.empty() || Record[0] >= BundleTags.size()) 6416 return error("Invalid record"); 6417 6418 std::vector<Value *> Inputs; 6419 6420 unsigned OpNum = 1; 6421 while (OpNum != Record.size()) { 6422 Value *Op; 6423 unsigned OpTypeID; 6424 if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB)) 6425 return error("Invalid record"); 6426 Inputs.push_back(Op); 6427 } 6428 6429 OperandBundles.emplace_back(BundleTags[Record[0]], std::move(Inputs)); 6430 continue; 6431 } 6432 6433 case bitc::FUNC_CODE_INST_FREEZE: { // FREEZE: [opty,opval] 6434 unsigned OpNum = 0; 6435 Value *Op = nullptr; 6436 unsigned OpTypeID; 6437 if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB)) 6438 return error("Invalid record"); 6439 if (OpNum != Record.size()) 6440 return error("Invalid record"); 6441 6442 I = new FreezeInst(Op); 6443 ResTypeID = OpTypeID; 6444 InstructionList.push_back(I); 6445 break; 6446 } 6447 } 6448 6449 // Add instruction to end of current BB. If there is no current BB, reject 6450 // this file. 6451 if (!CurBB) { 6452 I->deleteValue(); 6453 return error("Invalid instruction with no BB"); 6454 } 6455 if (!OperandBundles.empty()) { 6456 I->deleteValue(); 6457 return error("Operand bundles found with no consumer"); 6458 } 6459 I->insertInto(CurBB, CurBB->end()); 6460 6461 // If this was a terminator instruction, move to the next block. 6462 if (I->isTerminator()) { 6463 ++CurBBNo; 6464 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr; 6465 } 6466 6467 // Non-void values get registered in the value table for future use. 6468 if (!I->getType()->isVoidTy()) { 6469 assert(I->getType() == getTypeByID(ResTypeID) && 6470 "Incorrect result type ID"); 6471 if (Error Err = ValueList.assignValue(NextValueNo++, I, ResTypeID)) 6472 return Err; 6473 } 6474 } 6475 6476 OutOfRecordLoop: 6477 6478 if (!OperandBundles.empty()) 6479 return error("Operand bundles found with no consumer"); 6480 6481 // Check the function list for unresolved values. 6482 if (Argument *A = dyn_cast<Argument>(ValueList.back())) { 6483 if (!A->getParent()) { 6484 // We found at least one unresolved value. Nuke them all to avoid leaks. 6485 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){ 6486 if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) { 6487 A->replaceAllUsesWith(PoisonValue::get(A->getType())); 6488 delete A; 6489 } 6490 } 6491 return error("Never resolved value found in function"); 6492 } 6493 } 6494 6495 // Unexpected unresolved metadata about to be dropped. 6496 if (MDLoader->hasFwdRefs()) 6497 return error("Invalid function metadata: outgoing forward refs"); 6498 6499 if (PhiConstExprBB) 6500 PhiConstExprBB->eraseFromParent(); 6501 6502 for (const auto &Pair : ConstExprEdgeBBs) { 6503 BasicBlock *From = Pair.first.first; 6504 BasicBlock *To = Pair.first.second; 6505 BasicBlock *EdgeBB = Pair.second; 6506 BranchInst::Create(To, EdgeBB); 6507 From->getTerminator()->replaceSuccessorWith(To, EdgeBB); 6508 To->replacePhiUsesWith(From, EdgeBB); 6509 EdgeBB->moveBefore(To); 6510 } 6511 6512 // Trim the value list down to the size it was before we parsed this function. 6513 ValueList.shrinkTo(ModuleValueListSize); 6514 MDLoader->shrinkTo(ModuleMDLoaderSize); 6515 std::vector<BasicBlock*>().swap(FunctionBBs); 6516 return Error::success(); 6517 } 6518 6519 /// Find the function body in the bitcode stream 6520 Error BitcodeReader::findFunctionInStream( 6521 Function *F, 6522 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) { 6523 while (DeferredFunctionInfoIterator->second == 0) { 6524 // This is the fallback handling for the old format bitcode that 6525 // didn't contain the function index in the VST, or when we have 6526 // an anonymous function which would not have a VST entry. 6527 // Assert that we have one of those two cases. 6528 assert(VSTOffset == 0 || !F->hasName()); 6529 // Parse the next body in the stream and set its position in the 6530 // DeferredFunctionInfo map. 6531 if (Error Err = rememberAndSkipFunctionBodies()) 6532 return Err; 6533 } 6534 return Error::success(); 6535 } 6536 6537 SyncScope::ID BitcodeReader::getDecodedSyncScopeID(unsigned Val) { 6538 if (Val == SyncScope::SingleThread || Val == SyncScope::System) 6539 return SyncScope::ID(Val); 6540 if (Val >= SSIDs.size()) 6541 return SyncScope::System; // Map unknown synchronization scopes to system. 6542 return SSIDs[Val]; 6543 } 6544 6545 //===----------------------------------------------------------------------===// 6546 // GVMaterializer implementation 6547 //===----------------------------------------------------------------------===// 6548 6549 Error BitcodeReader::materialize(GlobalValue *GV) { 6550 Function *F = dyn_cast<Function>(GV); 6551 // If it's not a function or is already material, ignore the request. 6552 if (!F || !F->isMaterializable()) 6553 return Error::success(); 6554 6555 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F); 6556 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!"); 6557 // If its position is recorded as 0, its body is somewhere in the stream 6558 // but we haven't seen it yet. 6559 if (DFII->second == 0) 6560 if (Error Err = findFunctionInStream(F, DFII)) 6561 return Err; 6562 6563 // Materialize metadata before parsing any function bodies. 6564 if (Error Err = materializeMetadata()) 6565 return Err; 6566 6567 // Move the bit stream to the saved position of the deferred function body. 6568 if (Error JumpFailed = Stream.JumpToBit(DFII->second)) 6569 return JumpFailed; 6570 if (Error Err = parseFunctionBody(F)) 6571 return Err; 6572 F->setIsMaterializable(false); 6573 6574 if (StripDebugInfo) 6575 stripDebugInfo(*F); 6576 6577 // Upgrade any old intrinsic calls in the function. 6578 for (auto &I : UpgradedIntrinsics) { 6579 for (User *U : llvm::make_early_inc_range(I.first->materialized_users())) 6580 if (CallInst *CI = dyn_cast<CallInst>(U)) 6581 UpgradeIntrinsicCall(CI, I.second); 6582 } 6583 6584 // Finish fn->subprogram upgrade for materialized functions. 6585 if (DISubprogram *SP = MDLoader->lookupSubprogramForFunction(F)) 6586 F->setSubprogram(SP); 6587 6588 // Check if the TBAA Metadata are valid, otherwise we will need to strip them. 6589 if (!MDLoader->isStrippingTBAA()) { 6590 for (auto &I : instructions(F)) { 6591 MDNode *TBAA = I.getMetadata(LLVMContext::MD_tbaa); 6592 if (!TBAA || TBAAVerifyHelper.visitTBAAMetadata(I, TBAA)) 6593 continue; 6594 MDLoader->setStripTBAA(true); 6595 stripTBAA(F->getParent()); 6596 } 6597 } 6598 6599 for (auto &I : instructions(F)) { 6600 // "Upgrade" older incorrect branch weights by dropping them. 6601 if (auto *MD = I.getMetadata(LLVMContext::MD_prof)) { 6602 if (MD->getOperand(0) != nullptr && isa<MDString>(MD->getOperand(0))) { 6603 MDString *MDS = cast<MDString>(MD->getOperand(0)); 6604 StringRef ProfName = MDS->getString(); 6605 // Check consistency of !prof branch_weights metadata. 6606 if (!ProfName.equals("branch_weights")) 6607 continue; 6608 unsigned ExpectedNumOperands = 0; 6609 if (BranchInst *BI = dyn_cast<BranchInst>(&I)) 6610 ExpectedNumOperands = BI->getNumSuccessors(); 6611 else if (SwitchInst *SI = dyn_cast<SwitchInst>(&I)) 6612 ExpectedNumOperands = SI->getNumSuccessors(); 6613 else if (isa<CallInst>(&I)) 6614 ExpectedNumOperands = 1; 6615 else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(&I)) 6616 ExpectedNumOperands = IBI->getNumDestinations(); 6617 else if (isa<SelectInst>(&I)) 6618 ExpectedNumOperands = 2; 6619 else 6620 continue; // ignore and continue. 6621 6622 // If branch weight doesn't match, just strip branch weight. 6623 if (MD->getNumOperands() != 1 + ExpectedNumOperands) 6624 I.setMetadata(LLVMContext::MD_prof, nullptr); 6625 } 6626 } 6627 6628 // Remove incompatible attributes on function calls. 6629 if (auto *CI = dyn_cast<CallBase>(&I)) { 6630 CI->removeRetAttrs(AttributeFuncs::typeIncompatible( 6631 CI->getFunctionType()->getReturnType())); 6632 6633 for (unsigned ArgNo = 0; ArgNo < CI->arg_size(); ++ArgNo) 6634 CI->removeParamAttrs(ArgNo, AttributeFuncs::typeIncompatible( 6635 CI->getArgOperand(ArgNo)->getType())); 6636 } 6637 } 6638 6639 // Look for functions that rely on old function attribute behavior. 6640 UpgradeFunctionAttributes(*F); 6641 6642 // Bring in any functions that this function forward-referenced via 6643 // blockaddresses. 6644 return materializeForwardReferencedFunctions(); 6645 } 6646 6647 Error BitcodeReader::materializeModule() { 6648 if (Error Err = materializeMetadata()) 6649 return Err; 6650 6651 // Promise to materialize all forward references. 6652 WillMaterializeAllForwardRefs = true; 6653 6654 // Iterate over the module, deserializing any functions that are still on 6655 // disk. 6656 for (Function &F : *TheModule) { 6657 if (Error Err = materialize(&F)) 6658 return Err; 6659 } 6660 // At this point, if there are any function bodies, parse the rest of 6661 // the bits in the module past the last function block we have recorded 6662 // through either lazy scanning or the VST. 6663 if (LastFunctionBlockBit || NextUnreadBit) 6664 if (Error Err = parseModule(LastFunctionBlockBit > NextUnreadBit 6665 ? LastFunctionBlockBit 6666 : NextUnreadBit)) 6667 return Err; 6668 6669 // Check that all block address forward references got resolved (as we 6670 // promised above). 6671 if (!BasicBlockFwdRefs.empty()) 6672 return error("Never resolved function from blockaddress"); 6673 6674 // Upgrade any intrinsic calls that slipped through (should not happen!) and 6675 // delete the old functions to clean up. We can't do this unless the entire 6676 // module is materialized because there could always be another function body 6677 // with calls to the old function. 6678 for (auto &I : UpgradedIntrinsics) { 6679 for (auto *U : I.first->users()) { 6680 if (CallInst *CI = dyn_cast<CallInst>(U)) 6681 UpgradeIntrinsicCall(CI, I.second); 6682 } 6683 if (!I.first->use_empty()) 6684 I.first->replaceAllUsesWith(I.second); 6685 I.first->eraseFromParent(); 6686 } 6687 UpgradedIntrinsics.clear(); 6688 6689 UpgradeDebugInfo(*TheModule); 6690 6691 UpgradeModuleFlags(*TheModule); 6692 6693 UpgradeARCRuntime(*TheModule); 6694 6695 return Error::success(); 6696 } 6697 6698 std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const { 6699 return IdentifiedStructTypes; 6700 } 6701 6702 ModuleSummaryIndexBitcodeReader::ModuleSummaryIndexBitcodeReader( 6703 BitstreamCursor Cursor, StringRef Strtab, ModuleSummaryIndex &TheIndex, 6704 StringRef ModulePath, std::function<bool(GlobalValue::GUID)> IsPrevailing) 6705 : BitcodeReaderBase(std::move(Cursor), Strtab), TheIndex(TheIndex), 6706 ModulePath(ModulePath), IsPrevailing(IsPrevailing) {} 6707 6708 void ModuleSummaryIndexBitcodeReader::addThisModule() { 6709 TheIndex.addModule(ModulePath); 6710 } 6711 6712 ModuleSummaryIndex::ModuleInfo * 6713 ModuleSummaryIndexBitcodeReader::getThisModule() { 6714 return TheIndex.getModule(ModulePath); 6715 } 6716 6717 template <bool AllowNullValueInfo> 6718 std::tuple<ValueInfo, GlobalValue::GUID, GlobalValue::GUID> 6719 ModuleSummaryIndexBitcodeReader::getValueInfoFromValueId(unsigned ValueId) { 6720 auto VGI = ValueIdToValueInfoMap[ValueId]; 6721 // We can have a null value info for memprof callsite info records in 6722 // distributed ThinLTO index files when the callee function summary is not 6723 // included in the index. The bitcode writer records 0 in that case, 6724 // and the caller of this helper will set AllowNullValueInfo to true. 6725 assert(AllowNullValueInfo || std::get<0>(VGI)); 6726 return VGI; 6727 } 6728 6729 void ModuleSummaryIndexBitcodeReader::setValueGUID( 6730 uint64_t ValueID, StringRef ValueName, GlobalValue::LinkageTypes Linkage, 6731 StringRef SourceFileName) { 6732 std::string GlobalId = 6733 GlobalValue::getGlobalIdentifier(ValueName, Linkage, SourceFileName); 6734 auto ValueGUID = GlobalValue::getGUID(GlobalId); 6735 auto OriginalNameID = ValueGUID; 6736 if (GlobalValue::isLocalLinkage(Linkage)) 6737 OriginalNameID = GlobalValue::getGUID(ValueName); 6738 if (PrintSummaryGUIDs) 6739 dbgs() << "GUID " << ValueGUID << "(" << OriginalNameID << ") is " 6740 << ValueName << "\n"; 6741 6742 // UseStrtab is false for legacy summary formats and value names are 6743 // created on stack. In that case we save the name in a string saver in 6744 // the index so that the value name can be recorded. 6745 ValueIdToValueInfoMap[ValueID] = std::make_tuple( 6746 TheIndex.getOrInsertValueInfo( 6747 ValueGUID, UseStrtab ? ValueName : TheIndex.saveString(ValueName)), 6748 OriginalNameID, ValueGUID); 6749 } 6750 6751 // Specialized value symbol table parser used when reading module index 6752 // blocks where we don't actually create global values. The parsed information 6753 // is saved in the bitcode reader for use when later parsing summaries. 6754 Error ModuleSummaryIndexBitcodeReader::parseValueSymbolTable( 6755 uint64_t Offset, 6756 DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap) { 6757 // With a strtab the VST is not required to parse the summary. 6758 if (UseStrtab) 6759 return Error::success(); 6760 6761 assert(Offset > 0 && "Expected non-zero VST offset"); 6762 Expected<uint64_t> MaybeCurrentBit = jumpToValueSymbolTable(Offset, Stream); 6763 if (!MaybeCurrentBit) 6764 return MaybeCurrentBit.takeError(); 6765 uint64_t CurrentBit = MaybeCurrentBit.get(); 6766 6767 if (Error Err = Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID)) 6768 return Err; 6769 6770 SmallVector<uint64_t, 64> Record; 6771 6772 // Read all the records for this value table. 6773 SmallString<128> ValueName; 6774 6775 while (true) { 6776 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); 6777 if (!MaybeEntry) 6778 return MaybeEntry.takeError(); 6779 BitstreamEntry Entry = MaybeEntry.get(); 6780 6781 switch (Entry.Kind) { 6782 case BitstreamEntry::SubBlock: // Handled for us already. 6783 case BitstreamEntry::Error: 6784 return error("Malformed block"); 6785 case BitstreamEntry::EndBlock: 6786 // Done parsing VST, jump back to wherever we came from. 6787 if (Error JumpFailed = Stream.JumpToBit(CurrentBit)) 6788 return JumpFailed; 6789 return Error::success(); 6790 case BitstreamEntry::Record: 6791 // The interesting case. 6792 break; 6793 } 6794 6795 // Read a record. 6796 Record.clear(); 6797 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record); 6798 if (!MaybeRecord) 6799 return MaybeRecord.takeError(); 6800 switch (MaybeRecord.get()) { 6801 default: // Default behavior: ignore (e.g. VST_CODE_BBENTRY records). 6802 break; 6803 case bitc::VST_CODE_ENTRY: { // VST_CODE_ENTRY: [valueid, namechar x N] 6804 if (convertToString(Record, 1, ValueName)) 6805 return error("Invalid record"); 6806 unsigned ValueID = Record[0]; 6807 assert(!SourceFileName.empty()); 6808 auto VLI = ValueIdToLinkageMap.find(ValueID); 6809 assert(VLI != ValueIdToLinkageMap.end() && 6810 "No linkage found for VST entry?"); 6811 auto Linkage = VLI->second; 6812 setValueGUID(ValueID, ValueName, Linkage, SourceFileName); 6813 ValueName.clear(); 6814 break; 6815 } 6816 case bitc::VST_CODE_FNENTRY: { 6817 // VST_CODE_FNENTRY: [valueid, offset, namechar x N] 6818 if (convertToString(Record, 2, ValueName)) 6819 return error("Invalid record"); 6820 unsigned ValueID = Record[0]; 6821 assert(!SourceFileName.empty()); 6822 auto VLI = ValueIdToLinkageMap.find(ValueID); 6823 assert(VLI != ValueIdToLinkageMap.end() && 6824 "No linkage found for VST entry?"); 6825 auto Linkage = VLI->second; 6826 setValueGUID(ValueID, ValueName, Linkage, SourceFileName); 6827 ValueName.clear(); 6828 break; 6829 } 6830 case bitc::VST_CODE_COMBINED_ENTRY: { 6831 // VST_CODE_COMBINED_ENTRY: [valueid, refguid] 6832 unsigned ValueID = Record[0]; 6833 GlobalValue::GUID RefGUID = Record[1]; 6834 // The "original name", which is the second value of the pair will be 6835 // overriden later by a FS_COMBINED_ORIGINAL_NAME in the combined index. 6836 ValueIdToValueInfoMap[ValueID] = std::make_tuple( 6837 TheIndex.getOrInsertValueInfo(RefGUID), RefGUID, RefGUID); 6838 break; 6839 } 6840 } 6841 } 6842 } 6843 6844 // Parse just the blocks needed for building the index out of the module. 6845 // At the end of this routine the module Index is populated with a map 6846 // from global value id to GlobalValueSummary objects. 6847 Error ModuleSummaryIndexBitcodeReader::parseModule() { 6848 if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID)) 6849 return Err; 6850 6851 SmallVector<uint64_t, 64> Record; 6852 DenseMap<unsigned, GlobalValue::LinkageTypes> ValueIdToLinkageMap; 6853 unsigned ValueId = 0; 6854 6855 // Read the index for this module. 6856 while (true) { 6857 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance(); 6858 if (!MaybeEntry) 6859 return MaybeEntry.takeError(); 6860 llvm::BitstreamEntry Entry = MaybeEntry.get(); 6861 6862 switch (Entry.Kind) { 6863 case BitstreamEntry::Error: 6864 return error("Malformed block"); 6865 case BitstreamEntry::EndBlock: 6866 return Error::success(); 6867 6868 case BitstreamEntry::SubBlock: 6869 switch (Entry.ID) { 6870 default: // Skip unknown content. 6871 if (Error Err = Stream.SkipBlock()) 6872 return Err; 6873 break; 6874 case bitc::BLOCKINFO_BLOCK_ID: 6875 // Need to parse these to get abbrev ids (e.g. for VST) 6876 if (Error Err = readBlockInfo()) 6877 return Err; 6878 break; 6879 case bitc::VALUE_SYMTAB_BLOCK_ID: 6880 // Should have been parsed earlier via VSTOffset, unless there 6881 // is no summary section. 6882 assert(((SeenValueSymbolTable && VSTOffset > 0) || 6883 !SeenGlobalValSummary) && 6884 "Expected early VST parse via VSTOffset record"); 6885 if (Error Err = Stream.SkipBlock()) 6886 return Err; 6887 break; 6888 case bitc::GLOBALVAL_SUMMARY_BLOCK_ID: 6889 case bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID: 6890 // Add the module if it is a per-module index (has a source file name). 6891 if (!SourceFileName.empty()) 6892 addThisModule(); 6893 assert(!SeenValueSymbolTable && 6894 "Already read VST when parsing summary block?"); 6895 // We might not have a VST if there were no values in the 6896 // summary. An empty summary block generated when we are 6897 // performing ThinLTO compiles so we don't later invoke 6898 // the regular LTO process on them. 6899 if (VSTOffset > 0) { 6900 if (Error Err = parseValueSymbolTable(VSTOffset, ValueIdToLinkageMap)) 6901 return Err; 6902 SeenValueSymbolTable = true; 6903 } 6904 SeenGlobalValSummary = true; 6905 if (Error Err = parseEntireSummary(Entry.ID)) 6906 return Err; 6907 break; 6908 case bitc::MODULE_STRTAB_BLOCK_ID: 6909 if (Error Err = parseModuleStringTable()) 6910 return Err; 6911 break; 6912 } 6913 continue; 6914 6915 case BitstreamEntry::Record: { 6916 Record.clear(); 6917 Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record); 6918 if (!MaybeBitCode) 6919 return MaybeBitCode.takeError(); 6920 switch (MaybeBitCode.get()) { 6921 default: 6922 break; // Default behavior, ignore unknown content. 6923 case bitc::MODULE_CODE_VERSION: { 6924 if (Error Err = parseVersionRecord(Record).takeError()) 6925 return Err; 6926 break; 6927 } 6928 /// MODULE_CODE_SOURCE_FILENAME: [namechar x N] 6929 case bitc::MODULE_CODE_SOURCE_FILENAME: { 6930 SmallString<128> ValueName; 6931 if (convertToString(Record, 0, ValueName)) 6932 return error("Invalid record"); 6933 SourceFileName = ValueName.c_str(); 6934 break; 6935 } 6936 /// MODULE_CODE_HASH: [5*i32] 6937 case bitc::MODULE_CODE_HASH: { 6938 if (Record.size() != 5) 6939 return error("Invalid hash length " + Twine(Record.size()).str()); 6940 auto &Hash = getThisModule()->second; 6941 int Pos = 0; 6942 for (auto &Val : Record) { 6943 assert(!(Val >> 32) && "Unexpected high bits set"); 6944 Hash[Pos++] = Val; 6945 } 6946 break; 6947 } 6948 /// MODULE_CODE_VSTOFFSET: [offset] 6949 case bitc::MODULE_CODE_VSTOFFSET: 6950 if (Record.empty()) 6951 return error("Invalid record"); 6952 // Note that we subtract 1 here because the offset is relative to one 6953 // word before the start of the identification or module block, which 6954 // was historically always the start of the regular bitcode header. 6955 VSTOffset = Record[0] - 1; 6956 break; 6957 // v1 GLOBALVAR: [pointer type, isconst, initid, linkage, ...] 6958 // v1 FUNCTION: [type, callingconv, isproto, linkage, ...] 6959 // v1 ALIAS: [alias type, addrspace, aliasee val#, linkage, ...] 6960 // v2: [strtab offset, strtab size, v1] 6961 case bitc::MODULE_CODE_GLOBALVAR: 6962 case bitc::MODULE_CODE_FUNCTION: 6963 case bitc::MODULE_CODE_ALIAS: { 6964 StringRef Name; 6965 ArrayRef<uint64_t> GVRecord; 6966 std::tie(Name, GVRecord) = readNameFromStrtab(Record); 6967 if (GVRecord.size() <= 3) 6968 return error("Invalid record"); 6969 uint64_t RawLinkage = GVRecord[3]; 6970 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage); 6971 if (!UseStrtab) { 6972 ValueIdToLinkageMap[ValueId++] = Linkage; 6973 break; 6974 } 6975 6976 setValueGUID(ValueId++, Name, Linkage, SourceFileName); 6977 break; 6978 } 6979 } 6980 } 6981 continue; 6982 } 6983 } 6984 } 6985 6986 std::vector<ValueInfo> 6987 ModuleSummaryIndexBitcodeReader::makeRefList(ArrayRef<uint64_t> Record) { 6988 std::vector<ValueInfo> Ret; 6989 Ret.reserve(Record.size()); 6990 for (uint64_t RefValueId : Record) 6991 Ret.push_back(std::get<0>(getValueInfoFromValueId(RefValueId))); 6992 return Ret; 6993 } 6994 6995 std::vector<FunctionSummary::EdgeTy> 6996 ModuleSummaryIndexBitcodeReader::makeCallList(ArrayRef<uint64_t> Record, 6997 bool IsOldProfileFormat, 6998 bool HasProfile, bool HasRelBF) { 6999 std::vector<FunctionSummary::EdgeTy> Ret; 7000 Ret.reserve(Record.size()); 7001 for (unsigned I = 0, E = Record.size(); I != E; ++I) { 7002 CalleeInfo::HotnessType Hotness = CalleeInfo::HotnessType::Unknown; 7003 uint64_t RelBF = 0; 7004 ValueInfo Callee = std::get<0>(getValueInfoFromValueId(Record[I])); 7005 if (IsOldProfileFormat) { 7006 I += 1; // Skip old callsitecount field 7007 if (HasProfile) 7008 I += 1; // Skip old profilecount field 7009 } else if (HasProfile) 7010 Hotness = static_cast<CalleeInfo::HotnessType>(Record[++I]); 7011 else if (HasRelBF) 7012 RelBF = Record[++I]; 7013 Ret.push_back(FunctionSummary::EdgeTy{Callee, CalleeInfo(Hotness, RelBF)}); 7014 } 7015 return Ret; 7016 } 7017 7018 static void 7019 parseWholeProgramDevirtResolutionByArg(ArrayRef<uint64_t> Record, size_t &Slot, 7020 WholeProgramDevirtResolution &Wpd) { 7021 uint64_t ArgNum = Record[Slot++]; 7022 WholeProgramDevirtResolution::ByArg &B = 7023 Wpd.ResByArg[{Record.begin() + Slot, Record.begin() + Slot + ArgNum}]; 7024 Slot += ArgNum; 7025 7026 B.TheKind = 7027 static_cast<WholeProgramDevirtResolution::ByArg::Kind>(Record[Slot++]); 7028 B.Info = Record[Slot++]; 7029 B.Byte = Record[Slot++]; 7030 B.Bit = Record[Slot++]; 7031 } 7032 7033 static void parseWholeProgramDevirtResolution(ArrayRef<uint64_t> Record, 7034 StringRef Strtab, size_t &Slot, 7035 TypeIdSummary &TypeId) { 7036 uint64_t Id = Record[Slot++]; 7037 WholeProgramDevirtResolution &Wpd = TypeId.WPDRes[Id]; 7038 7039 Wpd.TheKind = static_cast<WholeProgramDevirtResolution::Kind>(Record[Slot++]); 7040 Wpd.SingleImplName = {Strtab.data() + Record[Slot], 7041 static_cast<size_t>(Record[Slot + 1])}; 7042 Slot += 2; 7043 7044 uint64_t ResByArgNum = Record[Slot++]; 7045 for (uint64_t I = 0; I != ResByArgNum; ++I) 7046 parseWholeProgramDevirtResolutionByArg(Record, Slot, Wpd); 7047 } 7048 7049 static void parseTypeIdSummaryRecord(ArrayRef<uint64_t> Record, 7050 StringRef Strtab, 7051 ModuleSummaryIndex &TheIndex) { 7052 size_t Slot = 0; 7053 TypeIdSummary &TypeId = TheIndex.getOrInsertTypeIdSummary( 7054 {Strtab.data() + Record[Slot], static_cast<size_t>(Record[Slot + 1])}); 7055 Slot += 2; 7056 7057 TypeId.TTRes.TheKind = static_cast<TypeTestResolution::Kind>(Record[Slot++]); 7058 TypeId.TTRes.SizeM1BitWidth = Record[Slot++]; 7059 TypeId.TTRes.AlignLog2 = Record[Slot++]; 7060 TypeId.TTRes.SizeM1 = Record[Slot++]; 7061 TypeId.TTRes.BitMask = Record[Slot++]; 7062 TypeId.TTRes.InlineBits = Record[Slot++]; 7063 7064 while (Slot < Record.size()) 7065 parseWholeProgramDevirtResolution(Record, Strtab, Slot, TypeId); 7066 } 7067 7068 std::vector<FunctionSummary::ParamAccess> 7069 ModuleSummaryIndexBitcodeReader::parseParamAccesses(ArrayRef<uint64_t> Record) { 7070 auto ReadRange = [&]() { 7071 APInt Lower(FunctionSummary::ParamAccess::RangeWidth, 7072 BitcodeReader::decodeSignRotatedValue(Record.front())); 7073 Record = Record.drop_front(); 7074 APInt Upper(FunctionSummary::ParamAccess::RangeWidth, 7075 BitcodeReader::decodeSignRotatedValue(Record.front())); 7076 Record = Record.drop_front(); 7077 ConstantRange Range{Lower, Upper}; 7078 assert(!Range.isFullSet()); 7079 assert(!Range.isUpperSignWrapped()); 7080 return Range; 7081 }; 7082 7083 std::vector<FunctionSummary::ParamAccess> PendingParamAccesses; 7084 while (!Record.empty()) { 7085 PendingParamAccesses.emplace_back(); 7086 FunctionSummary::ParamAccess &ParamAccess = PendingParamAccesses.back(); 7087 ParamAccess.ParamNo = Record.front(); 7088 Record = Record.drop_front(); 7089 ParamAccess.Use = ReadRange(); 7090 ParamAccess.Calls.resize(Record.front()); 7091 Record = Record.drop_front(); 7092 for (auto &Call : ParamAccess.Calls) { 7093 Call.ParamNo = Record.front(); 7094 Record = Record.drop_front(); 7095 Call.Callee = std::get<0>(getValueInfoFromValueId(Record.front())); 7096 Record = Record.drop_front(); 7097 Call.Offsets = ReadRange(); 7098 } 7099 } 7100 return PendingParamAccesses; 7101 } 7102 7103 void ModuleSummaryIndexBitcodeReader::parseTypeIdCompatibleVtableInfo( 7104 ArrayRef<uint64_t> Record, size_t &Slot, 7105 TypeIdCompatibleVtableInfo &TypeId) { 7106 uint64_t Offset = Record[Slot++]; 7107 ValueInfo Callee = std::get<0>(getValueInfoFromValueId(Record[Slot++])); 7108 TypeId.push_back({Offset, Callee}); 7109 } 7110 7111 void ModuleSummaryIndexBitcodeReader::parseTypeIdCompatibleVtableSummaryRecord( 7112 ArrayRef<uint64_t> Record) { 7113 size_t Slot = 0; 7114 TypeIdCompatibleVtableInfo &TypeId = 7115 TheIndex.getOrInsertTypeIdCompatibleVtableSummary( 7116 {Strtab.data() + Record[Slot], 7117 static_cast<size_t>(Record[Slot + 1])}); 7118 Slot += 2; 7119 7120 while (Slot < Record.size()) 7121 parseTypeIdCompatibleVtableInfo(Record, Slot, TypeId); 7122 } 7123 7124 static void setSpecialRefs(std::vector<ValueInfo> &Refs, unsigned ROCnt, 7125 unsigned WOCnt) { 7126 // Readonly and writeonly refs are in the end of the refs list. 7127 assert(ROCnt + WOCnt <= Refs.size()); 7128 unsigned FirstWORef = Refs.size() - WOCnt; 7129 unsigned RefNo = FirstWORef - ROCnt; 7130 for (; RefNo < FirstWORef; ++RefNo) 7131 Refs[RefNo].setReadOnly(); 7132 for (; RefNo < Refs.size(); ++RefNo) 7133 Refs[RefNo].setWriteOnly(); 7134 } 7135 7136 // Eagerly parse the entire summary block. This populates the GlobalValueSummary 7137 // objects in the index. 7138 Error ModuleSummaryIndexBitcodeReader::parseEntireSummary(unsigned ID) { 7139 if (Error Err = Stream.EnterSubBlock(ID)) 7140 return Err; 7141 SmallVector<uint64_t, 64> Record; 7142 7143 // Parse version 7144 { 7145 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); 7146 if (!MaybeEntry) 7147 return MaybeEntry.takeError(); 7148 BitstreamEntry Entry = MaybeEntry.get(); 7149 7150 if (Entry.Kind != BitstreamEntry::Record) 7151 return error("Invalid Summary Block: record for version expected"); 7152 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record); 7153 if (!MaybeRecord) 7154 return MaybeRecord.takeError(); 7155 if (MaybeRecord.get() != bitc::FS_VERSION) 7156 return error("Invalid Summary Block: version expected"); 7157 } 7158 const uint64_t Version = Record[0]; 7159 const bool IsOldProfileFormat = Version == 1; 7160 if (Version < 1 || Version > ModuleSummaryIndex::BitcodeSummaryVersion) 7161 return error("Invalid summary version " + Twine(Version) + 7162 ". Version should be in the range [1-" + 7163 Twine(ModuleSummaryIndex::BitcodeSummaryVersion) + 7164 "]."); 7165 Record.clear(); 7166 7167 // Keep around the last seen summary to be used when we see an optional 7168 // "OriginalName" attachement. 7169 GlobalValueSummary *LastSeenSummary = nullptr; 7170 GlobalValue::GUID LastSeenGUID = 0; 7171 7172 // We can expect to see any number of type ID information records before 7173 // each function summary records; these variables store the information 7174 // collected so far so that it can be used to create the summary object. 7175 std::vector<GlobalValue::GUID> PendingTypeTests; 7176 std::vector<FunctionSummary::VFuncId> PendingTypeTestAssumeVCalls, 7177 PendingTypeCheckedLoadVCalls; 7178 std::vector<FunctionSummary::ConstVCall> PendingTypeTestAssumeConstVCalls, 7179 PendingTypeCheckedLoadConstVCalls; 7180 std::vector<FunctionSummary::ParamAccess> PendingParamAccesses; 7181 7182 std::vector<CallsiteInfo> PendingCallsites; 7183 std::vector<AllocInfo> PendingAllocs; 7184 7185 while (true) { 7186 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); 7187 if (!MaybeEntry) 7188 return MaybeEntry.takeError(); 7189 BitstreamEntry Entry = MaybeEntry.get(); 7190 7191 switch (Entry.Kind) { 7192 case BitstreamEntry::SubBlock: // Handled for us already. 7193 case BitstreamEntry::Error: 7194 return error("Malformed block"); 7195 case BitstreamEntry::EndBlock: 7196 return Error::success(); 7197 case BitstreamEntry::Record: 7198 // The interesting case. 7199 break; 7200 } 7201 7202 // Read a record. The record format depends on whether this 7203 // is a per-module index or a combined index file. In the per-module 7204 // case the records contain the associated value's ID for correlation 7205 // with VST entries. In the combined index the correlation is done 7206 // via the bitcode offset of the summary records (which were saved 7207 // in the combined index VST entries). The records also contain 7208 // information used for ThinLTO renaming and importing. 7209 Record.clear(); 7210 Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record); 7211 if (!MaybeBitCode) 7212 return MaybeBitCode.takeError(); 7213 switch (unsigned BitCode = MaybeBitCode.get()) { 7214 default: // Default behavior: ignore. 7215 break; 7216 case bitc::FS_FLAGS: { // [flags] 7217 TheIndex.setFlags(Record[0]); 7218 break; 7219 } 7220 case bitc::FS_VALUE_GUID: { // [valueid, refguid] 7221 uint64_t ValueID = Record[0]; 7222 GlobalValue::GUID RefGUID = Record[1]; 7223 ValueIdToValueInfoMap[ValueID] = std::make_tuple( 7224 TheIndex.getOrInsertValueInfo(RefGUID), RefGUID, RefGUID); 7225 break; 7226 } 7227 // FS_PERMODULE: [valueid, flags, instcount, fflags, numrefs, 7228 // numrefs x valueid, n x (valueid)] 7229 // FS_PERMODULE_PROFILE: [valueid, flags, instcount, fflags, numrefs, 7230 // numrefs x valueid, 7231 // n x (valueid, hotness)] 7232 // FS_PERMODULE_RELBF: [valueid, flags, instcount, fflags, numrefs, 7233 // numrefs x valueid, 7234 // n x (valueid, relblockfreq)] 7235 case bitc::FS_PERMODULE: 7236 case bitc::FS_PERMODULE_RELBF: 7237 case bitc::FS_PERMODULE_PROFILE: { 7238 unsigned ValueID = Record[0]; 7239 uint64_t RawFlags = Record[1]; 7240 unsigned InstCount = Record[2]; 7241 uint64_t RawFunFlags = 0; 7242 unsigned NumRefs = Record[3]; 7243 unsigned NumRORefs = 0, NumWORefs = 0; 7244 int RefListStartIndex = 4; 7245 if (Version >= 4) { 7246 RawFunFlags = Record[3]; 7247 NumRefs = Record[4]; 7248 RefListStartIndex = 5; 7249 if (Version >= 5) { 7250 NumRORefs = Record[5]; 7251 RefListStartIndex = 6; 7252 if (Version >= 7) { 7253 NumWORefs = Record[6]; 7254 RefListStartIndex = 7; 7255 } 7256 } 7257 } 7258 7259 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version); 7260 // The module path string ref set in the summary must be owned by the 7261 // index's module string table. Since we don't have a module path 7262 // string table section in the per-module index, we create a single 7263 // module path string table entry with an empty (0) ID to take 7264 // ownership. 7265 int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs; 7266 assert(Record.size() >= RefListStartIndex + NumRefs && 7267 "Record size inconsistent with number of references"); 7268 std::vector<ValueInfo> Refs = makeRefList( 7269 ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs)); 7270 bool HasProfile = (BitCode == bitc::FS_PERMODULE_PROFILE); 7271 bool HasRelBF = (BitCode == bitc::FS_PERMODULE_RELBF); 7272 std::vector<FunctionSummary::EdgeTy> Calls = makeCallList( 7273 ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex), 7274 IsOldProfileFormat, HasProfile, HasRelBF); 7275 setSpecialRefs(Refs, NumRORefs, NumWORefs); 7276 auto VIAndOriginalGUID = getValueInfoFromValueId(ValueID); 7277 // In order to save memory, only record the memprof summaries if this is 7278 // the prevailing copy of a symbol. The linker doesn't resolve local 7279 // linkage values so don't check whether those are prevailing. 7280 auto LT = (GlobalValue::LinkageTypes)Flags.Linkage; 7281 if (IsPrevailing && 7282 !GlobalValue::isLocalLinkage(LT) && 7283 !IsPrevailing(std::get<2>(VIAndOriginalGUID))) { 7284 PendingCallsites.clear(); 7285 PendingAllocs.clear(); 7286 } 7287 auto FS = std::make_unique<FunctionSummary>( 7288 Flags, InstCount, getDecodedFFlags(RawFunFlags), /*EntryCount=*/0, 7289 std::move(Refs), std::move(Calls), std::move(PendingTypeTests), 7290 std::move(PendingTypeTestAssumeVCalls), 7291 std::move(PendingTypeCheckedLoadVCalls), 7292 std::move(PendingTypeTestAssumeConstVCalls), 7293 std::move(PendingTypeCheckedLoadConstVCalls), 7294 std::move(PendingParamAccesses), std::move(PendingCallsites), 7295 std::move(PendingAllocs)); 7296 FS->setModulePath(getThisModule()->first()); 7297 FS->setOriginalName(std::get<1>(VIAndOriginalGUID)); 7298 TheIndex.addGlobalValueSummary(std::get<0>(VIAndOriginalGUID), 7299 std::move(FS)); 7300 break; 7301 } 7302 // FS_ALIAS: [valueid, flags, valueid] 7303 // Aliases must be emitted (and parsed) after all FS_PERMODULE entries, as 7304 // they expect all aliasee summaries to be available. 7305 case bitc::FS_ALIAS: { 7306 unsigned ValueID = Record[0]; 7307 uint64_t RawFlags = Record[1]; 7308 unsigned AliaseeID = Record[2]; 7309 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version); 7310 auto AS = std::make_unique<AliasSummary>(Flags); 7311 // The module path string ref set in the summary must be owned by the 7312 // index's module string table. Since we don't have a module path 7313 // string table section in the per-module index, we create a single 7314 // module path string table entry with an empty (0) ID to take 7315 // ownership. 7316 AS->setModulePath(getThisModule()->first()); 7317 7318 auto AliaseeVI = std::get<0>(getValueInfoFromValueId(AliaseeID)); 7319 auto AliaseeInModule = TheIndex.findSummaryInModule(AliaseeVI, ModulePath); 7320 if (!AliaseeInModule) 7321 return error("Alias expects aliasee summary to be parsed"); 7322 AS->setAliasee(AliaseeVI, AliaseeInModule); 7323 7324 auto GUID = getValueInfoFromValueId(ValueID); 7325 AS->setOriginalName(std::get<1>(GUID)); 7326 TheIndex.addGlobalValueSummary(std::get<0>(GUID), std::move(AS)); 7327 break; 7328 } 7329 // FS_PERMODULE_GLOBALVAR_INIT_REFS: [valueid, flags, varflags, n x valueid] 7330 case bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS: { 7331 unsigned ValueID = Record[0]; 7332 uint64_t RawFlags = Record[1]; 7333 unsigned RefArrayStart = 2; 7334 GlobalVarSummary::GVarFlags GVF(/* ReadOnly */ false, 7335 /* WriteOnly */ false, 7336 /* Constant */ false, 7337 GlobalObject::VCallVisibilityPublic); 7338 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version); 7339 if (Version >= 5) { 7340 GVF = getDecodedGVarFlags(Record[2]); 7341 RefArrayStart = 3; 7342 } 7343 std::vector<ValueInfo> Refs = 7344 makeRefList(ArrayRef<uint64_t>(Record).slice(RefArrayStart)); 7345 auto FS = 7346 std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs)); 7347 FS->setModulePath(getThisModule()->first()); 7348 auto GUID = getValueInfoFromValueId(ValueID); 7349 FS->setOriginalName(std::get<1>(GUID)); 7350 TheIndex.addGlobalValueSummary(std::get<0>(GUID), std::move(FS)); 7351 break; 7352 } 7353 // FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS: [valueid, flags, varflags, 7354 // numrefs, numrefs x valueid, 7355 // n x (valueid, offset)] 7356 case bitc::FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS: { 7357 unsigned ValueID = Record[0]; 7358 uint64_t RawFlags = Record[1]; 7359 GlobalVarSummary::GVarFlags GVF = getDecodedGVarFlags(Record[2]); 7360 unsigned NumRefs = Record[3]; 7361 unsigned RefListStartIndex = 4; 7362 unsigned VTableListStartIndex = RefListStartIndex + NumRefs; 7363 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version); 7364 std::vector<ValueInfo> Refs = makeRefList( 7365 ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs)); 7366 VTableFuncList VTableFuncs; 7367 for (unsigned I = VTableListStartIndex, E = Record.size(); I != E; ++I) { 7368 ValueInfo Callee = std::get<0>(getValueInfoFromValueId(Record[I])); 7369 uint64_t Offset = Record[++I]; 7370 VTableFuncs.push_back({Callee, Offset}); 7371 } 7372 auto VS = 7373 std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs)); 7374 VS->setModulePath(getThisModule()->first()); 7375 VS->setVTableFuncs(VTableFuncs); 7376 auto GUID = getValueInfoFromValueId(ValueID); 7377 VS->setOriginalName(std::get<1>(GUID)); 7378 TheIndex.addGlobalValueSummary(std::get<0>(GUID), std::move(VS)); 7379 break; 7380 } 7381 // FS_COMBINED: [valueid, modid, flags, instcount, fflags, numrefs, 7382 // numrefs x valueid, n x (valueid)] 7383 // FS_COMBINED_PROFILE: [valueid, modid, flags, instcount, fflags, numrefs, 7384 // numrefs x valueid, n x (valueid, hotness)] 7385 case bitc::FS_COMBINED: 7386 case bitc::FS_COMBINED_PROFILE: { 7387 unsigned ValueID = Record[0]; 7388 uint64_t ModuleId = Record[1]; 7389 uint64_t RawFlags = Record[2]; 7390 unsigned InstCount = Record[3]; 7391 uint64_t RawFunFlags = 0; 7392 uint64_t EntryCount = 0; 7393 unsigned NumRefs = Record[4]; 7394 unsigned NumRORefs = 0, NumWORefs = 0; 7395 int RefListStartIndex = 5; 7396 7397 if (Version >= 4) { 7398 RawFunFlags = Record[4]; 7399 RefListStartIndex = 6; 7400 size_t NumRefsIndex = 5; 7401 if (Version >= 5) { 7402 unsigned NumRORefsOffset = 1; 7403 RefListStartIndex = 7; 7404 if (Version >= 6) { 7405 NumRefsIndex = 6; 7406 EntryCount = Record[5]; 7407 RefListStartIndex = 8; 7408 if (Version >= 7) { 7409 RefListStartIndex = 9; 7410 NumWORefs = Record[8]; 7411 NumRORefsOffset = 2; 7412 } 7413 } 7414 NumRORefs = Record[RefListStartIndex - NumRORefsOffset]; 7415 } 7416 NumRefs = Record[NumRefsIndex]; 7417 } 7418 7419 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version); 7420 int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs; 7421 assert(Record.size() >= RefListStartIndex + NumRefs && 7422 "Record size inconsistent with number of references"); 7423 std::vector<ValueInfo> Refs = makeRefList( 7424 ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs)); 7425 bool HasProfile = (BitCode == bitc::FS_COMBINED_PROFILE); 7426 std::vector<FunctionSummary::EdgeTy> Edges = makeCallList( 7427 ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex), 7428 IsOldProfileFormat, HasProfile, false); 7429 ValueInfo VI = std::get<0>(getValueInfoFromValueId(ValueID)); 7430 setSpecialRefs(Refs, NumRORefs, NumWORefs); 7431 auto FS = std::make_unique<FunctionSummary>( 7432 Flags, InstCount, getDecodedFFlags(RawFunFlags), EntryCount, 7433 std::move(Refs), std::move(Edges), std::move(PendingTypeTests), 7434 std::move(PendingTypeTestAssumeVCalls), 7435 std::move(PendingTypeCheckedLoadVCalls), 7436 std::move(PendingTypeTestAssumeConstVCalls), 7437 std::move(PendingTypeCheckedLoadConstVCalls), 7438 std::move(PendingParamAccesses), std::move(PendingCallsites), 7439 std::move(PendingAllocs)); 7440 LastSeenSummary = FS.get(); 7441 LastSeenGUID = VI.getGUID(); 7442 FS->setModulePath(ModuleIdMap[ModuleId]); 7443 TheIndex.addGlobalValueSummary(VI, std::move(FS)); 7444 break; 7445 } 7446 // FS_COMBINED_ALIAS: [valueid, modid, flags, valueid] 7447 // Aliases must be emitted (and parsed) after all FS_COMBINED entries, as 7448 // they expect all aliasee summaries to be available. 7449 case bitc::FS_COMBINED_ALIAS: { 7450 unsigned ValueID = Record[0]; 7451 uint64_t ModuleId = Record[1]; 7452 uint64_t RawFlags = Record[2]; 7453 unsigned AliaseeValueId = Record[3]; 7454 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version); 7455 auto AS = std::make_unique<AliasSummary>(Flags); 7456 LastSeenSummary = AS.get(); 7457 AS->setModulePath(ModuleIdMap[ModuleId]); 7458 7459 auto AliaseeVI = std::get<0>(getValueInfoFromValueId(AliaseeValueId)); 7460 auto AliaseeInModule = TheIndex.findSummaryInModule(AliaseeVI, AS->modulePath()); 7461 AS->setAliasee(AliaseeVI, AliaseeInModule); 7462 7463 ValueInfo VI = std::get<0>(getValueInfoFromValueId(ValueID)); 7464 LastSeenGUID = VI.getGUID(); 7465 TheIndex.addGlobalValueSummary(VI, std::move(AS)); 7466 break; 7467 } 7468 // FS_COMBINED_GLOBALVAR_INIT_REFS: [valueid, modid, flags, n x valueid] 7469 case bitc::FS_COMBINED_GLOBALVAR_INIT_REFS: { 7470 unsigned ValueID = Record[0]; 7471 uint64_t ModuleId = Record[1]; 7472 uint64_t RawFlags = Record[2]; 7473 unsigned RefArrayStart = 3; 7474 GlobalVarSummary::GVarFlags GVF(/* ReadOnly */ false, 7475 /* WriteOnly */ false, 7476 /* Constant */ false, 7477 GlobalObject::VCallVisibilityPublic); 7478 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version); 7479 if (Version >= 5) { 7480 GVF = getDecodedGVarFlags(Record[3]); 7481 RefArrayStart = 4; 7482 } 7483 std::vector<ValueInfo> Refs = 7484 makeRefList(ArrayRef<uint64_t>(Record).slice(RefArrayStart)); 7485 auto FS = 7486 std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs)); 7487 LastSeenSummary = FS.get(); 7488 FS->setModulePath(ModuleIdMap[ModuleId]); 7489 ValueInfo VI = std::get<0>(getValueInfoFromValueId(ValueID)); 7490 LastSeenGUID = VI.getGUID(); 7491 TheIndex.addGlobalValueSummary(VI, std::move(FS)); 7492 break; 7493 } 7494 // FS_COMBINED_ORIGINAL_NAME: [original_name] 7495 case bitc::FS_COMBINED_ORIGINAL_NAME: { 7496 uint64_t OriginalName = Record[0]; 7497 if (!LastSeenSummary) 7498 return error("Name attachment that does not follow a combined record"); 7499 LastSeenSummary->setOriginalName(OriginalName); 7500 TheIndex.addOriginalName(LastSeenGUID, OriginalName); 7501 // Reset the LastSeenSummary 7502 LastSeenSummary = nullptr; 7503 LastSeenGUID = 0; 7504 break; 7505 } 7506 case bitc::FS_TYPE_TESTS: 7507 assert(PendingTypeTests.empty()); 7508 llvm::append_range(PendingTypeTests, Record); 7509 break; 7510 7511 case bitc::FS_TYPE_TEST_ASSUME_VCALLS: 7512 assert(PendingTypeTestAssumeVCalls.empty()); 7513 for (unsigned I = 0; I != Record.size(); I += 2) 7514 PendingTypeTestAssumeVCalls.push_back({Record[I], Record[I+1]}); 7515 break; 7516 7517 case bitc::FS_TYPE_CHECKED_LOAD_VCALLS: 7518 assert(PendingTypeCheckedLoadVCalls.empty()); 7519 for (unsigned I = 0; I != Record.size(); I += 2) 7520 PendingTypeCheckedLoadVCalls.push_back({Record[I], Record[I+1]}); 7521 break; 7522 7523 case bitc::FS_TYPE_TEST_ASSUME_CONST_VCALL: 7524 PendingTypeTestAssumeConstVCalls.push_back( 7525 {{Record[0], Record[1]}, {Record.begin() + 2, Record.end()}}); 7526 break; 7527 7528 case bitc::FS_TYPE_CHECKED_LOAD_CONST_VCALL: 7529 PendingTypeCheckedLoadConstVCalls.push_back( 7530 {{Record[0], Record[1]}, {Record.begin() + 2, Record.end()}}); 7531 break; 7532 7533 case bitc::FS_CFI_FUNCTION_DEFS: { 7534 std::set<std::string> &CfiFunctionDefs = TheIndex.cfiFunctionDefs(); 7535 for (unsigned I = 0; I != Record.size(); I += 2) 7536 CfiFunctionDefs.insert( 7537 {Strtab.data() + Record[I], static_cast<size_t>(Record[I + 1])}); 7538 break; 7539 } 7540 7541 case bitc::FS_CFI_FUNCTION_DECLS: { 7542 std::set<std::string> &CfiFunctionDecls = TheIndex.cfiFunctionDecls(); 7543 for (unsigned I = 0; I != Record.size(); I += 2) 7544 CfiFunctionDecls.insert( 7545 {Strtab.data() + Record[I], static_cast<size_t>(Record[I + 1])}); 7546 break; 7547 } 7548 7549 case bitc::FS_TYPE_ID: 7550 parseTypeIdSummaryRecord(Record, Strtab, TheIndex); 7551 break; 7552 7553 case bitc::FS_TYPE_ID_METADATA: 7554 parseTypeIdCompatibleVtableSummaryRecord(Record); 7555 break; 7556 7557 case bitc::FS_BLOCK_COUNT: 7558 TheIndex.addBlockCount(Record[0]); 7559 break; 7560 7561 case bitc::FS_PARAM_ACCESS: { 7562 PendingParamAccesses = parseParamAccesses(Record); 7563 break; 7564 } 7565 7566 case bitc::FS_STACK_IDS: { // [n x stackid] 7567 // Save stack ids in the reader to consult when adding stack ids from the 7568 // lists in the stack node and alloc node entries. 7569 StackIds = ArrayRef<uint64_t>(Record); 7570 break; 7571 } 7572 7573 case bitc::FS_PERMODULE_CALLSITE_INFO: { 7574 unsigned ValueID = Record[0]; 7575 SmallVector<unsigned> StackIdList; 7576 for (auto R = Record.begin() + 1; R != Record.end(); R++) { 7577 assert(*R < StackIds.size()); 7578 StackIdList.push_back(TheIndex.addOrGetStackIdIndex(StackIds[*R])); 7579 } 7580 ValueInfo VI = std::get<0>(getValueInfoFromValueId(ValueID)); 7581 PendingCallsites.push_back(CallsiteInfo({VI, std::move(StackIdList)})); 7582 break; 7583 } 7584 7585 case bitc::FS_COMBINED_CALLSITE_INFO: { 7586 auto RecordIter = Record.begin(); 7587 unsigned ValueID = *RecordIter++; 7588 unsigned NumStackIds = *RecordIter++; 7589 unsigned NumVersions = *RecordIter++; 7590 assert(Record.size() == 3 + NumStackIds + NumVersions); 7591 SmallVector<unsigned> StackIdList; 7592 for (unsigned J = 0; J < NumStackIds; J++) { 7593 assert(*RecordIter < StackIds.size()); 7594 StackIdList.push_back( 7595 TheIndex.addOrGetStackIdIndex(StackIds[*RecordIter++])); 7596 } 7597 SmallVector<unsigned> Versions; 7598 for (unsigned J = 0; J < NumVersions; J++) 7599 Versions.push_back(*RecordIter++); 7600 ValueInfo VI = std::get<0>( 7601 getValueInfoFromValueId</*AllowNullValueInfo*/ true>(ValueID)); 7602 PendingCallsites.push_back( 7603 CallsiteInfo({VI, std::move(Versions), std::move(StackIdList)})); 7604 break; 7605 } 7606 7607 case bitc::FS_PERMODULE_ALLOC_INFO: { 7608 unsigned I = 0; 7609 std::vector<MIBInfo> MIBs; 7610 while (I < Record.size()) { 7611 assert(Record.size() - I >= 2); 7612 AllocationType AllocType = (AllocationType)Record[I++]; 7613 unsigned NumStackEntries = Record[I++]; 7614 assert(Record.size() - I >= NumStackEntries); 7615 SmallVector<unsigned> StackIdList; 7616 for (unsigned J = 0; J < NumStackEntries; J++) { 7617 assert(Record[I] < StackIds.size()); 7618 StackIdList.push_back( 7619 TheIndex.addOrGetStackIdIndex(StackIds[Record[I++]])); 7620 } 7621 MIBs.push_back(MIBInfo(AllocType, std::move(StackIdList))); 7622 } 7623 PendingAllocs.push_back(AllocInfo(std::move(MIBs))); 7624 break; 7625 } 7626 7627 case bitc::FS_COMBINED_ALLOC_INFO: { 7628 unsigned I = 0; 7629 std::vector<MIBInfo> MIBs; 7630 unsigned NumMIBs = Record[I++]; 7631 unsigned NumVersions = Record[I++]; 7632 unsigned MIBsRead = 0; 7633 while (MIBsRead++ < NumMIBs) { 7634 assert(Record.size() - I >= 2); 7635 AllocationType AllocType = (AllocationType)Record[I++]; 7636 unsigned NumStackEntries = Record[I++]; 7637 assert(Record.size() - I >= NumStackEntries); 7638 SmallVector<unsigned> StackIdList; 7639 for (unsigned J = 0; J < NumStackEntries; J++) { 7640 assert(Record[I] < StackIds.size()); 7641 StackIdList.push_back( 7642 TheIndex.addOrGetStackIdIndex(StackIds[Record[I++]])); 7643 } 7644 MIBs.push_back(MIBInfo(AllocType, std::move(StackIdList))); 7645 } 7646 assert(Record.size() - I >= NumVersions); 7647 SmallVector<uint8_t> Versions; 7648 for (unsigned J = 0; J < NumVersions; J++) 7649 Versions.push_back(Record[I++]); 7650 PendingAllocs.push_back( 7651 AllocInfo(std::move(Versions), std::move(MIBs))); 7652 break; 7653 } 7654 } 7655 } 7656 llvm_unreachable("Exit infinite loop"); 7657 } 7658 7659 // Parse the module string table block into the Index. 7660 // This populates the ModulePathStringTable map in the index. 7661 Error ModuleSummaryIndexBitcodeReader::parseModuleStringTable() { 7662 if (Error Err = Stream.EnterSubBlock(bitc::MODULE_STRTAB_BLOCK_ID)) 7663 return Err; 7664 7665 SmallVector<uint64_t, 64> Record; 7666 7667 SmallString<128> ModulePath; 7668 ModuleSummaryIndex::ModuleInfo *LastSeenModule = nullptr; 7669 7670 while (true) { 7671 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); 7672 if (!MaybeEntry) 7673 return MaybeEntry.takeError(); 7674 BitstreamEntry Entry = MaybeEntry.get(); 7675 7676 switch (Entry.Kind) { 7677 case BitstreamEntry::SubBlock: // Handled for us already. 7678 case BitstreamEntry::Error: 7679 return error("Malformed block"); 7680 case BitstreamEntry::EndBlock: 7681 return Error::success(); 7682 case BitstreamEntry::Record: 7683 // The interesting case. 7684 break; 7685 } 7686 7687 Record.clear(); 7688 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record); 7689 if (!MaybeRecord) 7690 return MaybeRecord.takeError(); 7691 switch (MaybeRecord.get()) { 7692 default: // Default behavior: ignore. 7693 break; 7694 case bitc::MST_CODE_ENTRY: { 7695 // MST_ENTRY: [modid, namechar x N] 7696 uint64_t ModuleId = Record[0]; 7697 7698 if (convertToString(Record, 1, ModulePath)) 7699 return error("Invalid record"); 7700 7701 LastSeenModule = TheIndex.addModule(ModulePath); 7702 ModuleIdMap[ModuleId] = LastSeenModule->first(); 7703 7704 ModulePath.clear(); 7705 break; 7706 } 7707 /// MST_CODE_HASH: [5*i32] 7708 case bitc::MST_CODE_HASH: { 7709 if (Record.size() != 5) 7710 return error("Invalid hash length " + Twine(Record.size()).str()); 7711 if (!LastSeenModule) 7712 return error("Invalid hash that does not follow a module path"); 7713 int Pos = 0; 7714 for (auto &Val : Record) { 7715 assert(!(Val >> 32) && "Unexpected high bits set"); 7716 LastSeenModule->second[Pos++] = Val; 7717 } 7718 // Reset LastSeenModule to avoid overriding the hash unexpectedly. 7719 LastSeenModule = nullptr; 7720 break; 7721 } 7722 } 7723 } 7724 llvm_unreachable("Exit infinite loop"); 7725 } 7726 7727 namespace { 7728 7729 // FIXME: This class is only here to support the transition to llvm::Error. It 7730 // will be removed once this transition is complete. Clients should prefer to 7731 // deal with the Error value directly, rather than converting to error_code. 7732 class BitcodeErrorCategoryType : public std::error_category { 7733 const char *name() const noexcept override { 7734 return "llvm.bitcode"; 7735 } 7736 7737 std::string message(int IE) const override { 7738 BitcodeError E = static_cast<BitcodeError>(IE); 7739 switch (E) { 7740 case BitcodeError::CorruptedBitcode: 7741 return "Corrupted bitcode"; 7742 } 7743 llvm_unreachable("Unknown error type!"); 7744 } 7745 }; 7746 7747 } // end anonymous namespace 7748 7749 const std::error_category &llvm::BitcodeErrorCategory() { 7750 static BitcodeErrorCategoryType ErrorCategory; 7751 return ErrorCategory; 7752 } 7753 7754 static Expected<StringRef> readBlobInRecord(BitstreamCursor &Stream, 7755 unsigned Block, unsigned RecordID) { 7756 if (Error Err = Stream.EnterSubBlock(Block)) 7757 return std::move(Err); 7758 7759 StringRef Strtab; 7760 while (true) { 7761 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance(); 7762 if (!MaybeEntry) 7763 return MaybeEntry.takeError(); 7764 llvm::BitstreamEntry Entry = MaybeEntry.get(); 7765 7766 switch (Entry.Kind) { 7767 case BitstreamEntry::EndBlock: 7768 return Strtab; 7769 7770 case BitstreamEntry::Error: 7771 return error("Malformed block"); 7772 7773 case BitstreamEntry::SubBlock: 7774 if (Error Err = Stream.SkipBlock()) 7775 return std::move(Err); 7776 break; 7777 7778 case BitstreamEntry::Record: 7779 StringRef Blob; 7780 SmallVector<uint64_t, 1> Record; 7781 Expected<unsigned> MaybeRecord = 7782 Stream.readRecord(Entry.ID, Record, &Blob); 7783 if (!MaybeRecord) 7784 return MaybeRecord.takeError(); 7785 if (MaybeRecord.get() == RecordID) 7786 Strtab = Blob; 7787 break; 7788 } 7789 } 7790 } 7791 7792 //===----------------------------------------------------------------------===// 7793 // External interface 7794 //===----------------------------------------------------------------------===// 7795 7796 Expected<std::vector<BitcodeModule>> 7797 llvm::getBitcodeModuleList(MemoryBufferRef Buffer) { 7798 auto FOrErr = getBitcodeFileContents(Buffer); 7799 if (!FOrErr) 7800 return FOrErr.takeError(); 7801 return std::move(FOrErr->Mods); 7802 } 7803 7804 Expected<BitcodeFileContents> 7805 llvm::getBitcodeFileContents(MemoryBufferRef Buffer) { 7806 Expected<BitstreamCursor> StreamOrErr = initStream(Buffer); 7807 if (!StreamOrErr) 7808 return StreamOrErr.takeError(); 7809 BitstreamCursor &Stream = *StreamOrErr; 7810 7811 BitcodeFileContents F; 7812 while (true) { 7813 uint64_t BCBegin = Stream.getCurrentByteNo(); 7814 7815 // We may be consuming bitcode from a client that leaves garbage at the end 7816 // of the bitcode stream (e.g. Apple's ar tool). If we are close enough to 7817 // the end that there cannot possibly be another module, stop looking. 7818 if (BCBegin + 8 >= Stream.getBitcodeBytes().size()) 7819 return F; 7820 7821 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance(); 7822 if (!MaybeEntry) 7823 return MaybeEntry.takeError(); 7824 llvm::BitstreamEntry Entry = MaybeEntry.get(); 7825 7826 switch (Entry.Kind) { 7827 case BitstreamEntry::EndBlock: 7828 case BitstreamEntry::Error: 7829 return error("Malformed block"); 7830 7831 case BitstreamEntry::SubBlock: { 7832 uint64_t IdentificationBit = -1ull; 7833 if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) { 7834 IdentificationBit = Stream.GetCurrentBitNo() - BCBegin * 8; 7835 if (Error Err = Stream.SkipBlock()) 7836 return std::move(Err); 7837 7838 { 7839 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance(); 7840 if (!MaybeEntry) 7841 return MaybeEntry.takeError(); 7842 Entry = MaybeEntry.get(); 7843 } 7844 7845 if (Entry.Kind != BitstreamEntry::SubBlock || 7846 Entry.ID != bitc::MODULE_BLOCK_ID) 7847 return error("Malformed block"); 7848 } 7849 7850 if (Entry.ID == bitc::MODULE_BLOCK_ID) { 7851 uint64_t ModuleBit = Stream.GetCurrentBitNo() - BCBegin * 8; 7852 if (Error Err = Stream.SkipBlock()) 7853 return std::move(Err); 7854 7855 F.Mods.push_back({Stream.getBitcodeBytes().slice( 7856 BCBegin, Stream.getCurrentByteNo() - BCBegin), 7857 Buffer.getBufferIdentifier(), IdentificationBit, 7858 ModuleBit}); 7859 continue; 7860 } 7861 7862 if (Entry.ID == bitc::STRTAB_BLOCK_ID) { 7863 Expected<StringRef> Strtab = 7864 readBlobInRecord(Stream, bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB); 7865 if (!Strtab) 7866 return Strtab.takeError(); 7867 // This string table is used by every preceding bitcode module that does 7868 // not have its own string table. A bitcode file may have multiple 7869 // string tables if it was created by binary concatenation, for example 7870 // with "llvm-cat -b". 7871 for (BitcodeModule &I : llvm::reverse(F.Mods)) { 7872 if (!I.Strtab.empty()) 7873 break; 7874 I.Strtab = *Strtab; 7875 } 7876 // Similarly, the string table is used by every preceding symbol table; 7877 // normally there will be just one unless the bitcode file was created 7878 // by binary concatenation. 7879 if (!F.Symtab.empty() && F.StrtabForSymtab.empty()) 7880 F.StrtabForSymtab = *Strtab; 7881 continue; 7882 } 7883 7884 if (Entry.ID == bitc::SYMTAB_BLOCK_ID) { 7885 Expected<StringRef> SymtabOrErr = 7886 readBlobInRecord(Stream, bitc::SYMTAB_BLOCK_ID, bitc::SYMTAB_BLOB); 7887 if (!SymtabOrErr) 7888 return SymtabOrErr.takeError(); 7889 7890 // We can expect the bitcode file to have multiple symbol tables if it 7891 // was created by binary concatenation. In that case we silently 7892 // ignore any subsequent symbol tables, which is fine because this is a 7893 // low level function. The client is expected to notice that the number 7894 // of modules in the symbol table does not match the number of modules 7895 // in the input file and regenerate the symbol table. 7896 if (F.Symtab.empty()) 7897 F.Symtab = *SymtabOrErr; 7898 continue; 7899 } 7900 7901 if (Error Err = Stream.SkipBlock()) 7902 return std::move(Err); 7903 continue; 7904 } 7905 case BitstreamEntry::Record: 7906 if (Error E = Stream.skipRecord(Entry.ID).takeError()) 7907 return std::move(E); 7908 continue; 7909 } 7910 } 7911 } 7912 7913 /// Get a lazy one-at-time loading module from bitcode. 7914 /// 7915 /// This isn't always used in a lazy context. In particular, it's also used by 7916 /// \a parseModule(). If this is truly lazy, then we need to eagerly pull 7917 /// in forward-referenced functions from block address references. 7918 /// 7919 /// \param[in] MaterializeAll Set to \c true if we should materialize 7920 /// everything. 7921 Expected<std::unique_ptr<Module>> 7922 BitcodeModule::getModuleImpl(LLVMContext &Context, bool MaterializeAll, 7923 bool ShouldLazyLoadMetadata, bool IsImporting, 7924 ParserCallbacks Callbacks) { 7925 BitstreamCursor Stream(Buffer); 7926 7927 std::string ProducerIdentification; 7928 if (IdentificationBit != -1ull) { 7929 if (Error JumpFailed = Stream.JumpToBit(IdentificationBit)) 7930 return std::move(JumpFailed); 7931 if (Error E = 7932 readIdentificationBlock(Stream).moveInto(ProducerIdentification)) 7933 return std::move(E); 7934 } 7935 7936 if (Error JumpFailed = Stream.JumpToBit(ModuleBit)) 7937 return std::move(JumpFailed); 7938 auto *R = new BitcodeReader(std::move(Stream), Strtab, ProducerIdentification, 7939 Context); 7940 7941 std::unique_ptr<Module> M = 7942 std::make_unique<Module>(ModuleIdentifier, Context); 7943 M->setMaterializer(R); 7944 7945 // Delay parsing Metadata if ShouldLazyLoadMetadata is true. 7946 if (Error Err = R->parseBitcodeInto(M.get(), ShouldLazyLoadMetadata, 7947 IsImporting, Callbacks)) 7948 return std::move(Err); 7949 7950 if (MaterializeAll) { 7951 // Read in the entire module, and destroy the BitcodeReader. 7952 if (Error Err = M->materializeAll()) 7953 return std::move(Err); 7954 } else { 7955 // Resolve forward references from blockaddresses. 7956 if (Error Err = R->materializeForwardReferencedFunctions()) 7957 return std::move(Err); 7958 } 7959 return std::move(M); 7960 } 7961 7962 Expected<std::unique_ptr<Module>> 7963 BitcodeModule::getLazyModule(LLVMContext &Context, bool ShouldLazyLoadMetadata, 7964 bool IsImporting, ParserCallbacks Callbacks) { 7965 return getModuleImpl(Context, false, ShouldLazyLoadMetadata, IsImporting, 7966 Callbacks); 7967 } 7968 7969 // Parse the specified bitcode buffer and merge the index into CombinedIndex. 7970 // We don't use ModuleIdentifier here because the client may need to control the 7971 // module path used in the combined summary (e.g. when reading summaries for 7972 // regular LTO modules). 7973 Error BitcodeModule::readSummary( 7974 ModuleSummaryIndex &CombinedIndex, StringRef ModulePath, 7975 std::function<bool(GlobalValue::GUID)> IsPrevailing) { 7976 BitstreamCursor Stream(Buffer); 7977 if (Error JumpFailed = Stream.JumpToBit(ModuleBit)) 7978 return JumpFailed; 7979 7980 ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, CombinedIndex, 7981 ModulePath, IsPrevailing); 7982 return R.parseModule(); 7983 } 7984 7985 // Parse the specified bitcode buffer, returning the function info index. 7986 Expected<std::unique_ptr<ModuleSummaryIndex>> BitcodeModule::getSummary() { 7987 BitstreamCursor Stream(Buffer); 7988 if (Error JumpFailed = Stream.JumpToBit(ModuleBit)) 7989 return std::move(JumpFailed); 7990 7991 auto Index = std::make_unique<ModuleSummaryIndex>(/*HaveGVs=*/false); 7992 ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, *Index, 7993 ModuleIdentifier, 0); 7994 7995 if (Error Err = R.parseModule()) 7996 return std::move(Err); 7997 7998 return std::move(Index); 7999 } 8000 8001 static Expected<std::pair<bool, bool>> 8002 getEnableSplitLTOUnitAndUnifiedFlag(BitstreamCursor &Stream, 8003 unsigned ID, 8004 BitcodeLTOInfo <OInfo) { 8005 if (Error Err = Stream.EnterSubBlock(ID)) 8006 return std::move(Err); 8007 SmallVector<uint64_t, 64> Record; 8008 8009 while (true) { 8010 BitstreamEntry Entry; 8011 std::pair<bool, bool> Result = {false,false}; 8012 if (Error E = Stream.advanceSkippingSubblocks().moveInto(Entry)) 8013 return std::move(E); 8014 8015 switch (Entry.Kind) { 8016 case BitstreamEntry::SubBlock: // Handled for us already. 8017 case BitstreamEntry::Error: 8018 return error("Malformed block"); 8019 case BitstreamEntry::EndBlock: { 8020 // If no flags record found, set both flags to false. 8021 return Result; 8022 } 8023 case BitstreamEntry::Record: 8024 // The interesting case. 8025 break; 8026 } 8027 8028 // Look for the FS_FLAGS record. 8029 Record.clear(); 8030 Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record); 8031 if (!MaybeBitCode) 8032 return MaybeBitCode.takeError(); 8033 switch (MaybeBitCode.get()) { 8034 default: // Default behavior: ignore. 8035 break; 8036 case bitc::FS_FLAGS: { // [flags] 8037 uint64_t Flags = Record[0]; 8038 // Scan flags. 8039 assert(Flags <= 0x2ff && "Unexpected bits in flag"); 8040 8041 bool EnableSplitLTOUnit = Flags & 0x8; 8042 bool UnifiedLTO = Flags & 0x200; 8043 Result = {EnableSplitLTOUnit, UnifiedLTO}; 8044 8045 return Result; 8046 } 8047 } 8048 } 8049 llvm_unreachable("Exit infinite loop"); 8050 } 8051 8052 // Check if the given bitcode buffer contains a global value summary block. 8053 Expected<BitcodeLTOInfo> BitcodeModule::getLTOInfo() { 8054 BitstreamCursor Stream(Buffer); 8055 if (Error JumpFailed = Stream.JumpToBit(ModuleBit)) 8056 return std::move(JumpFailed); 8057 8058 if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID)) 8059 return std::move(Err); 8060 8061 while (true) { 8062 llvm::BitstreamEntry Entry; 8063 if (Error E = Stream.advance().moveInto(Entry)) 8064 return std::move(E); 8065 8066 switch (Entry.Kind) { 8067 case BitstreamEntry::Error: 8068 return error("Malformed block"); 8069 case BitstreamEntry::EndBlock: 8070 return BitcodeLTOInfo{/*IsThinLTO=*/false, /*HasSummary=*/false, 8071 /*EnableSplitLTOUnit=*/false, /*UnifiedLTO=*/false}; 8072 8073 case BitstreamEntry::SubBlock: 8074 if (Entry.ID == bitc::GLOBALVAL_SUMMARY_BLOCK_ID) { 8075 BitcodeLTOInfo LTOInfo; 8076 Expected<std::pair<bool, bool>> Flags = 8077 getEnableSplitLTOUnitAndUnifiedFlag(Stream, Entry.ID, LTOInfo); 8078 if (!Flags) 8079 return Flags.takeError(); 8080 std::tie(LTOInfo.EnableSplitLTOUnit, LTOInfo.UnifiedLTO) = Flags.get(); 8081 LTOInfo.IsThinLTO = true; 8082 LTOInfo.HasSummary = true; 8083 return LTOInfo; 8084 } 8085 8086 if (Entry.ID == bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID) { 8087 BitcodeLTOInfo LTOInfo; 8088 Expected<std::pair<bool, bool>> Flags = 8089 getEnableSplitLTOUnitAndUnifiedFlag(Stream, Entry.ID, LTOInfo); 8090 if (!Flags) 8091 return Flags.takeError(); 8092 std::tie(LTOInfo.EnableSplitLTOUnit, LTOInfo.UnifiedLTO) = Flags.get(); 8093 LTOInfo.IsThinLTO = false; 8094 LTOInfo.HasSummary = true; 8095 return LTOInfo; 8096 } 8097 8098 // Ignore other sub-blocks. 8099 if (Error Err = Stream.SkipBlock()) 8100 return std::move(Err); 8101 continue; 8102 8103 case BitstreamEntry::Record: 8104 if (Expected<unsigned> StreamFailed = Stream.skipRecord(Entry.ID)) 8105 continue; 8106 else 8107 return StreamFailed.takeError(); 8108 } 8109 } 8110 } 8111 8112 static Expected<BitcodeModule> getSingleModule(MemoryBufferRef Buffer) { 8113 Expected<std::vector<BitcodeModule>> MsOrErr = getBitcodeModuleList(Buffer); 8114 if (!MsOrErr) 8115 return MsOrErr.takeError(); 8116 8117 if (MsOrErr->size() != 1) 8118 return error("Expected a single module"); 8119 8120 return (*MsOrErr)[0]; 8121 } 8122 8123 Expected<std::unique_ptr<Module>> 8124 llvm::getLazyBitcodeModule(MemoryBufferRef Buffer, LLVMContext &Context, 8125 bool ShouldLazyLoadMetadata, bool IsImporting, 8126 ParserCallbacks Callbacks) { 8127 Expected<BitcodeModule> BM = getSingleModule(Buffer); 8128 if (!BM) 8129 return BM.takeError(); 8130 8131 return BM->getLazyModule(Context, ShouldLazyLoadMetadata, IsImporting, 8132 Callbacks); 8133 } 8134 8135 Expected<std::unique_ptr<Module>> llvm::getOwningLazyBitcodeModule( 8136 std::unique_ptr<MemoryBuffer> &&Buffer, LLVMContext &Context, 8137 bool ShouldLazyLoadMetadata, bool IsImporting, ParserCallbacks Callbacks) { 8138 auto MOrErr = getLazyBitcodeModule(*Buffer, Context, ShouldLazyLoadMetadata, 8139 IsImporting, Callbacks); 8140 if (MOrErr) 8141 (*MOrErr)->setOwnedMemoryBuffer(std::move(Buffer)); 8142 return MOrErr; 8143 } 8144 8145 Expected<std::unique_ptr<Module>> 8146 BitcodeModule::parseModule(LLVMContext &Context, ParserCallbacks Callbacks) { 8147 return getModuleImpl(Context, true, false, false, Callbacks); 8148 // TODO: Restore the use-lists to the in-memory state when the bitcode was 8149 // written. We must defer until the Module has been fully materialized. 8150 } 8151 8152 Expected<std::unique_ptr<Module>> 8153 llvm::parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context, 8154 ParserCallbacks Callbacks) { 8155 Expected<BitcodeModule> BM = getSingleModule(Buffer); 8156 if (!BM) 8157 return BM.takeError(); 8158 8159 return BM->parseModule(Context, Callbacks); 8160 } 8161 8162 Expected<std::string> llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer) { 8163 Expected<BitstreamCursor> StreamOrErr = initStream(Buffer); 8164 if (!StreamOrErr) 8165 return StreamOrErr.takeError(); 8166 8167 return readTriple(*StreamOrErr); 8168 } 8169 8170 Expected<bool> llvm::isBitcodeContainingObjCCategory(MemoryBufferRef Buffer) { 8171 Expected<BitstreamCursor> StreamOrErr = initStream(Buffer); 8172 if (!StreamOrErr) 8173 return StreamOrErr.takeError(); 8174 8175 return hasObjCCategory(*StreamOrErr); 8176 } 8177 8178 Expected<std::string> llvm::getBitcodeProducerString(MemoryBufferRef Buffer) { 8179 Expected<BitstreamCursor> StreamOrErr = initStream(Buffer); 8180 if (!StreamOrErr) 8181 return StreamOrErr.takeError(); 8182 8183 return readIdentificationCode(*StreamOrErr); 8184 } 8185 8186 Error llvm::readModuleSummaryIndex(MemoryBufferRef Buffer, 8187 ModuleSummaryIndex &CombinedIndex) { 8188 Expected<BitcodeModule> BM = getSingleModule(Buffer); 8189 if (!BM) 8190 return BM.takeError(); 8191 8192 return BM->readSummary(CombinedIndex, BM->getModuleIdentifier()); 8193 } 8194 8195 Expected<std::unique_ptr<ModuleSummaryIndex>> 8196 llvm::getModuleSummaryIndex(MemoryBufferRef Buffer) { 8197 Expected<BitcodeModule> BM = getSingleModule(Buffer); 8198 if (!BM) 8199 return BM.takeError(); 8200 8201 return BM->getSummary(); 8202 } 8203 8204 Expected<BitcodeLTOInfo> llvm::getBitcodeLTOInfo(MemoryBufferRef Buffer) { 8205 Expected<BitcodeModule> BM = getSingleModule(Buffer); 8206 if (!BM) 8207 return BM.takeError(); 8208 8209 return BM->getLTOInfo(); 8210 } 8211 8212 Expected<std::unique_ptr<ModuleSummaryIndex>> 8213 llvm::getModuleSummaryIndexForFile(StringRef Path, 8214 bool IgnoreEmptyThinLTOIndexFile) { 8215 ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr = 8216 MemoryBuffer::getFileOrSTDIN(Path); 8217 if (!FileOrErr) 8218 return errorCodeToError(FileOrErr.getError()); 8219 if (IgnoreEmptyThinLTOIndexFile && !(*FileOrErr)->getBufferSize()) 8220 return nullptr; 8221 return getModuleSummaryIndex(**FileOrErr); 8222 } 8223