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