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