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