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