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