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