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+2 != Record.size()) 4881 return error("Invalid record"); 4882 4883 ResTypeID = Record[OpNum]; 4884 Type *ResTy = getTypeByID(ResTypeID); 4885 int Opc = getDecodedCastOpcode(Record[OpNum + 1]); 4886 if (Opc == -1 || !ResTy) 4887 return error("Invalid record"); 4888 Instruction *Temp = nullptr; 4889 if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) { 4890 if (Temp) { 4891 InstructionList.push_back(Temp); 4892 assert(CurBB && "No current BB?"); 4893 Temp->insertInto(CurBB, CurBB->end()); 4894 } 4895 } else { 4896 auto CastOp = (Instruction::CastOps)Opc; 4897 if (!CastInst::castIsValid(CastOp, Op, ResTy)) 4898 return error("Invalid cast"); 4899 I = CastInst::Create(CastOp, Op, ResTy); 4900 } 4901 InstructionList.push_back(I); 4902 break; 4903 } 4904 case bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD: 4905 case bitc::FUNC_CODE_INST_GEP_OLD: 4906 case bitc::FUNC_CODE_INST_GEP: { // GEP: type, [n x operands] 4907 unsigned OpNum = 0; 4908 4909 unsigned TyID; 4910 Type *Ty; 4911 bool InBounds; 4912 4913 if (BitCode == bitc::FUNC_CODE_INST_GEP) { 4914 InBounds = Record[OpNum++]; 4915 TyID = Record[OpNum++]; 4916 Ty = getTypeByID(TyID); 4917 } else { 4918 InBounds = BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD; 4919 TyID = InvalidTypeID; 4920 Ty = nullptr; 4921 } 4922 4923 Value *BasePtr; 4924 unsigned BasePtrTypeID; 4925 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr, BasePtrTypeID, 4926 CurBB)) 4927 return error("Invalid record"); 4928 4929 if (!Ty) { 4930 TyID = getContainedTypeID(BasePtrTypeID); 4931 if (BasePtr->getType()->isVectorTy()) 4932 TyID = getContainedTypeID(TyID); 4933 Ty = getTypeByID(TyID); 4934 } 4935 4936 SmallVector<Value*, 16> GEPIdx; 4937 while (OpNum != Record.size()) { 4938 Value *Op; 4939 unsigned OpTypeID; 4940 if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB)) 4941 return error("Invalid record"); 4942 GEPIdx.push_back(Op); 4943 } 4944 4945 I = GetElementPtrInst::Create(Ty, BasePtr, GEPIdx); 4946 4947 ResTypeID = TyID; 4948 if (cast<GEPOperator>(I)->getNumIndices() != 0) { 4949 auto GTI = std::next(gep_type_begin(I)); 4950 for (Value *Idx : drop_begin(cast<GEPOperator>(I)->indices())) { 4951 unsigned SubType = 0; 4952 if (GTI.isStruct()) { 4953 ConstantInt *IdxC = 4954 Idx->getType()->isVectorTy() 4955 ? cast<ConstantInt>(cast<Constant>(Idx)->getSplatValue()) 4956 : cast<ConstantInt>(Idx); 4957 SubType = IdxC->getZExtValue(); 4958 } 4959 ResTypeID = getContainedTypeID(ResTypeID, SubType); 4960 ++GTI; 4961 } 4962 } 4963 4964 // At this point ResTypeID is the result element type. We need a pointer 4965 // or vector of pointer to it. 4966 ResTypeID = getVirtualTypeID(I->getType()->getScalarType(), ResTypeID); 4967 if (I->getType()->isVectorTy()) 4968 ResTypeID = getVirtualTypeID(I->getType(), ResTypeID); 4969 4970 InstructionList.push_back(I); 4971 if (InBounds) 4972 cast<GetElementPtrInst>(I)->setIsInBounds(true); 4973 break; 4974 } 4975 4976 case bitc::FUNC_CODE_INST_EXTRACTVAL: { 4977 // EXTRACTVAL: [opty, opval, n x indices] 4978 unsigned OpNum = 0; 4979 Value *Agg; 4980 unsigned AggTypeID; 4981 if (getValueTypePair(Record, OpNum, NextValueNo, Agg, AggTypeID, CurBB)) 4982 return error("Invalid record"); 4983 Type *Ty = Agg->getType(); 4984 4985 unsigned RecSize = Record.size(); 4986 if (OpNum == RecSize) 4987 return error("EXTRACTVAL: Invalid instruction with 0 indices"); 4988 4989 SmallVector<unsigned, 4> EXTRACTVALIdx; 4990 ResTypeID = AggTypeID; 4991 for (; OpNum != RecSize; ++OpNum) { 4992 bool IsArray = Ty->isArrayTy(); 4993 bool IsStruct = Ty->isStructTy(); 4994 uint64_t Index = Record[OpNum]; 4995 4996 if (!IsStruct && !IsArray) 4997 return error("EXTRACTVAL: Invalid type"); 4998 if ((unsigned)Index != Index) 4999 return error("Invalid value"); 5000 if (IsStruct && Index >= Ty->getStructNumElements()) 5001 return error("EXTRACTVAL: Invalid struct index"); 5002 if (IsArray && Index >= Ty->getArrayNumElements()) 5003 return error("EXTRACTVAL: Invalid array index"); 5004 EXTRACTVALIdx.push_back((unsigned)Index); 5005 5006 if (IsStruct) { 5007 Ty = Ty->getStructElementType(Index); 5008 ResTypeID = getContainedTypeID(ResTypeID, Index); 5009 } else { 5010 Ty = Ty->getArrayElementType(); 5011 ResTypeID = getContainedTypeID(ResTypeID); 5012 } 5013 } 5014 5015 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx); 5016 InstructionList.push_back(I); 5017 break; 5018 } 5019 5020 case bitc::FUNC_CODE_INST_INSERTVAL: { 5021 // INSERTVAL: [opty, opval, opty, opval, n x indices] 5022 unsigned OpNum = 0; 5023 Value *Agg; 5024 unsigned AggTypeID; 5025 if (getValueTypePair(Record, OpNum, NextValueNo, Agg, AggTypeID, CurBB)) 5026 return error("Invalid record"); 5027 Value *Val; 5028 unsigned ValTypeID; 5029 if (getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID, CurBB)) 5030 return error("Invalid record"); 5031 5032 unsigned RecSize = Record.size(); 5033 if (OpNum == RecSize) 5034 return error("INSERTVAL: Invalid instruction with 0 indices"); 5035 5036 SmallVector<unsigned, 4> INSERTVALIdx; 5037 Type *CurTy = Agg->getType(); 5038 for (; OpNum != RecSize; ++OpNum) { 5039 bool IsArray = CurTy->isArrayTy(); 5040 bool IsStruct = CurTy->isStructTy(); 5041 uint64_t Index = Record[OpNum]; 5042 5043 if (!IsStruct && !IsArray) 5044 return error("INSERTVAL: Invalid type"); 5045 if ((unsigned)Index != Index) 5046 return error("Invalid value"); 5047 if (IsStruct && Index >= CurTy->getStructNumElements()) 5048 return error("INSERTVAL: Invalid struct index"); 5049 if (IsArray && Index >= CurTy->getArrayNumElements()) 5050 return error("INSERTVAL: Invalid array index"); 5051 5052 INSERTVALIdx.push_back((unsigned)Index); 5053 if (IsStruct) 5054 CurTy = CurTy->getStructElementType(Index); 5055 else 5056 CurTy = CurTy->getArrayElementType(); 5057 } 5058 5059 if (CurTy != Val->getType()) 5060 return error("Inserted value type doesn't match aggregate type"); 5061 5062 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx); 5063 ResTypeID = AggTypeID; 5064 InstructionList.push_back(I); 5065 break; 5066 } 5067 5068 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval] 5069 // obsolete form of select 5070 // handles select i1 ... in old bitcode 5071 unsigned OpNum = 0; 5072 Value *TrueVal, *FalseVal, *Cond; 5073 unsigned TypeID; 5074 Type *CondType = Type::getInt1Ty(Context); 5075 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal, TypeID, 5076 CurBB) || 5077 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), TypeID, 5078 FalseVal, CurBB) || 5079 popValue(Record, OpNum, NextValueNo, CondType, 5080 getVirtualTypeID(CondType), Cond, CurBB)) 5081 return error("Invalid record"); 5082 5083 I = SelectInst::Create(Cond, TrueVal, FalseVal); 5084 ResTypeID = TypeID; 5085 InstructionList.push_back(I); 5086 break; 5087 } 5088 5089 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred] 5090 // new form of select 5091 // handles select i1 or select [N x i1] 5092 unsigned OpNum = 0; 5093 Value *TrueVal, *FalseVal, *Cond; 5094 unsigned ValTypeID, CondTypeID; 5095 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal, ValTypeID, 5096 CurBB) || 5097 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), ValTypeID, 5098 FalseVal, CurBB) || 5099 getValueTypePair(Record, OpNum, NextValueNo, Cond, CondTypeID, CurBB)) 5100 return error("Invalid record"); 5101 5102 // select condition can be either i1 or [N x i1] 5103 if (VectorType* vector_type = 5104 dyn_cast<VectorType>(Cond->getType())) { 5105 // expect <n x i1> 5106 if (vector_type->getElementType() != Type::getInt1Ty(Context)) 5107 return error("Invalid type for value"); 5108 } else { 5109 // expect i1 5110 if (Cond->getType() != Type::getInt1Ty(Context)) 5111 return error("Invalid type for value"); 5112 } 5113 5114 I = SelectInst::Create(Cond, TrueVal, FalseVal); 5115 ResTypeID = ValTypeID; 5116 InstructionList.push_back(I); 5117 if (OpNum < Record.size() && isa<FPMathOperator>(I)) { 5118 FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]); 5119 if (FMF.any()) 5120 I->setFastMathFlags(FMF); 5121 } 5122 break; 5123 } 5124 5125 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval] 5126 unsigned OpNum = 0; 5127 Value *Vec, *Idx; 5128 unsigned VecTypeID, IdxTypeID; 5129 if (getValueTypePair(Record, OpNum, NextValueNo, Vec, VecTypeID, CurBB) || 5130 getValueTypePair(Record, OpNum, NextValueNo, Idx, IdxTypeID, CurBB)) 5131 return error("Invalid record"); 5132 if (!Vec->getType()->isVectorTy()) 5133 return error("Invalid type for value"); 5134 I = ExtractElementInst::Create(Vec, Idx); 5135 ResTypeID = getContainedTypeID(VecTypeID); 5136 InstructionList.push_back(I); 5137 break; 5138 } 5139 5140 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval] 5141 unsigned OpNum = 0; 5142 Value *Vec, *Elt, *Idx; 5143 unsigned VecTypeID, IdxTypeID; 5144 if (getValueTypePair(Record, OpNum, NextValueNo, Vec, VecTypeID, CurBB)) 5145 return error("Invalid record"); 5146 if (!Vec->getType()->isVectorTy()) 5147 return error("Invalid type for value"); 5148 if (popValue(Record, OpNum, NextValueNo, 5149 cast<VectorType>(Vec->getType())->getElementType(), 5150 getContainedTypeID(VecTypeID), Elt, CurBB) || 5151 getValueTypePair(Record, OpNum, NextValueNo, Idx, IdxTypeID, CurBB)) 5152 return error("Invalid record"); 5153 I = InsertElementInst::Create(Vec, Elt, Idx); 5154 ResTypeID = VecTypeID; 5155 InstructionList.push_back(I); 5156 break; 5157 } 5158 5159 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval] 5160 unsigned OpNum = 0; 5161 Value *Vec1, *Vec2, *Mask; 5162 unsigned Vec1TypeID; 5163 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1, Vec1TypeID, 5164 CurBB) || 5165 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec1TypeID, 5166 Vec2, CurBB)) 5167 return error("Invalid record"); 5168 5169 unsigned MaskTypeID; 5170 if (getValueTypePair(Record, OpNum, NextValueNo, Mask, MaskTypeID, CurBB)) 5171 return error("Invalid record"); 5172 if (!Vec1->getType()->isVectorTy() || !Vec2->getType()->isVectorTy()) 5173 return error("Invalid type for value"); 5174 5175 I = new ShuffleVectorInst(Vec1, Vec2, Mask); 5176 ResTypeID = 5177 getVirtualTypeID(I->getType(), getContainedTypeID(Vec1TypeID)); 5178 InstructionList.push_back(I); 5179 break; 5180 } 5181 5182 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred] 5183 // Old form of ICmp/FCmp returning bool 5184 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were 5185 // both legal on vectors but had different behaviour. 5186 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred] 5187 // FCmp/ICmp returning bool or vector of bool 5188 5189 unsigned OpNum = 0; 5190 Value *LHS, *RHS; 5191 unsigned LHSTypeID; 5192 if (getValueTypePair(Record, OpNum, NextValueNo, LHS, LHSTypeID, CurBB) || 5193 popValue(Record, OpNum, NextValueNo, LHS->getType(), LHSTypeID, RHS, 5194 CurBB)) 5195 return error("Invalid record"); 5196 5197 if (OpNum >= Record.size()) 5198 return error( 5199 "Invalid record: operand number exceeded available operands"); 5200 5201 unsigned PredVal = Record[OpNum]; 5202 bool IsFP = LHS->getType()->isFPOrFPVectorTy(); 5203 FastMathFlags FMF; 5204 if (IsFP && Record.size() > OpNum+1) 5205 FMF = getDecodedFastMathFlags(Record[++OpNum]); 5206 5207 if (OpNum+1 != Record.size()) 5208 return error("Invalid record"); 5209 5210 if (LHS->getType()->isFPOrFPVectorTy()) 5211 I = new FCmpInst((FCmpInst::Predicate)PredVal, LHS, RHS); 5212 else 5213 I = new ICmpInst((ICmpInst::Predicate)PredVal, LHS, RHS); 5214 5215 ResTypeID = getVirtualTypeID(I->getType()->getScalarType()); 5216 if (LHS->getType()->isVectorTy()) 5217 ResTypeID = getVirtualTypeID(I->getType(), ResTypeID); 5218 5219 if (FMF.any()) 5220 I->setFastMathFlags(FMF); 5221 InstructionList.push_back(I); 5222 break; 5223 } 5224 5225 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>] 5226 { 5227 unsigned Size = Record.size(); 5228 if (Size == 0) { 5229 I = ReturnInst::Create(Context); 5230 InstructionList.push_back(I); 5231 break; 5232 } 5233 5234 unsigned OpNum = 0; 5235 Value *Op = nullptr; 5236 unsigned OpTypeID; 5237 if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB)) 5238 return error("Invalid record"); 5239 if (OpNum != Record.size()) 5240 return error("Invalid record"); 5241 5242 I = ReturnInst::Create(Context, Op); 5243 InstructionList.push_back(I); 5244 break; 5245 } 5246 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#] 5247 if (Record.size() != 1 && Record.size() != 3) 5248 return error("Invalid record"); 5249 BasicBlock *TrueDest = getBasicBlock(Record[0]); 5250 if (!TrueDest) 5251 return error("Invalid record"); 5252 5253 if (Record.size() == 1) { 5254 I = BranchInst::Create(TrueDest); 5255 InstructionList.push_back(I); 5256 } 5257 else { 5258 BasicBlock *FalseDest = getBasicBlock(Record[1]); 5259 Type *CondType = Type::getInt1Ty(Context); 5260 Value *Cond = getValue(Record, 2, NextValueNo, CondType, 5261 getVirtualTypeID(CondType), CurBB); 5262 if (!FalseDest || !Cond) 5263 return error("Invalid record"); 5264 I = BranchInst::Create(TrueDest, FalseDest, Cond); 5265 InstructionList.push_back(I); 5266 } 5267 break; 5268 } 5269 case bitc::FUNC_CODE_INST_CLEANUPRET: { // CLEANUPRET: [val] or [val,bb#] 5270 if (Record.size() != 1 && Record.size() != 2) 5271 return error("Invalid record"); 5272 unsigned Idx = 0; 5273 Type *TokenTy = Type::getTokenTy(Context); 5274 Value *CleanupPad = getValue(Record, Idx++, NextValueNo, TokenTy, 5275 getVirtualTypeID(TokenTy), CurBB); 5276 if (!CleanupPad) 5277 return error("Invalid record"); 5278 BasicBlock *UnwindDest = nullptr; 5279 if (Record.size() == 2) { 5280 UnwindDest = getBasicBlock(Record[Idx++]); 5281 if (!UnwindDest) 5282 return error("Invalid record"); 5283 } 5284 5285 I = CleanupReturnInst::Create(CleanupPad, UnwindDest); 5286 InstructionList.push_back(I); 5287 break; 5288 } 5289 case bitc::FUNC_CODE_INST_CATCHRET: { // CATCHRET: [val,bb#] 5290 if (Record.size() != 2) 5291 return error("Invalid record"); 5292 unsigned Idx = 0; 5293 Type *TokenTy = Type::getTokenTy(Context); 5294 Value *CatchPad = getValue(Record, Idx++, NextValueNo, TokenTy, 5295 getVirtualTypeID(TokenTy), CurBB); 5296 if (!CatchPad) 5297 return error("Invalid record"); 5298 BasicBlock *BB = getBasicBlock(Record[Idx++]); 5299 if (!BB) 5300 return error("Invalid record"); 5301 5302 I = CatchReturnInst::Create(CatchPad, BB); 5303 InstructionList.push_back(I); 5304 break; 5305 } 5306 case bitc::FUNC_CODE_INST_CATCHSWITCH: { // CATCHSWITCH: [tok,num,(bb)*,bb?] 5307 // We must have, at minimum, the outer scope and the number of arguments. 5308 if (Record.size() < 2) 5309 return error("Invalid record"); 5310 5311 unsigned Idx = 0; 5312 5313 Type *TokenTy = Type::getTokenTy(Context); 5314 Value *ParentPad = getValue(Record, Idx++, NextValueNo, TokenTy, 5315 getVirtualTypeID(TokenTy), CurBB); 5316 5317 unsigned NumHandlers = Record[Idx++]; 5318 5319 SmallVector<BasicBlock *, 2> Handlers; 5320 for (unsigned Op = 0; Op != NumHandlers; ++Op) { 5321 BasicBlock *BB = getBasicBlock(Record[Idx++]); 5322 if (!BB) 5323 return error("Invalid record"); 5324 Handlers.push_back(BB); 5325 } 5326 5327 BasicBlock *UnwindDest = nullptr; 5328 if (Idx + 1 == Record.size()) { 5329 UnwindDest = getBasicBlock(Record[Idx++]); 5330 if (!UnwindDest) 5331 return error("Invalid record"); 5332 } 5333 5334 if (Record.size() != Idx) 5335 return error("Invalid record"); 5336 5337 auto *CatchSwitch = 5338 CatchSwitchInst::Create(ParentPad, UnwindDest, NumHandlers); 5339 for (BasicBlock *Handler : Handlers) 5340 CatchSwitch->addHandler(Handler); 5341 I = CatchSwitch; 5342 ResTypeID = getVirtualTypeID(I->getType()); 5343 InstructionList.push_back(I); 5344 break; 5345 } 5346 case bitc::FUNC_CODE_INST_CATCHPAD: 5347 case bitc::FUNC_CODE_INST_CLEANUPPAD: { // [tok,num,(ty,val)*] 5348 // We must have, at minimum, the outer scope and the number of arguments. 5349 if (Record.size() < 2) 5350 return error("Invalid record"); 5351 5352 unsigned Idx = 0; 5353 5354 Type *TokenTy = Type::getTokenTy(Context); 5355 Value *ParentPad = getValue(Record, Idx++, NextValueNo, TokenTy, 5356 getVirtualTypeID(TokenTy), CurBB); 5357 5358 unsigned NumArgOperands = Record[Idx++]; 5359 5360 SmallVector<Value *, 2> Args; 5361 for (unsigned Op = 0; Op != NumArgOperands; ++Op) { 5362 Value *Val; 5363 unsigned ValTypeID; 5364 if (getValueTypePair(Record, Idx, NextValueNo, Val, ValTypeID, nullptr)) 5365 return error("Invalid record"); 5366 Args.push_back(Val); 5367 } 5368 5369 if (Record.size() != Idx) 5370 return error("Invalid record"); 5371 5372 if (BitCode == bitc::FUNC_CODE_INST_CLEANUPPAD) 5373 I = CleanupPadInst::Create(ParentPad, Args); 5374 else 5375 I = CatchPadInst::Create(ParentPad, Args); 5376 ResTypeID = getVirtualTypeID(I->getType()); 5377 InstructionList.push_back(I); 5378 break; 5379 } 5380 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...] 5381 // Check magic 5382 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) { 5383 // "New" SwitchInst format with case ranges. The changes to write this 5384 // format were reverted but we still recognize bitcode that uses it. 5385 // Hopefully someday we will have support for case ranges and can use 5386 // this format again. 5387 5388 unsigned OpTyID = Record[1]; 5389 Type *OpTy = getTypeByID(OpTyID); 5390 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth(); 5391 5392 Value *Cond = getValue(Record, 2, NextValueNo, OpTy, OpTyID, CurBB); 5393 BasicBlock *Default = getBasicBlock(Record[3]); 5394 if (!OpTy || !Cond || !Default) 5395 return error("Invalid record"); 5396 5397 unsigned NumCases = Record[4]; 5398 5399 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases); 5400 InstructionList.push_back(SI); 5401 5402 unsigned CurIdx = 5; 5403 for (unsigned i = 0; i != NumCases; ++i) { 5404 SmallVector<ConstantInt*, 1> CaseVals; 5405 unsigned NumItems = Record[CurIdx++]; 5406 for (unsigned ci = 0; ci != NumItems; ++ci) { 5407 bool isSingleNumber = Record[CurIdx++]; 5408 5409 APInt Low; 5410 unsigned ActiveWords = 1; 5411 if (ValueBitWidth > 64) 5412 ActiveWords = Record[CurIdx++]; 5413 Low = readWideAPInt(ArrayRef(&Record[CurIdx], ActiveWords), 5414 ValueBitWidth); 5415 CurIdx += ActiveWords; 5416 5417 if (!isSingleNumber) { 5418 ActiveWords = 1; 5419 if (ValueBitWidth > 64) 5420 ActiveWords = Record[CurIdx++]; 5421 APInt High = readWideAPInt(ArrayRef(&Record[CurIdx], ActiveWords), 5422 ValueBitWidth); 5423 CurIdx += ActiveWords; 5424 5425 // FIXME: It is not clear whether values in the range should be 5426 // compared as signed or unsigned values. The partially 5427 // implemented changes that used this format in the past used 5428 // unsigned comparisons. 5429 for ( ; Low.ule(High); ++Low) 5430 CaseVals.push_back(ConstantInt::get(Context, Low)); 5431 } else 5432 CaseVals.push_back(ConstantInt::get(Context, Low)); 5433 } 5434 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]); 5435 for (ConstantInt *Cst : CaseVals) 5436 SI->addCase(Cst, DestBB); 5437 } 5438 I = SI; 5439 break; 5440 } 5441 5442 // Old SwitchInst format without case ranges. 5443 5444 if (Record.size() < 3 || (Record.size() & 1) == 0) 5445 return error("Invalid record"); 5446 unsigned OpTyID = Record[0]; 5447 Type *OpTy = getTypeByID(OpTyID); 5448 Value *Cond = getValue(Record, 1, NextValueNo, OpTy, OpTyID, CurBB); 5449 BasicBlock *Default = getBasicBlock(Record[2]); 5450 if (!OpTy || !Cond || !Default) 5451 return error("Invalid record"); 5452 unsigned NumCases = (Record.size()-3)/2; 5453 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases); 5454 InstructionList.push_back(SI); 5455 for (unsigned i = 0, e = NumCases; i != e; ++i) { 5456 ConstantInt *CaseVal = dyn_cast_or_null<ConstantInt>( 5457 getFnValueByID(Record[3+i*2], OpTy, OpTyID, nullptr)); 5458 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]); 5459 if (!CaseVal || !DestBB) { 5460 delete SI; 5461 return error("Invalid record"); 5462 } 5463 SI->addCase(CaseVal, DestBB); 5464 } 5465 I = SI; 5466 break; 5467 } 5468 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...] 5469 if (Record.size() < 2) 5470 return error("Invalid record"); 5471 unsigned OpTyID = Record[0]; 5472 Type *OpTy = getTypeByID(OpTyID); 5473 Value *Address = getValue(Record, 1, NextValueNo, OpTy, OpTyID, CurBB); 5474 if (!OpTy || !Address) 5475 return error("Invalid record"); 5476 unsigned NumDests = Record.size()-2; 5477 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests); 5478 InstructionList.push_back(IBI); 5479 for (unsigned i = 0, e = NumDests; i != e; ++i) { 5480 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) { 5481 IBI->addDestination(DestBB); 5482 } else { 5483 delete IBI; 5484 return error("Invalid record"); 5485 } 5486 } 5487 I = IBI; 5488 break; 5489 } 5490 5491 case bitc::FUNC_CODE_INST_INVOKE: { 5492 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...] 5493 if (Record.size() < 4) 5494 return error("Invalid record"); 5495 unsigned OpNum = 0; 5496 AttributeList PAL = getAttributes(Record[OpNum++]); 5497 unsigned CCInfo = Record[OpNum++]; 5498 BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]); 5499 BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]); 5500 5501 unsigned FTyID = InvalidTypeID; 5502 FunctionType *FTy = nullptr; 5503 if ((CCInfo >> 13) & 1) { 5504 FTyID = Record[OpNum++]; 5505 FTy = dyn_cast<FunctionType>(getTypeByID(FTyID)); 5506 if (!FTy) 5507 return error("Explicit invoke type is not a function type"); 5508 } 5509 5510 Value *Callee; 5511 unsigned CalleeTypeID; 5512 if (getValueTypePair(Record, OpNum, NextValueNo, Callee, CalleeTypeID, 5513 CurBB)) 5514 return error("Invalid record"); 5515 5516 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType()); 5517 if (!CalleeTy) 5518 return error("Callee is not a pointer"); 5519 if (!FTy) { 5520 FTyID = getContainedTypeID(CalleeTypeID); 5521 FTy = dyn_cast_or_null<FunctionType>(getTypeByID(FTyID)); 5522 if (!FTy) 5523 return error("Callee is not of pointer to function type"); 5524 } 5525 if (Record.size() < FTy->getNumParams() + OpNum) 5526 return error("Insufficient operands to call"); 5527 5528 SmallVector<Value*, 16> Ops; 5529 SmallVector<unsigned, 16> ArgTyIDs; 5530 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) { 5531 unsigned ArgTyID = getContainedTypeID(FTyID, i + 1); 5532 Ops.push_back(getValue(Record, OpNum, NextValueNo, FTy->getParamType(i), 5533 ArgTyID, CurBB)); 5534 ArgTyIDs.push_back(ArgTyID); 5535 if (!Ops.back()) 5536 return error("Invalid record"); 5537 } 5538 5539 if (!FTy->isVarArg()) { 5540 if (Record.size() != OpNum) 5541 return error("Invalid record"); 5542 } else { 5543 // Read type/value pairs for varargs params. 5544 while (OpNum != Record.size()) { 5545 Value *Op; 5546 unsigned OpTypeID; 5547 if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB)) 5548 return error("Invalid record"); 5549 Ops.push_back(Op); 5550 ArgTyIDs.push_back(OpTypeID); 5551 } 5552 } 5553 5554 // Upgrade the bundles if needed. 5555 if (!OperandBundles.empty()) 5556 UpgradeOperandBundles(OperandBundles); 5557 5558 I = InvokeInst::Create(FTy, Callee, NormalBB, UnwindBB, Ops, 5559 OperandBundles); 5560 ResTypeID = getContainedTypeID(FTyID); 5561 OperandBundles.clear(); 5562 InstructionList.push_back(I); 5563 cast<InvokeInst>(I)->setCallingConv( 5564 static_cast<CallingConv::ID>(CallingConv::MaxID & CCInfo)); 5565 cast<InvokeInst>(I)->setAttributes(PAL); 5566 if (Error Err = propagateAttributeTypes(cast<CallBase>(I), ArgTyIDs)) { 5567 I->deleteValue(); 5568 return Err; 5569 } 5570 5571 break; 5572 } 5573 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval] 5574 unsigned Idx = 0; 5575 Value *Val = nullptr; 5576 unsigned ValTypeID; 5577 if (getValueTypePair(Record, Idx, NextValueNo, Val, ValTypeID, CurBB)) 5578 return error("Invalid record"); 5579 I = ResumeInst::Create(Val); 5580 InstructionList.push_back(I); 5581 break; 5582 } 5583 case bitc::FUNC_CODE_INST_CALLBR: { 5584 // CALLBR: [attr, cc, norm, transfs, fty, fnid, args] 5585 unsigned OpNum = 0; 5586 AttributeList PAL = getAttributes(Record[OpNum++]); 5587 unsigned CCInfo = Record[OpNum++]; 5588 5589 BasicBlock *DefaultDest = getBasicBlock(Record[OpNum++]); 5590 unsigned NumIndirectDests = Record[OpNum++]; 5591 SmallVector<BasicBlock *, 16> IndirectDests; 5592 for (unsigned i = 0, e = NumIndirectDests; i != e; ++i) 5593 IndirectDests.push_back(getBasicBlock(Record[OpNum++])); 5594 5595 unsigned FTyID = InvalidTypeID; 5596 FunctionType *FTy = nullptr; 5597 if ((CCInfo >> bitc::CALL_EXPLICIT_TYPE) & 1) { 5598 FTyID = Record[OpNum++]; 5599 FTy = dyn_cast_or_null<FunctionType>(getTypeByID(FTyID)); 5600 if (!FTy) 5601 return error("Explicit call type is not a function type"); 5602 } 5603 5604 Value *Callee; 5605 unsigned CalleeTypeID; 5606 if (getValueTypePair(Record, OpNum, NextValueNo, Callee, CalleeTypeID, 5607 CurBB)) 5608 return error("Invalid record"); 5609 5610 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType()); 5611 if (!OpTy) 5612 return error("Callee is not a pointer type"); 5613 if (!FTy) { 5614 FTyID = getContainedTypeID(CalleeTypeID); 5615 FTy = dyn_cast_or_null<FunctionType>(getTypeByID(FTyID)); 5616 if (!FTy) 5617 return error("Callee is not of pointer to function type"); 5618 } 5619 if (Record.size() < FTy->getNumParams() + OpNum) 5620 return error("Insufficient operands to call"); 5621 5622 SmallVector<Value*, 16> Args; 5623 SmallVector<unsigned, 16> ArgTyIDs; 5624 // Read the fixed params. 5625 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) { 5626 Value *Arg; 5627 unsigned ArgTyID = getContainedTypeID(FTyID, i + 1); 5628 if (FTy->getParamType(i)->isLabelTy()) 5629 Arg = getBasicBlock(Record[OpNum]); 5630 else 5631 Arg = getValue(Record, OpNum, NextValueNo, FTy->getParamType(i), 5632 ArgTyID, CurBB); 5633 if (!Arg) 5634 return error("Invalid record"); 5635 Args.push_back(Arg); 5636 ArgTyIDs.push_back(ArgTyID); 5637 } 5638 5639 // Read type/value pairs for varargs params. 5640 if (!FTy->isVarArg()) { 5641 if (OpNum != Record.size()) 5642 return error("Invalid record"); 5643 } else { 5644 while (OpNum != Record.size()) { 5645 Value *Op; 5646 unsigned OpTypeID; 5647 if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB)) 5648 return error("Invalid record"); 5649 Args.push_back(Op); 5650 ArgTyIDs.push_back(OpTypeID); 5651 } 5652 } 5653 5654 // Upgrade the bundles if needed. 5655 if (!OperandBundles.empty()) 5656 UpgradeOperandBundles(OperandBundles); 5657 5658 if (auto *IA = dyn_cast<InlineAsm>(Callee)) { 5659 InlineAsm::ConstraintInfoVector ConstraintInfo = IA->ParseConstraints(); 5660 auto IsLabelConstraint = [](const InlineAsm::ConstraintInfo &CI) { 5661 return CI.Type == InlineAsm::isLabel; 5662 }; 5663 if (none_of(ConstraintInfo, IsLabelConstraint)) { 5664 // Upgrade explicit blockaddress arguments to label constraints. 5665 // Verify that the last arguments are blockaddress arguments that 5666 // match the indirect destinations. Clang always generates callbr 5667 // in this form. We could support reordering with more effort. 5668 unsigned FirstBlockArg = Args.size() - IndirectDests.size(); 5669 for (unsigned ArgNo = FirstBlockArg; ArgNo < Args.size(); ++ArgNo) { 5670 unsigned LabelNo = ArgNo - FirstBlockArg; 5671 auto *BA = dyn_cast<BlockAddress>(Args[ArgNo]); 5672 if (!BA || BA->getFunction() != F || 5673 LabelNo > IndirectDests.size() || 5674 BA->getBasicBlock() != IndirectDests[LabelNo]) 5675 return error("callbr argument does not match indirect dest"); 5676 } 5677 5678 // Remove blockaddress arguments. 5679 Args.erase(Args.begin() + FirstBlockArg, Args.end()); 5680 ArgTyIDs.erase(ArgTyIDs.begin() + FirstBlockArg, ArgTyIDs.end()); 5681 5682 // Recreate the function type with less arguments. 5683 SmallVector<Type *> ArgTys; 5684 for (Value *Arg : Args) 5685 ArgTys.push_back(Arg->getType()); 5686 FTy = 5687 FunctionType::get(FTy->getReturnType(), ArgTys, FTy->isVarArg()); 5688 5689 // Update constraint string to use label constraints. 5690 std::string Constraints = IA->getConstraintString(); 5691 unsigned ArgNo = 0; 5692 size_t Pos = 0; 5693 for (const auto &CI : ConstraintInfo) { 5694 if (CI.hasArg()) { 5695 if (ArgNo >= FirstBlockArg) 5696 Constraints.insert(Pos, "!"); 5697 ++ArgNo; 5698 } 5699 5700 // Go to next constraint in string. 5701 Pos = Constraints.find(',', Pos); 5702 if (Pos == std::string::npos) 5703 break; 5704 ++Pos; 5705 } 5706 5707 Callee = InlineAsm::get(FTy, IA->getAsmString(), Constraints, 5708 IA->hasSideEffects(), IA->isAlignStack(), 5709 IA->getDialect(), IA->canThrow()); 5710 } 5711 } 5712 5713 I = CallBrInst::Create(FTy, Callee, DefaultDest, IndirectDests, Args, 5714 OperandBundles); 5715 ResTypeID = getContainedTypeID(FTyID); 5716 OperandBundles.clear(); 5717 InstructionList.push_back(I); 5718 cast<CallBrInst>(I)->setCallingConv( 5719 static_cast<CallingConv::ID>((0x7ff & CCInfo) >> bitc::CALL_CCONV)); 5720 cast<CallBrInst>(I)->setAttributes(PAL); 5721 if (Error Err = propagateAttributeTypes(cast<CallBase>(I), ArgTyIDs)) { 5722 I->deleteValue(); 5723 return Err; 5724 } 5725 break; 5726 } 5727 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE 5728 I = new UnreachableInst(Context); 5729 InstructionList.push_back(I); 5730 break; 5731 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...] 5732 if (Record.empty()) 5733 return error("Invalid phi record"); 5734 // The first record specifies the type. 5735 unsigned TyID = Record[0]; 5736 Type *Ty = getTypeByID(TyID); 5737 if (!Ty) 5738 return error("Invalid phi record"); 5739 5740 // Phi arguments are pairs of records of [value, basic block]. 5741 // There is an optional final record for fast-math-flags if this phi has a 5742 // floating-point type. 5743 size_t NumArgs = (Record.size() - 1) / 2; 5744 PHINode *PN = PHINode::Create(Ty, NumArgs); 5745 if ((Record.size() - 1) % 2 == 1 && !isa<FPMathOperator>(PN)) { 5746 PN->deleteValue(); 5747 return error("Invalid phi record"); 5748 } 5749 InstructionList.push_back(PN); 5750 5751 SmallDenseMap<BasicBlock *, Value *> Args; 5752 for (unsigned i = 0; i != NumArgs; i++) { 5753 BasicBlock *BB = getBasicBlock(Record[i * 2 + 2]); 5754 if (!BB) { 5755 PN->deleteValue(); 5756 return error("Invalid phi BB"); 5757 } 5758 5759 // Phi nodes may contain the same predecessor multiple times, in which 5760 // case the incoming value must be identical. Directly reuse the already 5761 // seen value here, to avoid expanding a constant expression multiple 5762 // times. 5763 auto It = Args.find(BB); 5764 if (It != Args.end()) { 5765 PN->addIncoming(It->second, BB); 5766 continue; 5767 } 5768 5769 // If there already is a block for this edge (from a different phi), 5770 // use it. 5771 BasicBlock *EdgeBB = ConstExprEdgeBBs.lookup({BB, CurBB}); 5772 if (!EdgeBB) { 5773 // Otherwise, use a temporary block (that we will discard if it 5774 // turns out to be unnecessary). 5775 if (!PhiConstExprBB) 5776 PhiConstExprBB = BasicBlock::Create(Context, "phi.constexpr", F); 5777 EdgeBB = PhiConstExprBB; 5778 } 5779 5780 // With the new function encoding, it is possible that operands have 5781 // negative IDs (for forward references). Use a signed VBR 5782 // representation to keep the encoding small. 5783 Value *V; 5784 if (UseRelativeIDs) 5785 V = getValueSigned(Record, i * 2 + 1, NextValueNo, Ty, TyID, EdgeBB); 5786 else 5787 V = getValue(Record, i * 2 + 1, NextValueNo, Ty, TyID, EdgeBB); 5788 if (!V) { 5789 PN->deleteValue(); 5790 PhiConstExprBB->eraseFromParent(); 5791 return error("Invalid phi record"); 5792 } 5793 5794 if (EdgeBB == PhiConstExprBB && !EdgeBB->empty()) { 5795 ConstExprEdgeBBs.insert({{BB, CurBB}, EdgeBB}); 5796 PhiConstExprBB = nullptr; 5797 } 5798 PN->addIncoming(V, BB); 5799 Args.insert({BB, V}); 5800 } 5801 I = PN; 5802 ResTypeID = TyID; 5803 5804 // If there are an even number of records, the final record must be FMF. 5805 if (Record.size() % 2 == 0) { 5806 assert(isa<FPMathOperator>(I) && "Unexpected phi type"); 5807 FastMathFlags FMF = getDecodedFastMathFlags(Record[Record.size() - 1]); 5808 if (FMF.any()) 5809 I->setFastMathFlags(FMF); 5810 } 5811 5812 break; 5813 } 5814 5815 case bitc::FUNC_CODE_INST_LANDINGPAD: 5816 case bitc::FUNC_CODE_INST_LANDINGPAD_OLD: { 5817 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?] 5818 unsigned Idx = 0; 5819 if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD) { 5820 if (Record.size() < 3) 5821 return error("Invalid record"); 5822 } else { 5823 assert(BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD); 5824 if (Record.size() < 4) 5825 return error("Invalid record"); 5826 } 5827 ResTypeID = Record[Idx++]; 5828 Type *Ty = getTypeByID(ResTypeID); 5829 if (!Ty) 5830 return error("Invalid record"); 5831 if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD) { 5832 Value *PersFn = nullptr; 5833 unsigned PersFnTypeID; 5834 if (getValueTypePair(Record, Idx, NextValueNo, PersFn, PersFnTypeID, 5835 nullptr)) 5836 return error("Invalid record"); 5837 5838 if (!F->hasPersonalityFn()) 5839 F->setPersonalityFn(cast<Constant>(PersFn)); 5840 else if (F->getPersonalityFn() != cast<Constant>(PersFn)) 5841 return error("Personality function mismatch"); 5842 } 5843 5844 bool IsCleanup = !!Record[Idx++]; 5845 unsigned NumClauses = Record[Idx++]; 5846 LandingPadInst *LP = LandingPadInst::Create(Ty, NumClauses); 5847 LP->setCleanup(IsCleanup); 5848 for (unsigned J = 0; J != NumClauses; ++J) { 5849 LandingPadInst::ClauseType CT = 5850 LandingPadInst::ClauseType(Record[Idx++]); (void)CT; 5851 Value *Val; 5852 unsigned ValTypeID; 5853 5854 if (getValueTypePair(Record, Idx, NextValueNo, Val, ValTypeID, 5855 nullptr)) { 5856 delete LP; 5857 return error("Invalid record"); 5858 } 5859 5860 assert((CT != LandingPadInst::Catch || 5861 !isa<ArrayType>(Val->getType())) && 5862 "Catch clause has a invalid type!"); 5863 assert((CT != LandingPadInst::Filter || 5864 isa<ArrayType>(Val->getType())) && 5865 "Filter clause has invalid type!"); 5866 LP->addClause(cast<Constant>(Val)); 5867 } 5868 5869 I = LP; 5870 InstructionList.push_back(I); 5871 break; 5872 } 5873 5874 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align] 5875 if (Record.size() != 4 && Record.size() != 5) 5876 return error("Invalid record"); 5877 using APV = AllocaPackedValues; 5878 const uint64_t Rec = Record[3]; 5879 const bool InAlloca = Bitfield::get<APV::UsedWithInAlloca>(Rec); 5880 const bool SwiftError = Bitfield::get<APV::SwiftError>(Rec); 5881 unsigned TyID = Record[0]; 5882 Type *Ty = getTypeByID(TyID); 5883 if (!Bitfield::get<APV::ExplicitType>(Rec)) { 5884 TyID = getContainedTypeID(TyID); 5885 Ty = getTypeByID(TyID); 5886 if (!Ty) 5887 return error("Missing element type for old-style alloca"); 5888 } 5889 unsigned OpTyID = Record[1]; 5890 Type *OpTy = getTypeByID(OpTyID); 5891 Value *Size = getFnValueByID(Record[2], OpTy, OpTyID, CurBB); 5892 MaybeAlign Align; 5893 uint64_t AlignExp = 5894 Bitfield::get<APV::AlignLower>(Rec) | 5895 (Bitfield::get<APV::AlignUpper>(Rec) << APV::AlignLower::Bits); 5896 if (Error Err = parseAlignmentValue(AlignExp, Align)) { 5897 return Err; 5898 } 5899 if (!Ty || !Size) 5900 return error("Invalid record"); 5901 5902 const DataLayout &DL = TheModule->getDataLayout(); 5903 unsigned AS = Record.size() == 5 ? Record[4] : DL.getAllocaAddrSpace(); 5904 5905 SmallPtrSet<Type *, 4> Visited; 5906 if (!Align && !Ty->isSized(&Visited)) 5907 return error("alloca of unsized type"); 5908 if (!Align) 5909 Align = DL.getPrefTypeAlign(Ty); 5910 5911 AllocaInst *AI = new AllocaInst(Ty, AS, Size, *Align); 5912 AI->setUsedWithInAlloca(InAlloca); 5913 AI->setSwiftError(SwiftError); 5914 I = AI; 5915 ResTypeID = getVirtualTypeID(AI->getType(), TyID); 5916 InstructionList.push_back(I); 5917 break; 5918 } 5919 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol] 5920 unsigned OpNum = 0; 5921 Value *Op; 5922 unsigned OpTypeID; 5923 if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB) || 5924 (OpNum + 2 != Record.size() && OpNum + 3 != Record.size())) 5925 return error("Invalid record"); 5926 5927 if (!isa<PointerType>(Op->getType())) 5928 return error("Load operand is not a pointer type"); 5929 5930 Type *Ty = nullptr; 5931 if (OpNum + 3 == Record.size()) { 5932 ResTypeID = Record[OpNum++]; 5933 Ty = getTypeByID(ResTypeID); 5934 } else { 5935 ResTypeID = getContainedTypeID(OpTypeID); 5936 Ty = getTypeByID(ResTypeID); 5937 if (!Ty) 5938 return error("Missing element type for old-style load"); 5939 } 5940 5941 if (Error Err = typeCheckLoadStoreInst(Ty, Op->getType())) 5942 return Err; 5943 5944 MaybeAlign Align; 5945 if (Error Err = parseAlignmentValue(Record[OpNum], Align)) 5946 return Err; 5947 SmallPtrSet<Type *, 4> Visited; 5948 if (!Align && !Ty->isSized(&Visited)) 5949 return error("load of unsized type"); 5950 if (!Align) 5951 Align = TheModule->getDataLayout().getABITypeAlign(Ty); 5952 I = new LoadInst(Ty, Op, "", Record[OpNum + 1], *Align); 5953 InstructionList.push_back(I); 5954 break; 5955 } 5956 case bitc::FUNC_CODE_INST_LOADATOMIC: { 5957 // LOADATOMIC: [opty, op, align, vol, ordering, ssid] 5958 unsigned OpNum = 0; 5959 Value *Op; 5960 unsigned OpTypeID; 5961 if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB) || 5962 (OpNum + 4 != Record.size() && OpNum + 5 != Record.size())) 5963 return error("Invalid record"); 5964 5965 if (!isa<PointerType>(Op->getType())) 5966 return error("Load operand is not a pointer type"); 5967 5968 Type *Ty = nullptr; 5969 if (OpNum + 5 == Record.size()) { 5970 ResTypeID = Record[OpNum++]; 5971 Ty = getTypeByID(ResTypeID); 5972 } else { 5973 ResTypeID = getContainedTypeID(OpTypeID); 5974 Ty = getTypeByID(ResTypeID); 5975 if (!Ty) 5976 return error("Missing element type for old style atomic load"); 5977 } 5978 5979 if (Error Err = typeCheckLoadStoreInst(Ty, Op->getType())) 5980 return Err; 5981 5982 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]); 5983 if (Ordering == AtomicOrdering::NotAtomic || 5984 Ordering == AtomicOrdering::Release || 5985 Ordering == AtomicOrdering::AcquireRelease) 5986 return error("Invalid record"); 5987 if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0) 5988 return error("Invalid record"); 5989 SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]); 5990 5991 MaybeAlign Align; 5992 if (Error Err = parseAlignmentValue(Record[OpNum], Align)) 5993 return Err; 5994 if (!Align) 5995 return error("Alignment missing from atomic load"); 5996 I = new LoadInst(Ty, Op, "", Record[OpNum + 1], *Align, Ordering, SSID); 5997 InstructionList.push_back(I); 5998 break; 5999 } 6000 case bitc::FUNC_CODE_INST_STORE: 6001 case bitc::FUNC_CODE_INST_STORE_OLD: { // STORE2:[ptrty, ptr, val, align, vol] 6002 unsigned OpNum = 0; 6003 Value *Val, *Ptr; 6004 unsigned PtrTypeID, ValTypeID; 6005 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB)) 6006 return error("Invalid record"); 6007 6008 if (BitCode == bitc::FUNC_CODE_INST_STORE) { 6009 if (getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID, CurBB)) 6010 return error("Invalid record"); 6011 } else { 6012 ValTypeID = getContainedTypeID(PtrTypeID); 6013 if (popValue(Record, OpNum, NextValueNo, getTypeByID(ValTypeID), 6014 ValTypeID, Val, CurBB)) 6015 return error("Invalid record"); 6016 } 6017 6018 if (OpNum + 2 != Record.size()) 6019 return error("Invalid record"); 6020 6021 if (Error Err = typeCheckLoadStoreInst(Val->getType(), Ptr->getType())) 6022 return Err; 6023 MaybeAlign Align; 6024 if (Error Err = parseAlignmentValue(Record[OpNum], Align)) 6025 return Err; 6026 SmallPtrSet<Type *, 4> Visited; 6027 if (!Align && !Val->getType()->isSized(&Visited)) 6028 return error("store of unsized type"); 6029 if (!Align) 6030 Align = TheModule->getDataLayout().getABITypeAlign(Val->getType()); 6031 I = new StoreInst(Val, Ptr, Record[OpNum + 1], *Align); 6032 InstructionList.push_back(I); 6033 break; 6034 } 6035 case bitc::FUNC_CODE_INST_STOREATOMIC: 6036 case bitc::FUNC_CODE_INST_STOREATOMIC_OLD: { 6037 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, ssid] 6038 unsigned OpNum = 0; 6039 Value *Val, *Ptr; 6040 unsigned PtrTypeID, ValTypeID; 6041 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB) || 6042 !isa<PointerType>(Ptr->getType())) 6043 return error("Invalid record"); 6044 if (BitCode == bitc::FUNC_CODE_INST_STOREATOMIC) { 6045 if (getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID, CurBB)) 6046 return error("Invalid record"); 6047 } else { 6048 ValTypeID = getContainedTypeID(PtrTypeID); 6049 if (popValue(Record, OpNum, NextValueNo, getTypeByID(ValTypeID), 6050 ValTypeID, Val, CurBB)) 6051 return error("Invalid record"); 6052 } 6053 6054 if (OpNum + 4 != Record.size()) 6055 return error("Invalid record"); 6056 6057 if (Error Err = typeCheckLoadStoreInst(Val->getType(), Ptr->getType())) 6058 return Err; 6059 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]); 6060 if (Ordering == AtomicOrdering::NotAtomic || 6061 Ordering == AtomicOrdering::Acquire || 6062 Ordering == AtomicOrdering::AcquireRelease) 6063 return error("Invalid record"); 6064 SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]); 6065 if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0) 6066 return error("Invalid record"); 6067 6068 MaybeAlign Align; 6069 if (Error Err = parseAlignmentValue(Record[OpNum], Align)) 6070 return Err; 6071 if (!Align) 6072 return error("Alignment missing from atomic store"); 6073 I = new StoreInst(Val, Ptr, Record[OpNum + 1], *Align, Ordering, SSID); 6074 InstructionList.push_back(I); 6075 break; 6076 } 6077 case bitc::FUNC_CODE_INST_CMPXCHG_OLD: { 6078 // CMPXCHG_OLD: [ptrty, ptr, cmp, val, vol, ordering, synchscope, 6079 // failure_ordering?, weak?] 6080 const size_t NumRecords = Record.size(); 6081 unsigned OpNum = 0; 6082 Value *Ptr = nullptr; 6083 unsigned PtrTypeID; 6084 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB)) 6085 return error("Invalid record"); 6086 6087 if (!isa<PointerType>(Ptr->getType())) 6088 return error("Cmpxchg operand is not a pointer type"); 6089 6090 Value *Cmp = nullptr; 6091 unsigned CmpTypeID = getContainedTypeID(PtrTypeID); 6092 if (popValue(Record, OpNum, NextValueNo, getTypeByID(CmpTypeID), 6093 CmpTypeID, Cmp, CurBB)) 6094 return error("Invalid record"); 6095 6096 Value *New = nullptr; 6097 if (popValue(Record, OpNum, NextValueNo, Cmp->getType(), CmpTypeID, 6098 New, CurBB) || 6099 NumRecords < OpNum + 3 || NumRecords > OpNum + 5) 6100 return error("Invalid record"); 6101 6102 const AtomicOrdering SuccessOrdering = 6103 getDecodedOrdering(Record[OpNum + 1]); 6104 if (SuccessOrdering == AtomicOrdering::NotAtomic || 6105 SuccessOrdering == AtomicOrdering::Unordered) 6106 return error("Invalid record"); 6107 6108 const SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 2]); 6109 6110 if (Error Err = typeCheckLoadStoreInst(Cmp->getType(), Ptr->getType())) 6111 return Err; 6112 6113 const AtomicOrdering FailureOrdering = 6114 NumRecords < 7 6115 ? AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering) 6116 : getDecodedOrdering(Record[OpNum + 3]); 6117 6118 if (FailureOrdering == AtomicOrdering::NotAtomic || 6119 FailureOrdering == AtomicOrdering::Unordered) 6120 return error("Invalid record"); 6121 6122 const Align Alignment( 6123 TheModule->getDataLayout().getTypeStoreSize(Cmp->getType())); 6124 6125 I = new AtomicCmpXchgInst(Ptr, Cmp, New, Alignment, SuccessOrdering, 6126 FailureOrdering, SSID); 6127 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]); 6128 6129 if (NumRecords < 8) { 6130 // Before weak cmpxchgs existed, the instruction simply returned the 6131 // value loaded from memory, so bitcode files from that era will be 6132 // expecting the first component of a modern cmpxchg. 6133 I->insertInto(CurBB, CurBB->end()); 6134 I = ExtractValueInst::Create(I, 0); 6135 ResTypeID = CmpTypeID; 6136 } else { 6137 cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum + 4]); 6138 unsigned I1TypeID = getVirtualTypeID(Type::getInt1Ty(Context)); 6139 ResTypeID = getVirtualTypeID(I->getType(), {CmpTypeID, I1TypeID}); 6140 } 6141 6142 InstructionList.push_back(I); 6143 break; 6144 } 6145 case bitc::FUNC_CODE_INST_CMPXCHG: { 6146 // CMPXCHG: [ptrty, ptr, cmp, val, vol, success_ordering, synchscope, 6147 // failure_ordering, weak, align?] 6148 const size_t NumRecords = Record.size(); 6149 unsigned OpNum = 0; 6150 Value *Ptr = nullptr; 6151 unsigned PtrTypeID; 6152 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB)) 6153 return error("Invalid record"); 6154 6155 if (!isa<PointerType>(Ptr->getType())) 6156 return error("Cmpxchg operand is not a pointer type"); 6157 6158 Value *Cmp = nullptr; 6159 unsigned CmpTypeID; 6160 if (getValueTypePair(Record, OpNum, NextValueNo, Cmp, CmpTypeID, CurBB)) 6161 return error("Invalid record"); 6162 6163 Value *Val = nullptr; 6164 if (popValue(Record, OpNum, NextValueNo, Cmp->getType(), CmpTypeID, Val, 6165 CurBB)) 6166 return error("Invalid record"); 6167 6168 if (NumRecords < OpNum + 3 || NumRecords > OpNum + 6) 6169 return error("Invalid record"); 6170 6171 const bool IsVol = Record[OpNum]; 6172 6173 const AtomicOrdering SuccessOrdering = 6174 getDecodedOrdering(Record[OpNum + 1]); 6175 if (!AtomicCmpXchgInst::isValidSuccessOrdering(SuccessOrdering)) 6176 return error("Invalid cmpxchg success ordering"); 6177 6178 const SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 2]); 6179 6180 if (Error Err = typeCheckLoadStoreInst(Cmp->getType(), Ptr->getType())) 6181 return Err; 6182 6183 const AtomicOrdering FailureOrdering = 6184 getDecodedOrdering(Record[OpNum + 3]); 6185 if (!AtomicCmpXchgInst::isValidFailureOrdering(FailureOrdering)) 6186 return error("Invalid cmpxchg failure ordering"); 6187 6188 const bool IsWeak = Record[OpNum + 4]; 6189 6190 MaybeAlign Alignment; 6191 6192 if (NumRecords == (OpNum + 6)) { 6193 if (Error Err = parseAlignmentValue(Record[OpNum + 5], Alignment)) 6194 return Err; 6195 } 6196 if (!Alignment) 6197 Alignment = 6198 Align(TheModule->getDataLayout().getTypeStoreSize(Cmp->getType())); 6199 6200 I = new AtomicCmpXchgInst(Ptr, Cmp, Val, *Alignment, SuccessOrdering, 6201 FailureOrdering, SSID); 6202 cast<AtomicCmpXchgInst>(I)->setVolatile(IsVol); 6203 cast<AtomicCmpXchgInst>(I)->setWeak(IsWeak); 6204 6205 unsigned I1TypeID = getVirtualTypeID(Type::getInt1Ty(Context)); 6206 ResTypeID = getVirtualTypeID(I->getType(), {CmpTypeID, I1TypeID}); 6207 6208 InstructionList.push_back(I); 6209 break; 6210 } 6211 case bitc::FUNC_CODE_INST_ATOMICRMW_OLD: 6212 case bitc::FUNC_CODE_INST_ATOMICRMW: { 6213 // ATOMICRMW_OLD: [ptrty, ptr, val, op, vol, ordering, ssid, align?] 6214 // ATOMICRMW: [ptrty, ptr, valty, val, op, vol, ordering, ssid, align?] 6215 const size_t NumRecords = Record.size(); 6216 unsigned OpNum = 0; 6217 6218 Value *Ptr = nullptr; 6219 unsigned PtrTypeID; 6220 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB)) 6221 return error("Invalid record"); 6222 6223 if (!isa<PointerType>(Ptr->getType())) 6224 return error("Invalid record"); 6225 6226 Value *Val = nullptr; 6227 unsigned ValTypeID = InvalidTypeID; 6228 if (BitCode == bitc::FUNC_CODE_INST_ATOMICRMW_OLD) { 6229 ValTypeID = getContainedTypeID(PtrTypeID); 6230 if (popValue(Record, OpNum, NextValueNo, 6231 getTypeByID(ValTypeID), ValTypeID, Val, CurBB)) 6232 return error("Invalid record"); 6233 } else { 6234 if (getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID, CurBB)) 6235 return error("Invalid record"); 6236 } 6237 6238 if (!(NumRecords == (OpNum + 4) || NumRecords == (OpNum + 5))) 6239 return error("Invalid record"); 6240 6241 const AtomicRMWInst::BinOp Operation = 6242 getDecodedRMWOperation(Record[OpNum]); 6243 if (Operation < AtomicRMWInst::FIRST_BINOP || 6244 Operation > AtomicRMWInst::LAST_BINOP) 6245 return error("Invalid record"); 6246 6247 const bool IsVol = Record[OpNum + 1]; 6248 6249 const AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]); 6250 if (Ordering == AtomicOrdering::NotAtomic || 6251 Ordering == AtomicOrdering::Unordered) 6252 return error("Invalid record"); 6253 6254 const SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]); 6255 6256 MaybeAlign Alignment; 6257 6258 if (NumRecords == (OpNum + 5)) { 6259 if (Error Err = parseAlignmentValue(Record[OpNum + 4], Alignment)) 6260 return Err; 6261 } 6262 6263 if (!Alignment) 6264 Alignment = 6265 Align(TheModule->getDataLayout().getTypeStoreSize(Val->getType())); 6266 6267 I = new AtomicRMWInst(Operation, Ptr, Val, *Alignment, Ordering, SSID); 6268 ResTypeID = ValTypeID; 6269 cast<AtomicRMWInst>(I)->setVolatile(IsVol); 6270 6271 InstructionList.push_back(I); 6272 break; 6273 } 6274 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, ssid] 6275 if (2 != Record.size()) 6276 return error("Invalid record"); 6277 AtomicOrdering Ordering = getDecodedOrdering(Record[0]); 6278 if (Ordering == AtomicOrdering::NotAtomic || 6279 Ordering == AtomicOrdering::Unordered || 6280 Ordering == AtomicOrdering::Monotonic) 6281 return error("Invalid record"); 6282 SyncScope::ID SSID = getDecodedSyncScopeID(Record[1]); 6283 I = new FenceInst(Context, Ordering, SSID); 6284 InstructionList.push_back(I); 6285 break; 6286 } 6287 case bitc::FUNC_CODE_INST_CALL: { 6288 // CALL: [paramattrs, cc, fmf, fnty, fnid, arg0, arg1...] 6289 if (Record.size() < 3) 6290 return error("Invalid record"); 6291 6292 unsigned OpNum = 0; 6293 AttributeList PAL = getAttributes(Record[OpNum++]); 6294 unsigned CCInfo = Record[OpNum++]; 6295 6296 FastMathFlags FMF; 6297 if ((CCInfo >> bitc::CALL_FMF) & 1) { 6298 FMF = getDecodedFastMathFlags(Record[OpNum++]); 6299 if (!FMF.any()) 6300 return error("Fast math flags indicator set for call with no FMF"); 6301 } 6302 6303 unsigned FTyID = InvalidTypeID; 6304 FunctionType *FTy = nullptr; 6305 if ((CCInfo >> bitc::CALL_EXPLICIT_TYPE) & 1) { 6306 FTyID = Record[OpNum++]; 6307 FTy = dyn_cast_or_null<FunctionType>(getTypeByID(FTyID)); 6308 if (!FTy) 6309 return error("Explicit call type is not a function type"); 6310 } 6311 6312 Value *Callee; 6313 unsigned CalleeTypeID; 6314 if (getValueTypePair(Record, OpNum, NextValueNo, Callee, CalleeTypeID, 6315 CurBB)) 6316 return error("Invalid record"); 6317 6318 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType()); 6319 if (!OpTy) 6320 return error("Callee is not a pointer type"); 6321 if (!FTy) { 6322 FTyID = getContainedTypeID(CalleeTypeID); 6323 FTy = dyn_cast_or_null<FunctionType>(getTypeByID(FTyID)); 6324 if (!FTy) 6325 return error("Callee is not of pointer to function type"); 6326 } 6327 if (Record.size() < FTy->getNumParams() + OpNum) 6328 return error("Insufficient operands to call"); 6329 6330 SmallVector<Value*, 16> Args; 6331 SmallVector<unsigned, 16> ArgTyIDs; 6332 // Read the fixed params. 6333 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) { 6334 unsigned ArgTyID = getContainedTypeID(FTyID, i + 1); 6335 if (FTy->getParamType(i)->isLabelTy()) 6336 Args.push_back(getBasicBlock(Record[OpNum])); 6337 else 6338 Args.push_back(getValue(Record, OpNum, NextValueNo, 6339 FTy->getParamType(i), ArgTyID, CurBB)); 6340 ArgTyIDs.push_back(ArgTyID); 6341 if (!Args.back()) 6342 return error("Invalid record"); 6343 } 6344 6345 // Read type/value pairs for varargs params. 6346 if (!FTy->isVarArg()) { 6347 if (OpNum != Record.size()) 6348 return error("Invalid record"); 6349 } else { 6350 while (OpNum != Record.size()) { 6351 Value *Op; 6352 unsigned OpTypeID; 6353 if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB)) 6354 return error("Invalid record"); 6355 Args.push_back(Op); 6356 ArgTyIDs.push_back(OpTypeID); 6357 } 6358 } 6359 6360 // Upgrade the bundles if needed. 6361 if (!OperandBundles.empty()) 6362 UpgradeOperandBundles(OperandBundles); 6363 6364 I = CallInst::Create(FTy, Callee, Args, OperandBundles); 6365 ResTypeID = getContainedTypeID(FTyID); 6366 OperandBundles.clear(); 6367 InstructionList.push_back(I); 6368 cast<CallInst>(I)->setCallingConv( 6369 static_cast<CallingConv::ID>((0x7ff & CCInfo) >> bitc::CALL_CCONV)); 6370 CallInst::TailCallKind TCK = CallInst::TCK_None; 6371 if (CCInfo & (1 << bitc::CALL_TAIL)) 6372 TCK = CallInst::TCK_Tail; 6373 if (CCInfo & (1 << bitc::CALL_MUSTTAIL)) 6374 TCK = CallInst::TCK_MustTail; 6375 if (CCInfo & (1 << bitc::CALL_NOTAIL)) 6376 TCK = CallInst::TCK_NoTail; 6377 cast<CallInst>(I)->setTailCallKind(TCK); 6378 cast<CallInst>(I)->setAttributes(PAL); 6379 if (Error Err = propagateAttributeTypes(cast<CallBase>(I), ArgTyIDs)) { 6380 I->deleteValue(); 6381 return Err; 6382 } 6383 if (FMF.any()) { 6384 if (!isa<FPMathOperator>(I)) 6385 return error("Fast-math-flags specified for call without " 6386 "floating-point scalar or vector return type"); 6387 I->setFastMathFlags(FMF); 6388 } 6389 break; 6390 } 6391 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty] 6392 if (Record.size() < 3) 6393 return error("Invalid record"); 6394 unsigned OpTyID = Record[0]; 6395 Type *OpTy = getTypeByID(OpTyID); 6396 Value *Op = getValue(Record, 1, NextValueNo, OpTy, OpTyID, CurBB); 6397 ResTypeID = Record[2]; 6398 Type *ResTy = getTypeByID(ResTypeID); 6399 if (!OpTy || !Op || !ResTy) 6400 return error("Invalid record"); 6401 I = new VAArgInst(Op, ResTy); 6402 InstructionList.push_back(I); 6403 break; 6404 } 6405 6406 case bitc::FUNC_CODE_OPERAND_BUNDLE: { 6407 // A call or an invoke can be optionally prefixed with some variable 6408 // number of operand bundle blocks. These blocks are read into 6409 // OperandBundles and consumed at the next call or invoke instruction. 6410 6411 if (Record.empty() || Record[0] >= BundleTags.size()) 6412 return error("Invalid record"); 6413 6414 std::vector<Value *> Inputs; 6415 6416 unsigned OpNum = 1; 6417 while (OpNum != Record.size()) { 6418 Value *Op; 6419 unsigned OpTypeID; 6420 if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB)) 6421 return error("Invalid record"); 6422 Inputs.push_back(Op); 6423 } 6424 6425 OperandBundles.emplace_back(BundleTags[Record[0]], std::move(Inputs)); 6426 continue; 6427 } 6428 6429 case bitc::FUNC_CODE_INST_FREEZE: { // FREEZE: [opty,opval] 6430 unsigned OpNum = 0; 6431 Value *Op = nullptr; 6432 unsigned OpTypeID; 6433 if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB)) 6434 return error("Invalid record"); 6435 if (OpNum != Record.size()) 6436 return error("Invalid record"); 6437 6438 I = new FreezeInst(Op); 6439 ResTypeID = OpTypeID; 6440 InstructionList.push_back(I); 6441 break; 6442 } 6443 } 6444 6445 // Add instruction to end of current BB. If there is no current BB, reject 6446 // this file. 6447 if (!CurBB) { 6448 I->deleteValue(); 6449 return error("Invalid instruction with no BB"); 6450 } 6451 if (!OperandBundles.empty()) { 6452 I->deleteValue(); 6453 return error("Operand bundles found with no consumer"); 6454 } 6455 I->insertInto(CurBB, CurBB->end()); 6456 6457 // If this was a terminator instruction, move to the next block. 6458 if (I->isTerminator()) { 6459 ++CurBBNo; 6460 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr; 6461 } 6462 6463 // Non-void values get registered in the value table for future use. 6464 if (!I->getType()->isVoidTy()) { 6465 assert(I->getType() == getTypeByID(ResTypeID) && 6466 "Incorrect result type ID"); 6467 if (Error Err = ValueList.assignValue(NextValueNo++, I, ResTypeID)) 6468 return Err; 6469 } 6470 } 6471 6472 OutOfRecordLoop: 6473 6474 if (!OperandBundles.empty()) 6475 return error("Operand bundles found with no consumer"); 6476 6477 // Check the function list for unresolved values. 6478 if (Argument *A = dyn_cast<Argument>(ValueList.back())) { 6479 if (!A->getParent()) { 6480 // We found at least one unresolved value. Nuke them all to avoid leaks. 6481 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){ 6482 if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) { 6483 A->replaceAllUsesWith(PoisonValue::get(A->getType())); 6484 delete A; 6485 } 6486 } 6487 return error("Never resolved value found in function"); 6488 } 6489 } 6490 6491 // Unexpected unresolved metadata about to be dropped. 6492 if (MDLoader->hasFwdRefs()) 6493 return error("Invalid function metadata: outgoing forward refs"); 6494 6495 if (PhiConstExprBB) 6496 PhiConstExprBB->eraseFromParent(); 6497 6498 for (const auto &Pair : ConstExprEdgeBBs) { 6499 BasicBlock *From = Pair.first.first; 6500 BasicBlock *To = Pair.first.second; 6501 BasicBlock *EdgeBB = Pair.second; 6502 BranchInst::Create(To, EdgeBB); 6503 From->getTerminator()->replaceSuccessorWith(To, EdgeBB); 6504 To->replacePhiUsesWith(From, EdgeBB); 6505 EdgeBB->moveBefore(To); 6506 } 6507 6508 // Trim the value list down to the size it was before we parsed this function. 6509 ValueList.shrinkTo(ModuleValueListSize); 6510 MDLoader->shrinkTo(ModuleMDLoaderSize); 6511 std::vector<BasicBlock*>().swap(FunctionBBs); 6512 return Error::success(); 6513 } 6514 6515 /// Find the function body in the bitcode stream 6516 Error BitcodeReader::findFunctionInStream( 6517 Function *F, 6518 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) { 6519 while (DeferredFunctionInfoIterator->second == 0) { 6520 // This is the fallback handling for the old format bitcode that 6521 // didn't contain the function index in the VST, or when we have 6522 // an anonymous function which would not have a VST entry. 6523 // Assert that we have one of those two cases. 6524 assert(VSTOffset == 0 || !F->hasName()); 6525 // Parse the next body in the stream and set its position in the 6526 // DeferredFunctionInfo map. 6527 if (Error Err = rememberAndSkipFunctionBodies()) 6528 return Err; 6529 } 6530 return Error::success(); 6531 } 6532 6533 SyncScope::ID BitcodeReader::getDecodedSyncScopeID(unsigned Val) { 6534 if (Val == SyncScope::SingleThread || Val == SyncScope::System) 6535 return SyncScope::ID(Val); 6536 if (Val >= SSIDs.size()) 6537 return SyncScope::System; // Map unknown synchronization scopes to system. 6538 return SSIDs[Val]; 6539 } 6540 6541 //===----------------------------------------------------------------------===// 6542 // GVMaterializer implementation 6543 //===----------------------------------------------------------------------===// 6544 6545 Error BitcodeReader::materialize(GlobalValue *GV) { 6546 Function *F = dyn_cast<Function>(GV); 6547 // If it's not a function or is already material, ignore the request. 6548 if (!F || !F->isMaterializable()) 6549 return Error::success(); 6550 6551 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F); 6552 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!"); 6553 // If its position is recorded as 0, its body is somewhere in the stream 6554 // but we haven't seen it yet. 6555 if (DFII->second == 0) 6556 if (Error Err = findFunctionInStream(F, DFII)) 6557 return Err; 6558 6559 // Materialize metadata before parsing any function bodies. 6560 if (Error Err = materializeMetadata()) 6561 return Err; 6562 6563 // Move the bit stream to the saved position of the deferred function body. 6564 if (Error JumpFailed = Stream.JumpToBit(DFII->second)) 6565 return JumpFailed; 6566 if (Error Err = parseFunctionBody(F)) 6567 return Err; 6568 F->setIsMaterializable(false); 6569 6570 if (StripDebugInfo) 6571 stripDebugInfo(*F); 6572 6573 // Upgrade any old intrinsic calls in the function. 6574 for (auto &I : UpgradedIntrinsics) { 6575 for (User *U : llvm::make_early_inc_range(I.first->materialized_users())) 6576 if (CallInst *CI = dyn_cast<CallInst>(U)) 6577 UpgradeIntrinsicCall(CI, I.second); 6578 } 6579 6580 // Finish fn->subprogram upgrade for materialized functions. 6581 if (DISubprogram *SP = MDLoader->lookupSubprogramForFunction(F)) 6582 F->setSubprogram(SP); 6583 6584 // Check if the TBAA Metadata are valid, otherwise we will need to strip them. 6585 if (!MDLoader->isStrippingTBAA()) { 6586 for (auto &I : instructions(F)) { 6587 MDNode *TBAA = I.getMetadata(LLVMContext::MD_tbaa); 6588 if (!TBAA || TBAAVerifyHelper.visitTBAAMetadata(I, TBAA)) 6589 continue; 6590 MDLoader->setStripTBAA(true); 6591 stripTBAA(F->getParent()); 6592 } 6593 } 6594 6595 for (auto &I : instructions(F)) { 6596 // "Upgrade" older incorrect branch weights by dropping them. 6597 if (auto *MD = I.getMetadata(LLVMContext::MD_prof)) { 6598 if (MD->getOperand(0) != nullptr && isa<MDString>(MD->getOperand(0))) { 6599 MDString *MDS = cast<MDString>(MD->getOperand(0)); 6600 StringRef ProfName = MDS->getString(); 6601 // Check consistency of !prof branch_weights metadata. 6602 if (!ProfName.equals("branch_weights")) 6603 continue; 6604 unsigned ExpectedNumOperands = 0; 6605 if (BranchInst *BI = dyn_cast<BranchInst>(&I)) 6606 ExpectedNumOperands = BI->getNumSuccessors(); 6607 else if (SwitchInst *SI = dyn_cast<SwitchInst>(&I)) 6608 ExpectedNumOperands = SI->getNumSuccessors(); 6609 else if (isa<CallInst>(&I)) 6610 ExpectedNumOperands = 1; 6611 else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(&I)) 6612 ExpectedNumOperands = IBI->getNumDestinations(); 6613 else if (isa<SelectInst>(&I)) 6614 ExpectedNumOperands = 2; 6615 else 6616 continue; // ignore and continue. 6617 6618 // If branch weight doesn't match, just strip branch weight. 6619 if (MD->getNumOperands() != 1 + ExpectedNumOperands) 6620 I.setMetadata(LLVMContext::MD_prof, nullptr); 6621 } 6622 } 6623 6624 // Remove incompatible attributes on function calls. 6625 if (auto *CI = dyn_cast<CallBase>(&I)) { 6626 CI->removeRetAttrs(AttributeFuncs::typeIncompatible( 6627 CI->getFunctionType()->getReturnType())); 6628 6629 for (unsigned ArgNo = 0; ArgNo < CI->arg_size(); ++ArgNo) 6630 CI->removeParamAttrs(ArgNo, AttributeFuncs::typeIncompatible( 6631 CI->getArgOperand(ArgNo)->getType())); 6632 } 6633 } 6634 6635 // Look for functions that rely on old function attribute behavior. 6636 UpgradeFunctionAttributes(*F); 6637 6638 // Bring in any functions that this function forward-referenced via 6639 // blockaddresses. 6640 return materializeForwardReferencedFunctions(); 6641 } 6642 6643 Error BitcodeReader::materializeModule() { 6644 if (Error Err = materializeMetadata()) 6645 return Err; 6646 6647 // Promise to materialize all forward references. 6648 WillMaterializeAllForwardRefs = true; 6649 6650 // Iterate over the module, deserializing any functions that are still on 6651 // disk. 6652 for (Function &F : *TheModule) { 6653 if (Error Err = materialize(&F)) 6654 return Err; 6655 } 6656 // At this point, if there are any function bodies, parse the rest of 6657 // the bits in the module past the last function block we have recorded 6658 // through either lazy scanning or the VST. 6659 if (LastFunctionBlockBit || NextUnreadBit) 6660 if (Error Err = parseModule(LastFunctionBlockBit > NextUnreadBit 6661 ? LastFunctionBlockBit 6662 : NextUnreadBit)) 6663 return Err; 6664 6665 // Check that all block address forward references got resolved (as we 6666 // promised above). 6667 if (!BasicBlockFwdRefs.empty()) 6668 return error("Never resolved function from blockaddress"); 6669 6670 // Upgrade any intrinsic calls that slipped through (should not happen!) and 6671 // delete the old functions to clean up. We can't do this unless the entire 6672 // module is materialized because there could always be another function body 6673 // with calls to the old function. 6674 for (auto &I : UpgradedIntrinsics) { 6675 for (auto *U : I.first->users()) { 6676 if (CallInst *CI = dyn_cast<CallInst>(U)) 6677 UpgradeIntrinsicCall(CI, I.second); 6678 } 6679 if (!I.first->use_empty()) 6680 I.first->replaceAllUsesWith(I.second); 6681 I.first->eraseFromParent(); 6682 } 6683 UpgradedIntrinsics.clear(); 6684 6685 UpgradeDebugInfo(*TheModule); 6686 6687 UpgradeModuleFlags(*TheModule); 6688 6689 UpgradeARCRuntime(*TheModule); 6690 6691 return Error::success(); 6692 } 6693 6694 std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const { 6695 return IdentifiedStructTypes; 6696 } 6697 6698 ModuleSummaryIndexBitcodeReader::ModuleSummaryIndexBitcodeReader( 6699 BitstreamCursor Cursor, StringRef Strtab, ModuleSummaryIndex &TheIndex, 6700 StringRef ModulePath, std::function<bool(GlobalValue::GUID)> IsPrevailing) 6701 : BitcodeReaderBase(std::move(Cursor), Strtab), TheIndex(TheIndex), 6702 ModulePath(ModulePath), IsPrevailing(IsPrevailing) {} 6703 6704 void ModuleSummaryIndexBitcodeReader::addThisModule() { 6705 TheIndex.addModule(ModulePath); 6706 } 6707 6708 ModuleSummaryIndex::ModuleInfo * 6709 ModuleSummaryIndexBitcodeReader::getThisModule() { 6710 return TheIndex.getModule(ModulePath); 6711 } 6712 6713 template <bool AllowNullValueInfo> 6714 std::tuple<ValueInfo, GlobalValue::GUID, GlobalValue::GUID> 6715 ModuleSummaryIndexBitcodeReader::getValueInfoFromValueId(unsigned ValueId) { 6716 auto VGI = ValueIdToValueInfoMap[ValueId]; 6717 // We can have a null value info for memprof callsite info records in 6718 // distributed ThinLTO index files when the callee function summary is not 6719 // included in the index. The bitcode writer records 0 in that case, 6720 // and the caller of this helper will set AllowNullValueInfo to true. 6721 assert(AllowNullValueInfo || std::get<0>(VGI)); 6722 return VGI; 6723 } 6724 6725 void ModuleSummaryIndexBitcodeReader::setValueGUID( 6726 uint64_t ValueID, StringRef ValueName, GlobalValue::LinkageTypes Linkage, 6727 StringRef SourceFileName) { 6728 std::string GlobalId = 6729 GlobalValue::getGlobalIdentifier(ValueName, Linkage, SourceFileName); 6730 auto ValueGUID = GlobalValue::getGUID(GlobalId); 6731 auto OriginalNameID = ValueGUID; 6732 if (GlobalValue::isLocalLinkage(Linkage)) 6733 OriginalNameID = GlobalValue::getGUID(ValueName); 6734 if (PrintSummaryGUIDs) 6735 dbgs() << "GUID " << ValueGUID << "(" << OriginalNameID << ") is " 6736 << ValueName << "\n"; 6737 6738 // UseStrtab is false for legacy summary formats and value names are 6739 // created on stack. In that case we save the name in a string saver in 6740 // the index so that the value name can be recorded. 6741 ValueIdToValueInfoMap[ValueID] = std::make_tuple( 6742 TheIndex.getOrInsertValueInfo( 6743 ValueGUID, UseStrtab ? ValueName : TheIndex.saveString(ValueName)), 6744 OriginalNameID, ValueGUID); 6745 } 6746 6747 // Specialized value symbol table parser used when reading module index 6748 // blocks where we don't actually create global values. The parsed information 6749 // is saved in the bitcode reader for use when later parsing summaries. 6750 Error ModuleSummaryIndexBitcodeReader::parseValueSymbolTable( 6751 uint64_t Offset, 6752 DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap) { 6753 // With a strtab the VST is not required to parse the summary. 6754 if (UseStrtab) 6755 return Error::success(); 6756 6757 assert(Offset > 0 && "Expected non-zero VST offset"); 6758 Expected<uint64_t> MaybeCurrentBit = jumpToValueSymbolTable(Offset, Stream); 6759 if (!MaybeCurrentBit) 6760 return MaybeCurrentBit.takeError(); 6761 uint64_t CurrentBit = MaybeCurrentBit.get(); 6762 6763 if (Error Err = Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID)) 6764 return Err; 6765 6766 SmallVector<uint64_t, 64> Record; 6767 6768 // Read all the records for this value table. 6769 SmallString<128> ValueName; 6770 6771 while (true) { 6772 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); 6773 if (!MaybeEntry) 6774 return MaybeEntry.takeError(); 6775 BitstreamEntry Entry = MaybeEntry.get(); 6776 6777 switch (Entry.Kind) { 6778 case BitstreamEntry::SubBlock: // Handled for us already. 6779 case BitstreamEntry::Error: 6780 return error("Malformed block"); 6781 case BitstreamEntry::EndBlock: 6782 // Done parsing VST, jump back to wherever we came from. 6783 if (Error JumpFailed = Stream.JumpToBit(CurrentBit)) 6784 return JumpFailed; 6785 return Error::success(); 6786 case BitstreamEntry::Record: 6787 // The interesting case. 6788 break; 6789 } 6790 6791 // Read a record. 6792 Record.clear(); 6793 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record); 6794 if (!MaybeRecord) 6795 return MaybeRecord.takeError(); 6796 switch (MaybeRecord.get()) { 6797 default: // Default behavior: ignore (e.g. VST_CODE_BBENTRY records). 6798 break; 6799 case bitc::VST_CODE_ENTRY: { // VST_CODE_ENTRY: [valueid, namechar x N] 6800 if (convertToString(Record, 1, ValueName)) 6801 return error("Invalid record"); 6802 unsigned ValueID = Record[0]; 6803 assert(!SourceFileName.empty()); 6804 auto VLI = ValueIdToLinkageMap.find(ValueID); 6805 assert(VLI != ValueIdToLinkageMap.end() && 6806 "No linkage found for VST entry?"); 6807 auto Linkage = VLI->second; 6808 setValueGUID(ValueID, ValueName, Linkage, SourceFileName); 6809 ValueName.clear(); 6810 break; 6811 } 6812 case bitc::VST_CODE_FNENTRY: { 6813 // VST_CODE_FNENTRY: [valueid, offset, namechar x N] 6814 if (convertToString(Record, 2, ValueName)) 6815 return error("Invalid record"); 6816 unsigned ValueID = Record[0]; 6817 assert(!SourceFileName.empty()); 6818 auto VLI = ValueIdToLinkageMap.find(ValueID); 6819 assert(VLI != ValueIdToLinkageMap.end() && 6820 "No linkage found for VST entry?"); 6821 auto Linkage = VLI->second; 6822 setValueGUID(ValueID, ValueName, Linkage, SourceFileName); 6823 ValueName.clear(); 6824 break; 6825 } 6826 case bitc::VST_CODE_COMBINED_ENTRY: { 6827 // VST_CODE_COMBINED_ENTRY: [valueid, refguid] 6828 unsigned ValueID = Record[0]; 6829 GlobalValue::GUID RefGUID = Record[1]; 6830 // The "original name", which is the second value of the pair will be 6831 // overriden later by a FS_COMBINED_ORIGINAL_NAME in the combined index. 6832 ValueIdToValueInfoMap[ValueID] = std::make_tuple( 6833 TheIndex.getOrInsertValueInfo(RefGUID), RefGUID, RefGUID); 6834 break; 6835 } 6836 } 6837 } 6838 } 6839 6840 // Parse just the blocks needed for building the index out of the module. 6841 // At the end of this routine the module Index is populated with a map 6842 // from global value id to GlobalValueSummary objects. 6843 Error ModuleSummaryIndexBitcodeReader::parseModule() { 6844 if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID)) 6845 return Err; 6846 6847 SmallVector<uint64_t, 64> Record; 6848 DenseMap<unsigned, GlobalValue::LinkageTypes> ValueIdToLinkageMap; 6849 unsigned ValueId = 0; 6850 6851 // Read the index for this module. 6852 while (true) { 6853 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance(); 6854 if (!MaybeEntry) 6855 return MaybeEntry.takeError(); 6856 llvm::BitstreamEntry Entry = MaybeEntry.get(); 6857 6858 switch (Entry.Kind) { 6859 case BitstreamEntry::Error: 6860 return error("Malformed block"); 6861 case BitstreamEntry::EndBlock: 6862 return Error::success(); 6863 6864 case BitstreamEntry::SubBlock: 6865 switch (Entry.ID) { 6866 default: // Skip unknown content. 6867 if (Error Err = Stream.SkipBlock()) 6868 return Err; 6869 break; 6870 case bitc::BLOCKINFO_BLOCK_ID: 6871 // Need to parse these to get abbrev ids (e.g. for VST) 6872 if (Error Err = readBlockInfo()) 6873 return Err; 6874 break; 6875 case bitc::VALUE_SYMTAB_BLOCK_ID: 6876 // Should have been parsed earlier via VSTOffset, unless there 6877 // is no summary section. 6878 assert(((SeenValueSymbolTable && VSTOffset > 0) || 6879 !SeenGlobalValSummary) && 6880 "Expected early VST parse via VSTOffset record"); 6881 if (Error Err = Stream.SkipBlock()) 6882 return Err; 6883 break; 6884 case bitc::GLOBALVAL_SUMMARY_BLOCK_ID: 6885 case bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID: 6886 // Add the module if it is a per-module index (has a source file name). 6887 if (!SourceFileName.empty()) 6888 addThisModule(); 6889 assert(!SeenValueSymbolTable && 6890 "Already read VST when parsing summary block?"); 6891 // We might not have a VST if there were no values in the 6892 // summary. An empty summary block generated when we are 6893 // performing ThinLTO compiles so we don't later invoke 6894 // the regular LTO process on them. 6895 if (VSTOffset > 0) { 6896 if (Error Err = parseValueSymbolTable(VSTOffset, ValueIdToLinkageMap)) 6897 return Err; 6898 SeenValueSymbolTable = true; 6899 } 6900 SeenGlobalValSummary = true; 6901 if (Error Err = parseEntireSummary(Entry.ID)) 6902 return Err; 6903 break; 6904 case bitc::MODULE_STRTAB_BLOCK_ID: 6905 if (Error Err = parseModuleStringTable()) 6906 return Err; 6907 break; 6908 } 6909 continue; 6910 6911 case BitstreamEntry::Record: { 6912 Record.clear(); 6913 Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record); 6914 if (!MaybeBitCode) 6915 return MaybeBitCode.takeError(); 6916 switch (MaybeBitCode.get()) { 6917 default: 6918 break; // Default behavior, ignore unknown content. 6919 case bitc::MODULE_CODE_VERSION: { 6920 if (Error Err = parseVersionRecord(Record).takeError()) 6921 return Err; 6922 break; 6923 } 6924 /// MODULE_CODE_SOURCE_FILENAME: [namechar x N] 6925 case bitc::MODULE_CODE_SOURCE_FILENAME: { 6926 SmallString<128> ValueName; 6927 if (convertToString(Record, 0, ValueName)) 6928 return error("Invalid record"); 6929 SourceFileName = ValueName.c_str(); 6930 break; 6931 } 6932 /// MODULE_CODE_HASH: [5*i32] 6933 case bitc::MODULE_CODE_HASH: { 6934 if (Record.size() != 5) 6935 return error("Invalid hash length " + Twine(Record.size()).str()); 6936 auto &Hash = getThisModule()->second; 6937 int Pos = 0; 6938 for (auto &Val : Record) { 6939 assert(!(Val >> 32) && "Unexpected high bits set"); 6940 Hash[Pos++] = Val; 6941 } 6942 break; 6943 } 6944 /// MODULE_CODE_VSTOFFSET: [offset] 6945 case bitc::MODULE_CODE_VSTOFFSET: 6946 if (Record.empty()) 6947 return error("Invalid record"); 6948 // Note that we subtract 1 here because the offset is relative to one 6949 // word before the start of the identification or module block, which 6950 // was historically always the start of the regular bitcode header. 6951 VSTOffset = Record[0] - 1; 6952 break; 6953 // v1 GLOBALVAR: [pointer type, isconst, initid, linkage, ...] 6954 // v1 FUNCTION: [type, callingconv, isproto, linkage, ...] 6955 // v1 ALIAS: [alias type, addrspace, aliasee val#, linkage, ...] 6956 // v2: [strtab offset, strtab size, v1] 6957 case bitc::MODULE_CODE_GLOBALVAR: 6958 case bitc::MODULE_CODE_FUNCTION: 6959 case bitc::MODULE_CODE_ALIAS: { 6960 StringRef Name; 6961 ArrayRef<uint64_t> GVRecord; 6962 std::tie(Name, GVRecord) = readNameFromStrtab(Record); 6963 if (GVRecord.size() <= 3) 6964 return error("Invalid record"); 6965 uint64_t RawLinkage = GVRecord[3]; 6966 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage); 6967 if (!UseStrtab) { 6968 ValueIdToLinkageMap[ValueId++] = Linkage; 6969 break; 6970 } 6971 6972 setValueGUID(ValueId++, Name, Linkage, SourceFileName); 6973 break; 6974 } 6975 } 6976 } 6977 continue; 6978 } 6979 } 6980 } 6981 6982 std::vector<ValueInfo> 6983 ModuleSummaryIndexBitcodeReader::makeRefList(ArrayRef<uint64_t> Record) { 6984 std::vector<ValueInfo> Ret; 6985 Ret.reserve(Record.size()); 6986 for (uint64_t RefValueId : Record) 6987 Ret.push_back(std::get<0>(getValueInfoFromValueId(RefValueId))); 6988 return Ret; 6989 } 6990 6991 std::vector<FunctionSummary::EdgeTy> 6992 ModuleSummaryIndexBitcodeReader::makeCallList(ArrayRef<uint64_t> Record, 6993 bool IsOldProfileFormat, 6994 bool HasProfile, bool HasRelBF) { 6995 std::vector<FunctionSummary::EdgeTy> Ret; 6996 Ret.reserve(Record.size()); 6997 for (unsigned I = 0, E = Record.size(); I != E; ++I) { 6998 CalleeInfo::HotnessType Hotness = CalleeInfo::HotnessType::Unknown; 6999 uint64_t RelBF = 0; 7000 ValueInfo Callee = std::get<0>(getValueInfoFromValueId(Record[I])); 7001 if (IsOldProfileFormat) { 7002 I += 1; // Skip old callsitecount field 7003 if (HasProfile) 7004 I += 1; // Skip old profilecount field 7005 } else if (HasProfile) 7006 Hotness = static_cast<CalleeInfo::HotnessType>(Record[++I]); 7007 else if (HasRelBF) 7008 RelBF = Record[++I]; 7009 Ret.push_back(FunctionSummary::EdgeTy{Callee, CalleeInfo(Hotness, RelBF)}); 7010 } 7011 return Ret; 7012 } 7013 7014 static void 7015 parseWholeProgramDevirtResolutionByArg(ArrayRef<uint64_t> Record, size_t &Slot, 7016 WholeProgramDevirtResolution &Wpd) { 7017 uint64_t ArgNum = Record[Slot++]; 7018 WholeProgramDevirtResolution::ByArg &B = 7019 Wpd.ResByArg[{Record.begin() + Slot, Record.begin() + Slot + ArgNum}]; 7020 Slot += ArgNum; 7021 7022 B.TheKind = 7023 static_cast<WholeProgramDevirtResolution::ByArg::Kind>(Record[Slot++]); 7024 B.Info = Record[Slot++]; 7025 B.Byte = Record[Slot++]; 7026 B.Bit = Record[Slot++]; 7027 } 7028 7029 static void parseWholeProgramDevirtResolution(ArrayRef<uint64_t> Record, 7030 StringRef Strtab, size_t &Slot, 7031 TypeIdSummary &TypeId) { 7032 uint64_t Id = Record[Slot++]; 7033 WholeProgramDevirtResolution &Wpd = TypeId.WPDRes[Id]; 7034 7035 Wpd.TheKind = static_cast<WholeProgramDevirtResolution::Kind>(Record[Slot++]); 7036 Wpd.SingleImplName = {Strtab.data() + Record[Slot], 7037 static_cast<size_t>(Record[Slot + 1])}; 7038 Slot += 2; 7039 7040 uint64_t ResByArgNum = Record[Slot++]; 7041 for (uint64_t I = 0; I != ResByArgNum; ++I) 7042 parseWholeProgramDevirtResolutionByArg(Record, Slot, Wpd); 7043 } 7044 7045 static void parseTypeIdSummaryRecord(ArrayRef<uint64_t> Record, 7046 StringRef Strtab, 7047 ModuleSummaryIndex &TheIndex) { 7048 size_t Slot = 0; 7049 TypeIdSummary &TypeId = TheIndex.getOrInsertTypeIdSummary( 7050 {Strtab.data() + Record[Slot], static_cast<size_t>(Record[Slot + 1])}); 7051 Slot += 2; 7052 7053 TypeId.TTRes.TheKind = static_cast<TypeTestResolution::Kind>(Record[Slot++]); 7054 TypeId.TTRes.SizeM1BitWidth = Record[Slot++]; 7055 TypeId.TTRes.AlignLog2 = Record[Slot++]; 7056 TypeId.TTRes.SizeM1 = Record[Slot++]; 7057 TypeId.TTRes.BitMask = Record[Slot++]; 7058 TypeId.TTRes.InlineBits = Record[Slot++]; 7059 7060 while (Slot < Record.size()) 7061 parseWholeProgramDevirtResolution(Record, Strtab, Slot, TypeId); 7062 } 7063 7064 std::vector<FunctionSummary::ParamAccess> 7065 ModuleSummaryIndexBitcodeReader::parseParamAccesses(ArrayRef<uint64_t> Record) { 7066 auto ReadRange = [&]() { 7067 APInt Lower(FunctionSummary::ParamAccess::RangeWidth, 7068 BitcodeReader::decodeSignRotatedValue(Record.front())); 7069 Record = Record.drop_front(); 7070 APInt Upper(FunctionSummary::ParamAccess::RangeWidth, 7071 BitcodeReader::decodeSignRotatedValue(Record.front())); 7072 Record = Record.drop_front(); 7073 ConstantRange Range{Lower, Upper}; 7074 assert(!Range.isFullSet()); 7075 assert(!Range.isUpperSignWrapped()); 7076 return Range; 7077 }; 7078 7079 std::vector<FunctionSummary::ParamAccess> PendingParamAccesses; 7080 while (!Record.empty()) { 7081 PendingParamAccesses.emplace_back(); 7082 FunctionSummary::ParamAccess &ParamAccess = PendingParamAccesses.back(); 7083 ParamAccess.ParamNo = Record.front(); 7084 Record = Record.drop_front(); 7085 ParamAccess.Use = ReadRange(); 7086 ParamAccess.Calls.resize(Record.front()); 7087 Record = Record.drop_front(); 7088 for (auto &Call : ParamAccess.Calls) { 7089 Call.ParamNo = Record.front(); 7090 Record = Record.drop_front(); 7091 Call.Callee = std::get<0>(getValueInfoFromValueId(Record.front())); 7092 Record = Record.drop_front(); 7093 Call.Offsets = ReadRange(); 7094 } 7095 } 7096 return PendingParamAccesses; 7097 } 7098 7099 void ModuleSummaryIndexBitcodeReader::parseTypeIdCompatibleVtableInfo( 7100 ArrayRef<uint64_t> Record, size_t &Slot, 7101 TypeIdCompatibleVtableInfo &TypeId) { 7102 uint64_t Offset = Record[Slot++]; 7103 ValueInfo Callee = std::get<0>(getValueInfoFromValueId(Record[Slot++])); 7104 TypeId.push_back({Offset, Callee}); 7105 } 7106 7107 void ModuleSummaryIndexBitcodeReader::parseTypeIdCompatibleVtableSummaryRecord( 7108 ArrayRef<uint64_t> Record) { 7109 size_t Slot = 0; 7110 TypeIdCompatibleVtableInfo &TypeId = 7111 TheIndex.getOrInsertTypeIdCompatibleVtableSummary( 7112 {Strtab.data() + Record[Slot], 7113 static_cast<size_t>(Record[Slot + 1])}); 7114 Slot += 2; 7115 7116 while (Slot < Record.size()) 7117 parseTypeIdCompatibleVtableInfo(Record, Slot, TypeId); 7118 } 7119 7120 static void setSpecialRefs(std::vector<ValueInfo> &Refs, unsigned ROCnt, 7121 unsigned WOCnt) { 7122 // Readonly and writeonly refs are in the end of the refs list. 7123 assert(ROCnt + WOCnt <= Refs.size()); 7124 unsigned FirstWORef = Refs.size() - WOCnt; 7125 unsigned RefNo = FirstWORef - ROCnt; 7126 for (; RefNo < FirstWORef; ++RefNo) 7127 Refs[RefNo].setReadOnly(); 7128 for (; RefNo < Refs.size(); ++RefNo) 7129 Refs[RefNo].setWriteOnly(); 7130 } 7131 7132 // Eagerly parse the entire summary block. This populates the GlobalValueSummary 7133 // objects in the index. 7134 Error ModuleSummaryIndexBitcodeReader::parseEntireSummary(unsigned ID) { 7135 if (Error Err = Stream.EnterSubBlock(ID)) 7136 return Err; 7137 SmallVector<uint64_t, 64> Record; 7138 7139 // Parse version 7140 { 7141 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); 7142 if (!MaybeEntry) 7143 return MaybeEntry.takeError(); 7144 BitstreamEntry Entry = MaybeEntry.get(); 7145 7146 if (Entry.Kind != BitstreamEntry::Record) 7147 return error("Invalid Summary Block: record for version expected"); 7148 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record); 7149 if (!MaybeRecord) 7150 return MaybeRecord.takeError(); 7151 if (MaybeRecord.get() != bitc::FS_VERSION) 7152 return error("Invalid Summary Block: version expected"); 7153 } 7154 const uint64_t Version = Record[0]; 7155 const bool IsOldProfileFormat = Version == 1; 7156 if (Version < 1 || Version > ModuleSummaryIndex::BitcodeSummaryVersion) 7157 return error("Invalid summary version " + Twine(Version) + 7158 ". Version should be in the range [1-" + 7159 Twine(ModuleSummaryIndex::BitcodeSummaryVersion) + 7160 "]."); 7161 Record.clear(); 7162 7163 // Keep around the last seen summary to be used when we see an optional 7164 // "OriginalName" attachement. 7165 GlobalValueSummary *LastSeenSummary = nullptr; 7166 GlobalValue::GUID LastSeenGUID = 0; 7167 7168 // We can expect to see any number of type ID information records before 7169 // each function summary records; these variables store the information 7170 // collected so far so that it can be used to create the summary object. 7171 std::vector<GlobalValue::GUID> PendingTypeTests; 7172 std::vector<FunctionSummary::VFuncId> PendingTypeTestAssumeVCalls, 7173 PendingTypeCheckedLoadVCalls; 7174 std::vector<FunctionSummary::ConstVCall> PendingTypeTestAssumeConstVCalls, 7175 PendingTypeCheckedLoadConstVCalls; 7176 std::vector<FunctionSummary::ParamAccess> PendingParamAccesses; 7177 7178 std::vector<CallsiteInfo> PendingCallsites; 7179 std::vector<AllocInfo> PendingAllocs; 7180 7181 while (true) { 7182 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); 7183 if (!MaybeEntry) 7184 return MaybeEntry.takeError(); 7185 BitstreamEntry Entry = MaybeEntry.get(); 7186 7187 switch (Entry.Kind) { 7188 case BitstreamEntry::SubBlock: // Handled for us already. 7189 case BitstreamEntry::Error: 7190 return error("Malformed block"); 7191 case BitstreamEntry::EndBlock: 7192 return Error::success(); 7193 case BitstreamEntry::Record: 7194 // The interesting case. 7195 break; 7196 } 7197 7198 // Read a record. The record format depends on whether this 7199 // is a per-module index or a combined index file. In the per-module 7200 // case the records contain the associated value's ID for correlation 7201 // with VST entries. In the combined index the correlation is done 7202 // via the bitcode offset of the summary records (which were saved 7203 // in the combined index VST entries). The records also contain 7204 // information used for ThinLTO renaming and importing. 7205 Record.clear(); 7206 Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record); 7207 if (!MaybeBitCode) 7208 return MaybeBitCode.takeError(); 7209 switch (unsigned BitCode = MaybeBitCode.get()) { 7210 default: // Default behavior: ignore. 7211 break; 7212 case bitc::FS_FLAGS: { // [flags] 7213 TheIndex.setFlags(Record[0]); 7214 break; 7215 } 7216 case bitc::FS_VALUE_GUID: { // [valueid, refguid] 7217 uint64_t ValueID = Record[0]; 7218 GlobalValue::GUID RefGUID = Record[1]; 7219 ValueIdToValueInfoMap[ValueID] = std::make_tuple( 7220 TheIndex.getOrInsertValueInfo(RefGUID), RefGUID, RefGUID); 7221 break; 7222 } 7223 // FS_PERMODULE: [valueid, flags, instcount, fflags, numrefs, 7224 // numrefs x valueid, n x (valueid)] 7225 // FS_PERMODULE_PROFILE: [valueid, flags, instcount, fflags, numrefs, 7226 // numrefs x valueid, 7227 // n x (valueid, hotness)] 7228 // FS_PERMODULE_RELBF: [valueid, flags, instcount, fflags, numrefs, 7229 // numrefs x valueid, 7230 // n x (valueid, relblockfreq)] 7231 case bitc::FS_PERMODULE: 7232 case bitc::FS_PERMODULE_RELBF: 7233 case bitc::FS_PERMODULE_PROFILE: { 7234 unsigned ValueID = Record[0]; 7235 uint64_t RawFlags = Record[1]; 7236 unsigned InstCount = Record[2]; 7237 uint64_t RawFunFlags = 0; 7238 unsigned NumRefs = Record[3]; 7239 unsigned NumRORefs = 0, NumWORefs = 0; 7240 int RefListStartIndex = 4; 7241 if (Version >= 4) { 7242 RawFunFlags = Record[3]; 7243 NumRefs = Record[4]; 7244 RefListStartIndex = 5; 7245 if (Version >= 5) { 7246 NumRORefs = Record[5]; 7247 RefListStartIndex = 6; 7248 if (Version >= 7) { 7249 NumWORefs = Record[6]; 7250 RefListStartIndex = 7; 7251 } 7252 } 7253 } 7254 7255 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version); 7256 // The module path string ref set in the summary must be owned by the 7257 // index's module string table. Since we don't have a module path 7258 // string table section in the per-module index, we create a single 7259 // module path string table entry with an empty (0) ID to take 7260 // ownership. 7261 int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs; 7262 assert(Record.size() >= RefListStartIndex + NumRefs && 7263 "Record size inconsistent with number of references"); 7264 std::vector<ValueInfo> Refs = makeRefList( 7265 ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs)); 7266 bool HasProfile = (BitCode == bitc::FS_PERMODULE_PROFILE); 7267 bool HasRelBF = (BitCode == bitc::FS_PERMODULE_RELBF); 7268 std::vector<FunctionSummary::EdgeTy> Calls = makeCallList( 7269 ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex), 7270 IsOldProfileFormat, HasProfile, HasRelBF); 7271 setSpecialRefs(Refs, NumRORefs, NumWORefs); 7272 auto VIAndOriginalGUID = getValueInfoFromValueId(ValueID); 7273 // In order to save memory, only record the memprof summaries if this is 7274 // the prevailing copy of a symbol. The linker doesn't resolve local 7275 // linkage values so don't check whether those are prevailing. 7276 auto LT = (GlobalValue::LinkageTypes)Flags.Linkage; 7277 if (IsPrevailing && 7278 !GlobalValue::isLocalLinkage(LT) && 7279 !IsPrevailing(std::get<2>(VIAndOriginalGUID))) { 7280 PendingCallsites.clear(); 7281 PendingAllocs.clear(); 7282 } 7283 auto FS = std::make_unique<FunctionSummary>( 7284 Flags, InstCount, getDecodedFFlags(RawFunFlags), /*EntryCount=*/0, 7285 std::move(Refs), std::move(Calls), std::move(PendingTypeTests), 7286 std::move(PendingTypeTestAssumeVCalls), 7287 std::move(PendingTypeCheckedLoadVCalls), 7288 std::move(PendingTypeTestAssumeConstVCalls), 7289 std::move(PendingTypeCheckedLoadConstVCalls), 7290 std::move(PendingParamAccesses), std::move(PendingCallsites), 7291 std::move(PendingAllocs)); 7292 FS->setModulePath(getThisModule()->first()); 7293 FS->setOriginalName(std::get<1>(VIAndOriginalGUID)); 7294 TheIndex.addGlobalValueSummary(std::get<0>(VIAndOriginalGUID), 7295 std::move(FS)); 7296 break; 7297 } 7298 // FS_ALIAS: [valueid, flags, valueid] 7299 // Aliases must be emitted (and parsed) after all FS_PERMODULE entries, as 7300 // they expect all aliasee summaries to be available. 7301 case bitc::FS_ALIAS: { 7302 unsigned ValueID = Record[0]; 7303 uint64_t RawFlags = Record[1]; 7304 unsigned AliaseeID = Record[2]; 7305 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version); 7306 auto AS = std::make_unique<AliasSummary>(Flags); 7307 // The module path string ref set in the summary must be owned by the 7308 // index's module string table. Since we don't have a module path 7309 // string table section in the per-module index, we create a single 7310 // module path string table entry with an empty (0) ID to take 7311 // ownership. 7312 AS->setModulePath(getThisModule()->first()); 7313 7314 auto AliaseeVI = std::get<0>(getValueInfoFromValueId(AliaseeID)); 7315 auto AliaseeInModule = TheIndex.findSummaryInModule(AliaseeVI, ModulePath); 7316 if (!AliaseeInModule) 7317 return error("Alias expects aliasee summary to be parsed"); 7318 AS->setAliasee(AliaseeVI, AliaseeInModule); 7319 7320 auto GUID = getValueInfoFromValueId(ValueID); 7321 AS->setOriginalName(std::get<1>(GUID)); 7322 TheIndex.addGlobalValueSummary(std::get<0>(GUID), std::move(AS)); 7323 break; 7324 } 7325 // FS_PERMODULE_GLOBALVAR_INIT_REFS: [valueid, flags, varflags, n x valueid] 7326 case bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS: { 7327 unsigned ValueID = Record[0]; 7328 uint64_t RawFlags = Record[1]; 7329 unsigned RefArrayStart = 2; 7330 GlobalVarSummary::GVarFlags GVF(/* ReadOnly */ false, 7331 /* WriteOnly */ false, 7332 /* Constant */ false, 7333 GlobalObject::VCallVisibilityPublic); 7334 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version); 7335 if (Version >= 5) { 7336 GVF = getDecodedGVarFlags(Record[2]); 7337 RefArrayStart = 3; 7338 } 7339 std::vector<ValueInfo> Refs = 7340 makeRefList(ArrayRef<uint64_t>(Record).slice(RefArrayStart)); 7341 auto FS = 7342 std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs)); 7343 FS->setModulePath(getThisModule()->first()); 7344 auto GUID = getValueInfoFromValueId(ValueID); 7345 FS->setOriginalName(std::get<1>(GUID)); 7346 TheIndex.addGlobalValueSummary(std::get<0>(GUID), std::move(FS)); 7347 break; 7348 } 7349 // FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS: [valueid, flags, varflags, 7350 // numrefs, numrefs x valueid, 7351 // n x (valueid, offset)] 7352 case bitc::FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS: { 7353 unsigned ValueID = Record[0]; 7354 uint64_t RawFlags = Record[1]; 7355 GlobalVarSummary::GVarFlags GVF = getDecodedGVarFlags(Record[2]); 7356 unsigned NumRefs = Record[3]; 7357 unsigned RefListStartIndex = 4; 7358 unsigned VTableListStartIndex = RefListStartIndex + NumRefs; 7359 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version); 7360 std::vector<ValueInfo> Refs = makeRefList( 7361 ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs)); 7362 VTableFuncList VTableFuncs; 7363 for (unsigned I = VTableListStartIndex, E = Record.size(); I != E; ++I) { 7364 ValueInfo Callee = std::get<0>(getValueInfoFromValueId(Record[I])); 7365 uint64_t Offset = Record[++I]; 7366 VTableFuncs.push_back({Callee, Offset}); 7367 } 7368 auto VS = 7369 std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs)); 7370 VS->setModulePath(getThisModule()->first()); 7371 VS->setVTableFuncs(VTableFuncs); 7372 auto GUID = getValueInfoFromValueId(ValueID); 7373 VS->setOriginalName(std::get<1>(GUID)); 7374 TheIndex.addGlobalValueSummary(std::get<0>(GUID), std::move(VS)); 7375 break; 7376 } 7377 // FS_COMBINED: [valueid, modid, flags, instcount, fflags, numrefs, 7378 // numrefs x valueid, n x (valueid)] 7379 // FS_COMBINED_PROFILE: [valueid, modid, flags, instcount, fflags, numrefs, 7380 // numrefs x valueid, n x (valueid, hotness)] 7381 case bitc::FS_COMBINED: 7382 case bitc::FS_COMBINED_PROFILE: { 7383 unsigned ValueID = Record[0]; 7384 uint64_t ModuleId = Record[1]; 7385 uint64_t RawFlags = Record[2]; 7386 unsigned InstCount = Record[3]; 7387 uint64_t RawFunFlags = 0; 7388 uint64_t EntryCount = 0; 7389 unsigned NumRefs = Record[4]; 7390 unsigned NumRORefs = 0, NumWORefs = 0; 7391 int RefListStartIndex = 5; 7392 7393 if (Version >= 4) { 7394 RawFunFlags = Record[4]; 7395 RefListStartIndex = 6; 7396 size_t NumRefsIndex = 5; 7397 if (Version >= 5) { 7398 unsigned NumRORefsOffset = 1; 7399 RefListStartIndex = 7; 7400 if (Version >= 6) { 7401 NumRefsIndex = 6; 7402 EntryCount = Record[5]; 7403 RefListStartIndex = 8; 7404 if (Version >= 7) { 7405 RefListStartIndex = 9; 7406 NumWORefs = Record[8]; 7407 NumRORefsOffset = 2; 7408 } 7409 } 7410 NumRORefs = Record[RefListStartIndex - NumRORefsOffset]; 7411 } 7412 NumRefs = Record[NumRefsIndex]; 7413 } 7414 7415 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version); 7416 int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs; 7417 assert(Record.size() >= RefListStartIndex + NumRefs && 7418 "Record size inconsistent with number of references"); 7419 std::vector<ValueInfo> Refs = makeRefList( 7420 ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs)); 7421 bool HasProfile = (BitCode == bitc::FS_COMBINED_PROFILE); 7422 std::vector<FunctionSummary::EdgeTy> Edges = makeCallList( 7423 ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex), 7424 IsOldProfileFormat, HasProfile, false); 7425 ValueInfo VI = std::get<0>(getValueInfoFromValueId(ValueID)); 7426 setSpecialRefs(Refs, NumRORefs, NumWORefs); 7427 auto FS = std::make_unique<FunctionSummary>( 7428 Flags, InstCount, getDecodedFFlags(RawFunFlags), EntryCount, 7429 std::move(Refs), std::move(Edges), std::move(PendingTypeTests), 7430 std::move(PendingTypeTestAssumeVCalls), 7431 std::move(PendingTypeCheckedLoadVCalls), 7432 std::move(PendingTypeTestAssumeConstVCalls), 7433 std::move(PendingTypeCheckedLoadConstVCalls), 7434 std::move(PendingParamAccesses), std::move(PendingCallsites), 7435 std::move(PendingAllocs)); 7436 LastSeenSummary = FS.get(); 7437 LastSeenGUID = VI.getGUID(); 7438 FS->setModulePath(ModuleIdMap[ModuleId]); 7439 TheIndex.addGlobalValueSummary(VI, std::move(FS)); 7440 break; 7441 } 7442 // FS_COMBINED_ALIAS: [valueid, modid, flags, valueid] 7443 // Aliases must be emitted (and parsed) after all FS_COMBINED entries, as 7444 // they expect all aliasee summaries to be available. 7445 case bitc::FS_COMBINED_ALIAS: { 7446 unsigned ValueID = Record[0]; 7447 uint64_t ModuleId = Record[1]; 7448 uint64_t RawFlags = Record[2]; 7449 unsigned AliaseeValueId = Record[3]; 7450 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version); 7451 auto AS = std::make_unique<AliasSummary>(Flags); 7452 LastSeenSummary = AS.get(); 7453 AS->setModulePath(ModuleIdMap[ModuleId]); 7454 7455 auto AliaseeVI = std::get<0>(getValueInfoFromValueId(AliaseeValueId)); 7456 auto AliaseeInModule = TheIndex.findSummaryInModule(AliaseeVI, AS->modulePath()); 7457 AS->setAliasee(AliaseeVI, AliaseeInModule); 7458 7459 ValueInfo VI = std::get<0>(getValueInfoFromValueId(ValueID)); 7460 LastSeenGUID = VI.getGUID(); 7461 TheIndex.addGlobalValueSummary(VI, std::move(AS)); 7462 break; 7463 } 7464 // FS_COMBINED_GLOBALVAR_INIT_REFS: [valueid, modid, flags, n x valueid] 7465 case bitc::FS_COMBINED_GLOBALVAR_INIT_REFS: { 7466 unsigned ValueID = Record[0]; 7467 uint64_t ModuleId = Record[1]; 7468 uint64_t RawFlags = Record[2]; 7469 unsigned RefArrayStart = 3; 7470 GlobalVarSummary::GVarFlags GVF(/* ReadOnly */ false, 7471 /* WriteOnly */ false, 7472 /* Constant */ false, 7473 GlobalObject::VCallVisibilityPublic); 7474 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version); 7475 if (Version >= 5) { 7476 GVF = getDecodedGVarFlags(Record[3]); 7477 RefArrayStart = 4; 7478 } 7479 std::vector<ValueInfo> Refs = 7480 makeRefList(ArrayRef<uint64_t>(Record).slice(RefArrayStart)); 7481 auto FS = 7482 std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs)); 7483 LastSeenSummary = FS.get(); 7484 FS->setModulePath(ModuleIdMap[ModuleId]); 7485 ValueInfo VI = std::get<0>(getValueInfoFromValueId(ValueID)); 7486 LastSeenGUID = VI.getGUID(); 7487 TheIndex.addGlobalValueSummary(VI, std::move(FS)); 7488 break; 7489 } 7490 // FS_COMBINED_ORIGINAL_NAME: [original_name] 7491 case bitc::FS_COMBINED_ORIGINAL_NAME: { 7492 uint64_t OriginalName = Record[0]; 7493 if (!LastSeenSummary) 7494 return error("Name attachment that does not follow a combined record"); 7495 LastSeenSummary->setOriginalName(OriginalName); 7496 TheIndex.addOriginalName(LastSeenGUID, OriginalName); 7497 // Reset the LastSeenSummary 7498 LastSeenSummary = nullptr; 7499 LastSeenGUID = 0; 7500 break; 7501 } 7502 case bitc::FS_TYPE_TESTS: 7503 assert(PendingTypeTests.empty()); 7504 llvm::append_range(PendingTypeTests, Record); 7505 break; 7506 7507 case bitc::FS_TYPE_TEST_ASSUME_VCALLS: 7508 assert(PendingTypeTestAssumeVCalls.empty()); 7509 for (unsigned I = 0; I != Record.size(); I += 2) 7510 PendingTypeTestAssumeVCalls.push_back({Record[I], Record[I+1]}); 7511 break; 7512 7513 case bitc::FS_TYPE_CHECKED_LOAD_VCALLS: 7514 assert(PendingTypeCheckedLoadVCalls.empty()); 7515 for (unsigned I = 0; I != Record.size(); I += 2) 7516 PendingTypeCheckedLoadVCalls.push_back({Record[I], Record[I+1]}); 7517 break; 7518 7519 case bitc::FS_TYPE_TEST_ASSUME_CONST_VCALL: 7520 PendingTypeTestAssumeConstVCalls.push_back( 7521 {{Record[0], Record[1]}, {Record.begin() + 2, Record.end()}}); 7522 break; 7523 7524 case bitc::FS_TYPE_CHECKED_LOAD_CONST_VCALL: 7525 PendingTypeCheckedLoadConstVCalls.push_back( 7526 {{Record[0], Record[1]}, {Record.begin() + 2, Record.end()}}); 7527 break; 7528 7529 case bitc::FS_CFI_FUNCTION_DEFS: { 7530 std::set<std::string> &CfiFunctionDefs = TheIndex.cfiFunctionDefs(); 7531 for (unsigned I = 0; I != Record.size(); I += 2) 7532 CfiFunctionDefs.insert( 7533 {Strtab.data() + Record[I], static_cast<size_t>(Record[I + 1])}); 7534 break; 7535 } 7536 7537 case bitc::FS_CFI_FUNCTION_DECLS: { 7538 std::set<std::string> &CfiFunctionDecls = TheIndex.cfiFunctionDecls(); 7539 for (unsigned I = 0; I != Record.size(); I += 2) 7540 CfiFunctionDecls.insert( 7541 {Strtab.data() + Record[I], static_cast<size_t>(Record[I + 1])}); 7542 break; 7543 } 7544 7545 case bitc::FS_TYPE_ID: 7546 parseTypeIdSummaryRecord(Record, Strtab, TheIndex); 7547 break; 7548 7549 case bitc::FS_TYPE_ID_METADATA: 7550 parseTypeIdCompatibleVtableSummaryRecord(Record); 7551 break; 7552 7553 case bitc::FS_BLOCK_COUNT: 7554 TheIndex.addBlockCount(Record[0]); 7555 break; 7556 7557 case bitc::FS_PARAM_ACCESS: { 7558 PendingParamAccesses = parseParamAccesses(Record); 7559 break; 7560 } 7561 7562 case bitc::FS_STACK_IDS: { // [n x stackid] 7563 // Save stack ids in the reader to consult when adding stack ids from the 7564 // lists in the stack node and alloc node entries. 7565 StackIds = ArrayRef<uint64_t>(Record); 7566 break; 7567 } 7568 7569 case bitc::FS_PERMODULE_CALLSITE_INFO: { 7570 unsigned ValueID = Record[0]; 7571 SmallVector<unsigned> StackIdList; 7572 for (auto R = Record.begin() + 1; R != Record.end(); R++) { 7573 assert(*R < StackIds.size()); 7574 StackIdList.push_back(TheIndex.addOrGetStackIdIndex(StackIds[*R])); 7575 } 7576 ValueInfo VI = std::get<0>(getValueInfoFromValueId(ValueID)); 7577 PendingCallsites.push_back(CallsiteInfo({VI, std::move(StackIdList)})); 7578 break; 7579 } 7580 7581 case bitc::FS_COMBINED_CALLSITE_INFO: { 7582 auto RecordIter = Record.begin(); 7583 unsigned ValueID = *RecordIter++; 7584 unsigned NumStackIds = *RecordIter++; 7585 unsigned NumVersions = *RecordIter++; 7586 assert(Record.size() == 3 + NumStackIds + NumVersions); 7587 SmallVector<unsigned> StackIdList; 7588 for (unsigned J = 0; J < NumStackIds; J++) { 7589 assert(*RecordIter < StackIds.size()); 7590 StackIdList.push_back( 7591 TheIndex.addOrGetStackIdIndex(StackIds[*RecordIter++])); 7592 } 7593 SmallVector<unsigned> Versions; 7594 for (unsigned J = 0; J < NumVersions; J++) 7595 Versions.push_back(*RecordIter++); 7596 ValueInfo VI = std::get<0>( 7597 getValueInfoFromValueId</*AllowNullValueInfo*/ true>(ValueID)); 7598 PendingCallsites.push_back( 7599 CallsiteInfo({VI, std::move(Versions), std::move(StackIdList)})); 7600 break; 7601 } 7602 7603 case bitc::FS_PERMODULE_ALLOC_INFO: { 7604 unsigned I = 0; 7605 std::vector<MIBInfo> MIBs; 7606 while (I < Record.size()) { 7607 assert(Record.size() - I >= 2); 7608 AllocationType AllocType = (AllocationType)Record[I++]; 7609 unsigned NumStackEntries = Record[I++]; 7610 assert(Record.size() - I >= NumStackEntries); 7611 SmallVector<unsigned> StackIdList; 7612 for (unsigned J = 0; J < NumStackEntries; J++) { 7613 assert(Record[I] < StackIds.size()); 7614 StackIdList.push_back( 7615 TheIndex.addOrGetStackIdIndex(StackIds[Record[I++]])); 7616 } 7617 MIBs.push_back(MIBInfo(AllocType, std::move(StackIdList))); 7618 } 7619 PendingAllocs.push_back(AllocInfo(std::move(MIBs))); 7620 break; 7621 } 7622 7623 case bitc::FS_COMBINED_ALLOC_INFO: { 7624 unsigned I = 0; 7625 std::vector<MIBInfo> MIBs; 7626 unsigned NumMIBs = Record[I++]; 7627 unsigned NumVersions = Record[I++]; 7628 unsigned MIBsRead = 0; 7629 while (MIBsRead++ < NumMIBs) { 7630 assert(Record.size() - I >= 2); 7631 AllocationType AllocType = (AllocationType)Record[I++]; 7632 unsigned NumStackEntries = Record[I++]; 7633 assert(Record.size() - I >= NumStackEntries); 7634 SmallVector<unsigned> StackIdList; 7635 for (unsigned J = 0; J < NumStackEntries; J++) { 7636 assert(Record[I] < StackIds.size()); 7637 StackIdList.push_back( 7638 TheIndex.addOrGetStackIdIndex(StackIds[Record[I++]])); 7639 } 7640 MIBs.push_back(MIBInfo(AllocType, std::move(StackIdList))); 7641 } 7642 assert(Record.size() - I >= NumVersions); 7643 SmallVector<uint8_t> Versions; 7644 for (unsigned J = 0; J < NumVersions; J++) 7645 Versions.push_back(Record[I++]); 7646 PendingAllocs.push_back( 7647 AllocInfo(std::move(Versions), std::move(MIBs))); 7648 break; 7649 } 7650 } 7651 } 7652 llvm_unreachable("Exit infinite loop"); 7653 } 7654 7655 // Parse the module string table block into the Index. 7656 // This populates the ModulePathStringTable map in the index. 7657 Error ModuleSummaryIndexBitcodeReader::parseModuleStringTable() { 7658 if (Error Err = Stream.EnterSubBlock(bitc::MODULE_STRTAB_BLOCK_ID)) 7659 return Err; 7660 7661 SmallVector<uint64_t, 64> Record; 7662 7663 SmallString<128> ModulePath; 7664 ModuleSummaryIndex::ModuleInfo *LastSeenModule = nullptr; 7665 7666 while (true) { 7667 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); 7668 if (!MaybeEntry) 7669 return MaybeEntry.takeError(); 7670 BitstreamEntry Entry = MaybeEntry.get(); 7671 7672 switch (Entry.Kind) { 7673 case BitstreamEntry::SubBlock: // Handled for us already. 7674 case BitstreamEntry::Error: 7675 return error("Malformed block"); 7676 case BitstreamEntry::EndBlock: 7677 return Error::success(); 7678 case BitstreamEntry::Record: 7679 // The interesting case. 7680 break; 7681 } 7682 7683 Record.clear(); 7684 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record); 7685 if (!MaybeRecord) 7686 return MaybeRecord.takeError(); 7687 switch (MaybeRecord.get()) { 7688 default: // Default behavior: ignore. 7689 break; 7690 case bitc::MST_CODE_ENTRY: { 7691 // MST_ENTRY: [modid, namechar x N] 7692 uint64_t ModuleId = Record[0]; 7693 7694 if (convertToString(Record, 1, ModulePath)) 7695 return error("Invalid record"); 7696 7697 LastSeenModule = TheIndex.addModule(ModulePath); 7698 ModuleIdMap[ModuleId] = LastSeenModule->first(); 7699 7700 ModulePath.clear(); 7701 break; 7702 } 7703 /// MST_CODE_HASH: [5*i32] 7704 case bitc::MST_CODE_HASH: { 7705 if (Record.size() != 5) 7706 return error("Invalid hash length " + Twine(Record.size()).str()); 7707 if (!LastSeenModule) 7708 return error("Invalid hash that does not follow a module path"); 7709 int Pos = 0; 7710 for (auto &Val : Record) { 7711 assert(!(Val >> 32) && "Unexpected high bits set"); 7712 LastSeenModule->second[Pos++] = Val; 7713 } 7714 // Reset LastSeenModule to avoid overriding the hash unexpectedly. 7715 LastSeenModule = nullptr; 7716 break; 7717 } 7718 } 7719 } 7720 llvm_unreachable("Exit infinite loop"); 7721 } 7722 7723 namespace { 7724 7725 // FIXME: This class is only here to support the transition to llvm::Error. It 7726 // will be removed once this transition is complete. Clients should prefer to 7727 // deal with the Error value directly, rather than converting to error_code. 7728 class BitcodeErrorCategoryType : public std::error_category { 7729 const char *name() const noexcept override { 7730 return "llvm.bitcode"; 7731 } 7732 7733 std::string message(int IE) const override { 7734 BitcodeError E = static_cast<BitcodeError>(IE); 7735 switch (E) { 7736 case BitcodeError::CorruptedBitcode: 7737 return "Corrupted bitcode"; 7738 } 7739 llvm_unreachable("Unknown error type!"); 7740 } 7741 }; 7742 7743 } // end anonymous namespace 7744 7745 const std::error_category &llvm::BitcodeErrorCategory() { 7746 static BitcodeErrorCategoryType ErrorCategory; 7747 return ErrorCategory; 7748 } 7749 7750 static Expected<StringRef> readBlobInRecord(BitstreamCursor &Stream, 7751 unsigned Block, unsigned RecordID) { 7752 if (Error Err = Stream.EnterSubBlock(Block)) 7753 return std::move(Err); 7754 7755 StringRef Strtab; 7756 while (true) { 7757 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance(); 7758 if (!MaybeEntry) 7759 return MaybeEntry.takeError(); 7760 llvm::BitstreamEntry Entry = MaybeEntry.get(); 7761 7762 switch (Entry.Kind) { 7763 case BitstreamEntry::EndBlock: 7764 return Strtab; 7765 7766 case BitstreamEntry::Error: 7767 return error("Malformed block"); 7768 7769 case BitstreamEntry::SubBlock: 7770 if (Error Err = Stream.SkipBlock()) 7771 return std::move(Err); 7772 break; 7773 7774 case BitstreamEntry::Record: 7775 StringRef Blob; 7776 SmallVector<uint64_t, 1> Record; 7777 Expected<unsigned> MaybeRecord = 7778 Stream.readRecord(Entry.ID, Record, &Blob); 7779 if (!MaybeRecord) 7780 return MaybeRecord.takeError(); 7781 if (MaybeRecord.get() == RecordID) 7782 Strtab = Blob; 7783 break; 7784 } 7785 } 7786 } 7787 7788 //===----------------------------------------------------------------------===// 7789 // External interface 7790 //===----------------------------------------------------------------------===// 7791 7792 Expected<std::vector<BitcodeModule>> 7793 llvm::getBitcodeModuleList(MemoryBufferRef Buffer) { 7794 auto FOrErr = getBitcodeFileContents(Buffer); 7795 if (!FOrErr) 7796 return FOrErr.takeError(); 7797 return std::move(FOrErr->Mods); 7798 } 7799 7800 Expected<BitcodeFileContents> 7801 llvm::getBitcodeFileContents(MemoryBufferRef Buffer) { 7802 Expected<BitstreamCursor> StreamOrErr = initStream(Buffer); 7803 if (!StreamOrErr) 7804 return StreamOrErr.takeError(); 7805 BitstreamCursor &Stream = *StreamOrErr; 7806 7807 BitcodeFileContents F; 7808 while (true) { 7809 uint64_t BCBegin = Stream.getCurrentByteNo(); 7810 7811 // We may be consuming bitcode from a client that leaves garbage at the end 7812 // of the bitcode stream (e.g. Apple's ar tool). If we are close enough to 7813 // the end that there cannot possibly be another module, stop looking. 7814 if (BCBegin + 8 >= Stream.getBitcodeBytes().size()) 7815 return F; 7816 7817 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance(); 7818 if (!MaybeEntry) 7819 return MaybeEntry.takeError(); 7820 llvm::BitstreamEntry Entry = MaybeEntry.get(); 7821 7822 switch (Entry.Kind) { 7823 case BitstreamEntry::EndBlock: 7824 case BitstreamEntry::Error: 7825 return error("Malformed block"); 7826 7827 case BitstreamEntry::SubBlock: { 7828 uint64_t IdentificationBit = -1ull; 7829 if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) { 7830 IdentificationBit = Stream.GetCurrentBitNo() - BCBegin * 8; 7831 if (Error Err = Stream.SkipBlock()) 7832 return std::move(Err); 7833 7834 { 7835 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance(); 7836 if (!MaybeEntry) 7837 return MaybeEntry.takeError(); 7838 Entry = MaybeEntry.get(); 7839 } 7840 7841 if (Entry.Kind != BitstreamEntry::SubBlock || 7842 Entry.ID != bitc::MODULE_BLOCK_ID) 7843 return error("Malformed block"); 7844 } 7845 7846 if (Entry.ID == bitc::MODULE_BLOCK_ID) { 7847 uint64_t ModuleBit = Stream.GetCurrentBitNo() - BCBegin * 8; 7848 if (Error Err = Stream.SkipBlock()) 7849 return std::move(Err); 7850 7851 F.Mods.push_back({Stream.getBitcodeBytes().slice( 7852 BCBegin, Stream.getCurrentByteNo() - BCBegin), 7853 Buffer.getBufferIdentifier(), IdentificationBit, 7854 ModuleBit}); 7855 continue; 7856 } 7857 7858 if (Entry.ID == bitc::STRTAB_BLOCK_ID) { 7859 Expected<StringRef> Strtab = 7860 readBlobInRecord(Stream, bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB); 7861 if (!Strtab) 7862 return Strtab.takeError(); 7863 // This string table is used by every preceding bitcode module that does 7864 // not have its own string table. A bitcode file may have multiple 7865 // string tables if it was created by binary concatenation, for example 7866 // with "llvm-cat -b". 7867 for (BitcodeModule &I : llvm::reverse(F.Mods)) { 7868 if (!I.Strtab.empty()) 7869 break; 7870 I.Strtab = *Strtab; 7871 } 7872 // Similarly, the string table is used by every preceding symbol table; 7873 // normally there will be just one unless the bitcode file was created 7874 // by binary concatenation. 7875 if (!F.Symtab.empty() && F.StrtabForSymtab.empty()) 7876 F.StrtabForSymtab = *Strtab; 7877 continue; 7878 } 7879 7880 if (Entry.ID == bitc::SYMTAB_BLOCK_ID) { 7881 Expected<StringRef> SymtabOrErr = 7882 readBlobInRecord(Stream, bitc::SYMTAB_BLOCK_ID, bitc::SYMTAB_BLOB); 7883 if (!SymtabOrErr) 7884 return SymtabOrErr.takeError(); 7885 7886 // We can expect the bitcode file to have multiple symbol tables if it 7887 // was created by binary concatenation. In that case we silently 7888 // ignore any subsequent symbol tables, which is fine because this is a 7889 // low level function. The client is expected to notice that the number 7890 // of modules in the symbol table does not match the number of modules 7891 // in the input file and regenerate the symbol table. 7892 if (F.Symtab.empty()) 7893 F.Symtab = *SymtabOrErr; 7894 continue; 7895 } 7896 7897 if (Error Err = Stream.SkipBlock()) 7898 return std::move(Err); 7899 continue; 7900 } 7901 case BitstreamEntry::Record: 7902 if (Error E = Stream.skipRecord(Entry.ID).takeError()) 7903 return std::move(E); 7904 continue; 7905 } 7906 } 7907 } 7908 7909 /// Get a lazy one-at-time loading module from bitcode. 7910 /// 7911 /// This isn't always used in a lazy context. In particular, it's also used by 7912 /// \a parseModule(). If this is truly lazy, then we need to eagerly pull 7913 /// in forward-referenced functions from block address references. 7914 /// 7915 /// \param[in] MaterializeAll Set to \c true if we should materialize 7916 /// everything. 7917 Expected<std::unique_ptr<Module>> 7918 BitcodeModule::getModuleImpl(LLVMContext &Context, bool MaterializeAll, 7919 bool ShouldLazyLoadMetadata, bool IsImporting, 7920 ParserCallbacks Callbacks) { 7921 BitstreamCursor Stream(Buffer); 7922 7923 std::string ProducerIdentification; 7924 if (IdentificationBit != -1ull) { 7925 if (Error JumpFailed = Stream.JumpToBit(IdentificationBit)) 7926 return std::move(JumpFailed); 7927 if (Error E = 7928 readIdentificationBlock(Stream).moveInto(ProducerIdentification)) 7929 return std::move(E); 7930 } 7931 7932 if (Error JumpFailed = Stream.JumpToBit(ModuleBit)) 7933 return std::move(JumpFailed); 7934 auto *R = new BitcodeReader(std::move(Stream), Strtab, ProducerIdentification, 7935 Context); 7936 7937 std::unique_ptr<Module> M = 7938 std::make_unique<Module>(ModuleIdentifier, Context); 7939 M->setMaterializer(R); 7940 7941 // Delay parsing Metadata if ShouldLazyLoadMetadata is true. 7942 if (Error Err = R->parseBitcodeInto(M.get(), ShouldLazyLoadMetadata, 7943 IsImporting, Callbacks)) 7944 return std::move(Err); 7945 7946 if (MaterializeAll) { 7947 // Read in the entire module, and destroy the BitcodeReader. 7948 if (Error Err = M->materializeAll()) 7949 return std::move(Err); 7950 } else { 7951 // Resolve forward references from blockaddresses. 7952 if (Error Err = R->materializeForwardReferencedFunctions()) 7953 return std::move(Err); 7954 } 7955 return std::move(M); 7956 } 7957 7958 Expected<std::unique_ptr<Module>> 7959 BitcodeModule::getLazyModule(LLVMContext &Context, bool ShouldLazyLoadMetadata, 7960 bool IsImporting, ParserCallbacks Callbacks) { 7961 return getModuleImpl(Context, false, ShouldLazyLoadMetadata, IsImporting, 7962 Callbacks); 7963 } 7964 7965 // Parse the specified bitcode buffer and merge the index into CombinedIndex. 7966 // We don't use ModuleIdentifier here because the client may need to control the 7967 // module path used in the combined summary (e.g. when reading summaries for 7968 // regular LTO modules). 7969 Error BitcodeModule::readSummary( 7970 ModuleSummaryIndex &CombinedIndex, StringRef ModulePath, 7971 std::function<bool(GlobalValue::GUID)> IsPrevailing) { 7972 BitstreamCursor Stream(Buffer); 7973 if (Error JumpFailed = Stream.JumpToBit(ModuleBit)) 7974 return JumpFailed; 7975 7976 ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, CombinedIndex, 7977 ModulePath, IsPrevailing); 7978 return R.parseModule(); 7979 } 7980 7981 // Parse the specified bitcode buffer, returning the function info index. 7982 Expected<std::unique_ptr<ModuleSummaryIndex>> BitcodeModule::getSummary() { 7983 BitstreamCursor Stream(Buffer); 7984 if (Error JumpFailed = Stream.JumpToBit(ModuleBit)) 7985 return std::move(JumpFailed); 7986 7987 auto Index = std::make_unique<ModuleSummaryIndex>(/*HaveGVs=*/false); 7988 ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, *Index, 7989 ModuleIdentifier, 0); 7990 7991 if (Error Err = R.parseModule()) 7992 return std::move(Err); 7993 7994 return std::move(Index); 7995 } 7996 7997 static Expected<std::pair<bool, bool>> 7998 getEnableSplitLTOUnitAndUnifiedFlag(BitstreamCursor &Stream, 7999 unsigned ID, 8000 BitcodeLTOInfo <OInfo) { 8001 if (Error Err = Stream.EnterSubBlock(ID)) 8002 return std::move(Err); 8003 SmallVector<uint64_t, 64> Record; 8004 8005 while (true) { 8006 BitstreamEntry Entry; 8007 std::pair<bool, bool> Result = {false,false}; 8008 if (Error E = Stream.advanceSkippingSubblocks().moveInto(Entry)) 8009 return std::move(E); 8010 8011 switch (Entry.Kind) { 8012 case BitstreamEntry::SubBlock: // Handled for us already. 8013 case BitstreamEntry::Error: 8014 return error("Malformed block"); 8015 case BitstreamEntry::EndBlock: { 8016 // If no flags record found, set both flags to false. 8017 return Result; 8018 } 8019 case BitstreamEntry::Record: 8020 // The interesting case. 8021 break; 8022 } 8023 8024 // Look for the FS_FLAGS record. 8025 Record.clear(); 8026 Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record); 8027 if (!MaybeBitCode) 8028 return MaybeBitCode.takeError(); 8029 switch (MaybeBitCode.get()) { 8030 default: // Default behavior: ignore. 8031 break; 8032 case bitc::FS_FLAGS: { // [flags] 8033 uint64_t Flags = Record[0]; 8034 // Scan flags. 8035 assert(Flags <= 0x2ff && "Unexpected bits in flag"); 8036 8037 bool EnableSplitLTOUnit = Flags & 0x8; 8038 bool UnifiedLTO = Flags & 0x200; 8039 Result = {EnableSplitLTOUnit, UnifiedLTO}; 8040 8041 return Result; 8042 } 8043 } 8044 } 8045 llvm_unreachable("Exit infinite loop"); 8046 } 8047 8048 // Check if the given bitcode buffer contains a global value summary block. 8049 Expected<BitcodeLTOInfo> BitcodeModule::getLTOInfo() { 8050 BitstreamCursor Stream(Buffer); 8051 if (Error JumpFailed = Stream.JumpToBit(ModuleBit)) 8052 return std::move(JumpFailed); 8053 8054 if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID)) 8055 return std::move(Err); 8056 8057 while (true) { 8058 llvm::BitstreamEntry Entry; 8059 if (Error E = Stream.advance().moveInto(Entry)) 8060 return std::move(E); 8061 8062 switch (Entry.Kind) { 8063 case BitstreamEntry::Error: 8064 return error("Malformed block"); 8065 case BitstreamEntry::EndBlock: 8066 return BitcodeLTOInfo{/*IsThinLTO=*/false, /*HasSummary=*/false, 8067 /*EnableSplitLTOUnit=*/false, /*UnifiedLTO=*/false}; 8068 8069 case BitstreamEntry::SubBlock: 8070 if (Entry.ID == bitc::GLOBALVAL_SUMMARY_BLOCK_ID) { 8071 BitcodeLTOInfo LTOInfo; 8072 Expected<std::pair<bool, bool>> Flags = 8073 getEnableSplitLTOUnitAndUnifiedFlag(Stream, Entry.ID, LTOInfo); 8074 if (!Flags) 8075 return Flags.takeError(); 8076 std::tie(LTOInfo.EnableSplitLTOUnit, LTOInfo.UnifiedLTO) = Flags.get(); 8077 LTOInfo.IsThinLTO = true; 8078 LTOInfo.HasSummary = true; 8079 return LTOInfo; 8080 } 8081 8082 if (Entry.ID == bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID) { 8083 BitcodeLTOInfo LTOInfo; 8084 Expected<std::pair<bool, bool>> Flags = 8085 getEnableSplitLTOUnitAndUnifiedFlag(Stream, Entry.ID, LTOInfo); 8086 if (!Flags) 8087 return Flags.takeError(); 8088 std::tie(LTOInfo.EnableSplitLTOUnit, LTOInfo.UnifiedLTO) = Flags.get(); 8089 LTOInfo.IsThinLTO = false; 8090 LTOInfo.HasSummary = true; 8091 return LTOInfo; 8092 } 8093 8094 // Ignore other sub-blocks. 8095 if (Error Err = Stream.SkipBlock()) 8096 return std::move(Err); 8097 continue; 8098 8099 case BitstreamEntry::Record: 8100 if (Expected<unsigned> StreamFailed = Stream.skipRecord(Entry.ID)) 8101 continue; 8102 else 8103 return StreamFailed.takeError(); 8104 } 8105 } 8106 } 8107 8108 static Expected<BitcodeModule> getSingleModule(MemoryBufferRef Buffer) { 8109 Expected<std::vector<BitcodeModule>> MsOrErr = getBitcodeModuleList(Buffer); 8110 if (!MsOrErr) 8111 return MsOrErr.takeError(); 8112 8113 if (MsOrErr->size() != 1) 8114 return error("Expected a single module"); 8115 8116 return (*MsOrErr)[0]; 8117 } 8118 8119 Expected<std::unique_ptr<Module>> 8120 llvm::getLazyBitcodeModule(MemoryBufferRef Buffer, LLVMContext &Context, 8121 bool ShouldLazyLoadMetadata, bool IsImporting, 8122 ParserCallbacks Callbacks) { 8123 Expected<BitcodeModule> BM = getSingleModule(Buffer); 8124 if (!BM) 8125 return BM.takeError(); 8126 8127 return BM->getLazyModule(Context, ShouldLazyLoadMetadata, IsImporting, 8128 Callbacks); 8129 } 8130 8131 Expected<std::unique_ptr<Module>> llvm::getOwningLazyBitcodeModule( 8132 std::unique_ptr<MemoryBuffer> &&Buffer, LLVMContext &Context, 8133 bool ShouldLazyLoadMetadata, bool IsImporting, ParserCallbacks Callbacks) { 8134 auto MOrErr = getLazyBitcodeModule(*Buffer, Context, ShouldLazyLoadMetadata, 8135 IsImporting, Callbacks); 8136 if (MOrErr) 8137 (*MOrErr)->setOwnedMemoryBuffer(std::move(Buffer)); 8138 return MOrErr; 8139 } 8140 8141 Expected<std::unique_ptr<Module>> 8142 BitcodeModule::parseModule(LLVMContext &Context, ParserCallbacks Callbacks) { 8143 return getModuleImpl(Context, true, false, false, Callbacks); 8144 // TODO: Restore the use-lists to the in-memory state when the bitcode was 8145 // written. We must defer until the Module has been fully materialized. 8146 } 8147 8148 Expected<std::unique_ptr<Module>> 8149 llvm::parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context, 8150 ParserCallbacks Callbacks) { 8151 Expected<BitcodeModule> BM = getSingleModule(Buffer); 8152 if (!BM) 8153 return BM.takeError(); 8154 8155 return BM->parseModule(Context, Callbacks); 8156 } 8157 8158 Expected<std::string> llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer) { 8159 Expected<BitstreamCursor> StreamOrErr = initStream(Buffer); 8160 if (!StreamOrErr) 8161 return StreamOrErr.takeError(); 8162 8163 return readTriple(*StreamOrErr); 8164 } 8165 8166 Expected<bool> llvm::isBitcodeContainingObjCCategory(MemoryBufferRef Buffer) { 8167 Expected<BitstreamCursor> StreamOrErr = initStream(Buffer); 8168 if (!StreamOrErr) 8169 return StreamOrErr.takeError(); 8170 8171 return hasObjCCategory(*StreamOrErr); 8172 } 8173 8174 Expected<std::string> llvm::getBitcodeProducerString(MemoryBufferRef Buffer) { 8175 Expected<BitstreamCursor> StreamOrErr = initStream(Buffer); 8176 if (!StreamOrErr) 8177 return StreamOrErr.takeError(); 8178 8179 return readIdentificationCode(*StreamOrErr); 8180 } 8181 8182 Error llvm::readModuleSummaryIndex(MemoryBufferRef Buffer, 8183 ModuleSummaryIndex &CombinedIndex) { 8184 Expected<BitcodeModule> BM = getSingleModule(Buffer); 8185 if (!BM) 8186 return BM.takeError(); 8187 8188 return BM->readSummary(CombinedIndex, BM->getModuleIdentifier()); 8189 } 8190 8191 Expected<std::unique_ptr<ModuleSummaryIndex>> 8192 llvm::getModuleSummaryIndex(MemoryBufferRef Buffer) { 8193 Expected<BitcodeModule> BM = getSingleModule(Buffer); 8194 if (!BM) 8195 return BM.takeError(); 8196 8197 return BM->getSummary(); 8198 } 8199 8200 Expected<BitcodeLTOInfo> llvm::getBitcodeLTOInfo(MemoryBufferRef Buffer) { 8201 Expected<BitcodeModule> BM = getSingleModule(Buffer); 8202 if (!BM) 8203 return BM.takeError(); 8204 8205 return BM->getLTOInfo(); 8206 } 8207 8208 Expected<std::unique_ptr<ModuleSummaryIndex>> 8209 llvm::getModuleSummaryIndexForFile(StringRef Path, 8210 bool IgnoreEmptyThinLTOIndexFile) { 8211 ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr = 8212 MemoryBuffer::getFileOrSTDIN(Path); 8213 if (!FileOrErr) 8214 return errorCodeToError(FileOrErr.getError()); 8215 if (IgnoreEmptyThinLTOIndexFile && !(*FileOrErr)->getBufferSize()) 8216 return nullptr; 8217 return getModuleSummaryIndex(**FileOrErr); 8218 } 8219