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