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 Type *ResolverFTy = 2283 GlobalIFunc::getResolverFunctionType(GI->getValueType()); 2284 // Transparently fix up the type for compatiblity with older bitcode 2285 GI->setResolver( 2286 ConstantExpr::getBitCast(C, ResolverFTy->getPointerTo())); 2287 } else { 2288 return error("Expected an alias or an ifunc"); 2289 } 2290 } 2291 IndirectSymbolInitWorklist.pop_back(); 2292 } 2293 2294 while (!FunctionOperandWorklist.empty()) { 2295 FunctionOperandInfo &Info = FunctionOperandWorklist.back(); 2296 if (Info.PersonalityFn) { 2297 unsigned ValID = Info.PersonalityFn - 1; 2298 if (ValID < ValueList.size()) { 2299 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID])) 2300 Info.F->setPersonalityFn(C); 2301 else 2302 return error("Expected a constant"); 2303 Info.PersonalityFn = 0; 2304 } 2305 } 2306 if (Info.Prefix) { 2307 unsigned ValID = Info.Prefix - 1; 2308 if (ValID < ValueList.size()) { 2309 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID])) 2310 Info.F->setPrefixData(C); 2311 else 2312 return error("Expected a constant"); 2313 Info.Prefix = 0; 2314 } 2315 } 2316 if (Info.Prologue) { 2317 unsigned ValID = Info.Prologue - 1; 2318 if (ValID < ValueList.size()) { 2319 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID])) 2320 Info.F->setPrologueData(C); 2321 else 2322 return error("Expected a constant"); 2323 Info.Prologue = 0; 2324 } 2325 } 2326 if (Info.PersonalityFn || Info.Prefix || Info.Prologue) 2327 FunctionOperands.push_back(Info); 2328 FunctionOperandWorklist.pop_back(); 2329 } 2330 2331 return Error::success(); 2332 } 2333 2334 APInt llvm::readWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) { 2335 SmallVector<uint64_t, 8> Words(Vals.size()); 2336 transform(Vals, Words.begin(), 2337 BitcodeReader::decodeSignRotatedValue); 2338 2339 return APInt(TypeBits, Words); 2340 } 2341 2342 Error BitcodeReader::parseConstants() { 2343 if (Error Err = Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID)) 2344 return Err; 2345 2346 SmallVector<uint64_t, 64> Record; 2347 2348 // Read all the records for this value table. 2349 Type *CurTy = Type::getInt32Ty(Context); 2350 unsigned NextCstNo = ValueList.size(); 2351 2352 struct DelayedShufTy { 2353 VectorType *OpTy; 2354 VectorType *RTy; 2355 uint64_t Op0Idx; 2356 uint64_t Op1Idx; 2357 uint64_t Op2Idx; 2358 unsigned CstNo; 2359 }; 2360 std::vector<DelayedShufTy> DelayedShuffles; 2361 struct DelayedSelTy { 2362 Type *OpTy; 2363 uint64_t Op0Idx; 2364 uint64_t Op1Idx; 2365 uint64_t Op2Idx; 2366 unsigned CstNo; 2367 }; 2368 std::vector<DelayedSelTy> DelayedSelectors; 2369 2370 while (true) { 2371 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); 2372 if (!MaybeEntry) 2373 return MaybeEntry.takeError(); 2374 BitstreamEntry Entry = MaybeEntry.get(); 2375 2376 switch (Entry.Kind) { 2377 case BitstreamEntry::SubBlock: // Handled for us already. 2378 case BitstreamEntry::Error: 2379 return error("Malformed block"); 2380 case BitstreamEntry::EndBlock: 2381 // Once all the constants have been read, go through and resolve forward 2382 // references. 2383 // 2384 // We have to treat shuffles specially because they don't have three 2385 // operands anymore. We need to convert the shuffle mask into an array, 2386 // and we can't convert a forward reference. 2387 for (auto &DelayedShuffle : DelayedShuffles) { 2388 VectorType *OpTy = DelayedShuffle.OpTy; 2389 VectorType *RTy = DelayedShuffle.RTy; 2390 uint64_t Op0Idx = DelayedShuffle.Op0Idx; 2391 uint64_t Op1Idx = DelayedShuffle.Op1Idx; 2392 uint64_t Op2Idx = DelayedShuffle.Op2Idx; 2393 uint64_t CstNo = DelayedShuffle.CstNo; 2394 Constant *Op0 = ValueList.getConstantFwdRef(Op0Idx, OpTy); 2395 Constant *Op1 = ValueList.getConstantFwdRef(Op1Idx, OpTy); 2396 Type *ShufTy = 2397 VectorType::get(Type::getInt32Ty(Context), RTy->getElementCount()); 2398 Constant *Op2 = ValueList.getConstantFwdRef(Op2Idx, ShufTy); 2399 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2)) 2400 return error("Invalid shufflevector operands"); 2401 SmallVector<int, 16> Mask; 2402 ShuffleVectorInst::getShuffleMask(Op2, Mask); 2403 Value *V = ConstantExpr::getShuffleVector(Op0, Op1, Mask); 2404 ValueList.assignValue(V, CstNo); 2405 } 2406 for (auto &DelayedSelector : DelayedSelectors) { 2407 Type *OpTy = DelayedSelector.OpTy; 2408 Type *SelectorTy = Type::getInt1Ty(Context); 2409 uint64_t Op0Idx = DelayedSelector.Op0Idx; 2410 uint64_t Op1Idx = DelayedSelector.Op1Idx; 2411 uint64_t Op2Idx = DelayedSelector.Op2Idx; 2412 uint64_t CstNo = DelayedSelector.CstNo; 2413 Constant *Op1 = ValueList.getConstantFwdRef(Op1Idx, OpTy); 2414 Constant *Op2 = ValueList.getConstantFwdRef(Op2Idx, OpTy); 2415 // The selector might be an i1 or an <n x i1> 2416 // Get the type from the ValueList before getting a forward ref. 2417 if (VectorType *VTy = dyn_cast<VectorType>(OpTy)) { 2418 Value *V = ValueList[Op0Idx]; 2419 assert(V); 2420 if (SelectorTy != V->getType()) 2421 SelectorTy = VectorType::get(SelectorTy, VTy->getElementCount()); 2422 } 2423 Constant *Op0 = ValueList.getConstantFwdRef(Op0Idx, SelectorTy); 2424 Value *V = ConstantExpr::getSelect(Op0, Op1, Op2); 2425 ValueList.assignValue(V, CstNo); 2426 } 2427 2428 if (NextCstNo != ValueList.size()) 2429 return error("Invalid constant reference"); 2430 2431 ValueList.resolveConstantForwardRefs(); 2432 return Error::success(); 2433 case BitstreamEntry::Record: 2434 // The interesting case. 2435 break; 2436 } 2437 2438 // Read a record. 2439 Record.clear(); 2440 Type *VoidType = Type::getVoidTy(Context); 2441 Value *V = nullptr; 2442 Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record); 2443 if (!MaybeBitCode) 2444 return MaybeBitCode.takeError(); 2445 switch (unsigned BitCode = MaybeBitCode.get()) { 2446 default: // Default behavior: unknown constant 2447 case bitc::CST_CODE_UNDEF: // UNDEF 2448 V = UndefValue::get(CurTy); 2449 break; 2450 case bitc::CST_CODE_POISON: // POISON 2451 V = PoisonValue::get(CurTy); 2452 break; 2453 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid] 2454 if (Record.empty()) 2455 return error("Invalid record"); 2456 if (Record[0] >= TypeList.size() || !TypeList[Record[0]]) 2457 return error("Invalid record"); 2458 if (TypeList[Record[0]] == VoidType) 2459 return error("Invalid constant type"); 2460 CurTy = TypeList[Record[0]]; 2461 continue; // Skip the ValueList manipulation. 2462 case bitc::CST_CODE_NULL: // NULL 2463 if (CurTy->isVoidTy() || CurTy->isFunctionTy() || CurTy->isLabelTy()) 2464 return error("Invalid type for a constant null value"); 2465 V = Constant::getNullValue(CurTy); 2466 break; 2467 case bitc::CST_CODE_INTEGER: // INTEGER: [intval] 2468 if (!CurTy->isIntegerTy() || Record.empty()) 2469 return error("Invalid record"); 2470 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0])); 2471 break; 2472 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval] 2473 if (!CurTy->isIntegerTy() || Record.empty()) 2474 return error("Invalid record"); 2475 2476 APInt VInt = 2477 readWideAPInt(Record, cast<IntegerType>(CurTy)->getBitWidth()); 2478 V = ConstantInt::get(Context, VInt); 2479 2480 break; 2481 } 2482 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval] 2483 if (Record.empty()) 2484 return error("Invalid record"); 2485 if (CurTy->isHalfTy()) 2486 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf(), 2487 APInt(16, (uint16_t)Record[0]))); 2488 else if (CurTy->isBFloatTy()) 2489 V = ConstantFP::get(Context, APFloat(APFloat::BFloat(), 2490 APInt(16, (uint32_t)Record[0]))); 2491 else if (CurTy->isFloatTy()) 2492 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle(), 2493 APInt(32, (uint32_t)Record[0]))); 2494 else if (CurTy->isDoubleTy()) 2495 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble(), 2496 APInt(64, Record[0]))); 2497 else if (CurTy->isX86_FP80Ty()) { 2498 // Bits are not stored the same way as a normal i80 APInt, compensate. 2499 uint64_t Rearrange[2]; 2500 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16); 2501 Rearrange[1] = Record[0] >> 48; 2502 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended(), 2503 APInt(80, Rearrange))); 2504 } else if (CurTy->isFP128Ty()) 2505 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad(), 2506 APInt(128, Record))); 2507 else if (CurTy->isPPC_FP128Ty()) 2508 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble(), 2509 APInt(128, Record))); 2510 else 2511 V = UndefValue::get(CurTy); 2512 break; 2513 } 2514 2515 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number] 2516 if (Record.empty()) 2517 return error("Invalid record"); 2518 2519 unsigned Size = Record.size(); 2520 SmallVector<Constant*, 16> Elts; 2521 2522 if (StructType *STy = dyn_cast<StructType>(CurTy)) { 2523 for (unsigned i = 0; i != Size; ++i) 2524 Elts.push_back(ValueList.getConstantFwdRef(Record[i], 2525 STy->getElementType(i))); 2526 V = ConstantStruct::get(STy, Elts); 2527 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) { 2528 Type *EltTy = ATy->getElementType(); 2529 for (unsigned i = 0; i != Size; ++i) 2530 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy)); 2531 V = ConstantArray::get(ATy, Elts); 2532 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) { 2533 Type *EltTy = VTy->getElementType(); 2534 for (unsigned i = 0; i != Size; ++i) 2535 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy)); 2536 V = ConstantVector::get(Elts); 2537 } else { 2538 V = UndefValue::get(CurTy); 2539 } 2540 break; 2541 } 2542 case bitc::CST_CODE_STRING: // STRING: [values] 2543 case bitc::CST_CODE_CSTRING: { // CSTRING: [values] 2544 if (Record.empty()) 2545 return error("Invalid record"); 2546 2547 SmallString<16> Elts(Record.begin(), Record.end()); 2548 V = ConstantDataArray::getString(Context, Elts, 2549 BitCode == bitc::CST_CODE_CSTRING); 2550 break; 2551 } 2552 case bitc::CST_CODE_DATA: {// DATA: [n x value] 2553 if (Record.empty()) 2554 return error("Invalid record"); 2555 2556 Type *EltTy; 2557 if (auto *Array = dyn_cast<ArrayType>(CurTy)) 2558 EltTy = Array->getElementType(); 2559 else 2560 EltTy = cast<VectorType>(CurTy)->getElementType(); 2561 if (EltTy->isIntegerTy(8)) { 2562 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end()); 2563 if (isa<VectorType>(CurTy)) 2564 V = ConstantDataVector::get(Context, Elts); 2565 else 2566 V = ConstantDataArray::get(Context, Elts); 2567 } else if (EltTy->isIntegerTy(16)) { 2568 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end()); 2569 if (isa<VectorType>(CurTy)) 2570 V = ConstantDataVector::get(Context, Elts); 2571 else 2572 V = ConstantDataArray::get(Context, Elts); 2573 } else if (EltTy->isIntegerTy(32)) { 2574 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end()); 2575 if (isa<VectorType>(CurTy)) 2576 V = ConstantDataVector::get(Context, Elts); 2577 else 2578 V = ConstantDataArray::get(Context, Elts); 2579 } else if (EltTy->isIntegerTy(64)) { 2580 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end()); 2581 if (isa<VectorType>(CurTy)) 2582 V = ConstantDataVector::get(Context, Elts); 2583 else 2584 V = ConstantDataArray::get(Context, Elts); 2585 } else if (EltTy->isHalfTy()) { 2586 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end()); 2587 if (isa<VectorType>(CurTy)) 2588 V = ConstantDataVector::getFP(EltTy, Elts); 2589 else 2590 V = ConstantDataArray::getFP(EltTy, Elts); 2591 } else if (EltTy->isBFloatTy()) { 2592 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end()); 2593 if (isa<VectorType>(CurTy)) 2594 V = ConstantDataVector::getFP(EltTy, Elts); 2595 else 2596 V = ConstantDataArray::getFP(EltTy, Elts); 2597 } else if (EltTy->isFloatTy()) { 2598 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end()); 2599 if (isa<VectorType>(CurTy)) 2600 V = ConstantDataVector::getFP(EltTy, Elts); 2601 else 2602 V = ConstantDataArray::getFP(EltTy, Elts); 2603 } else if (EltTy->isDoubleTy()) { 2604 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end()); 2605 if (isa<VectorType>(CurTy)) 2606 V = ConstantDataVector::getFP(EltTy, Elts); 2607 else 2608 V = ConstantDataArray::getFP(EltTy, Elts); 2609 } else { 2610 return error("Invalid type for value"); 2611 } 2612 break; 2613 } 2614 case bitc::CST_CODE_CE_UNOP: { // CE_UNOP: [opcode, opval] 2615 if (Record.size() < 2) 2616 return error("Invalid record"); 2617 int Opc = getDecodedUnaryOpcode(Record[0], CurTy); 2618 if (Opc < 0) { 2619 V = UndefValue::get(CurTy); // Unknown unop. 2620 } else { 2621 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy); 2622 unsigned Flags = 0; 2623 V = ConstantExpr::get(Opc, LHS, Flags); 2624 } 2625 break; 2626 } 2627 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval] 2628 if (Record.size() < 3) 2629 return error("Invalid record"); 2630 int Opc = getDecodedBinaryOpcode(Record[0], CurTy); 2631 if (Opc < 0) { 2632 V = UndefValue::get(CurTy); // Unknown binop. 2633 } else { 2634 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy); 2635 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy); 2636 unsigned Flags = 0; 2637 if (Record.size() >= 4) { 2638 if (Opc == Instruction::Add || 2639 Opc == Instruction::Sub || 2640 Opc == Instruction::Mul || 2641 Opc == Instruction::Shl) { 2642 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP)) 2643 Flags |= OverflowingBinaryOperator::NoSignedWrap; 2644 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP)) 2645 Flags |= OverflowingBinaryOperator::NoUnsignedWrap; 2646 } else if (Opc == Instruction::SDiv || 2647 Opc == Instruction::UDiv || 2648 Opc == Instruction::LShr || 2649 Opc == Instruction::AShr) { 2650 if (Record[3] & (1 << bitc::PEO_EXACT)) 2651 Flags |= SDivOperator::IsExact; 2652 } 2653 } 2654 V = ConstantExpr::get(Opc, LHS, RHS, Flags); 2655 } 2656 break; 2657 } 2658 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval] 2659 if (Record.size() < 3) 2660 return error("Invalid record"); 2661 int Opc = getDecodedCastOpcode(Record[0]); 2662 if (Opc < 0) { 2663 V = UndefValue::get(CurTy); // Unknown cast. 2664 } else { 2665 Type *OpTy = getTypeByID(Record[1]); 2666 if (!OpTy) 2667 return error("Invalid record"); 2668 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy); 2669 V = UpgradeBitCastExpr(Opc, Op, CurTy); 2670 if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy); 2671 } 2672 break; 2673 } 2674 case bitc::CST_CODE_CE_INBOUNDS_GEP: // [ty, n x operands] 2675 case bitc::CST_CODE_CE_GEP: // [ty, n x operands] 2676 case bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX: { // [ty, flags, n x 2677 // operands] 2678 unsigned OpNum = 0; 2679 Type *PointeeType = nullptr; 2680 if (BitCode == bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX || 2681 Record.size() % 2) 2682 PointeeType = getTypeByID(Record[OpNum++]); 2683 2684 bool InBounds = false; 2685 Optional<unsigned> InRangeIndex; 2686 if (BitCode == bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX) { 2687 uint64_t Op = Record[OpNum++]; 2688 InBounds = Op & 1; 2689 InRangeIndex = Op >> 1; 2690 } else if (BitCode == bitc::CST_CODE_CE_INBOUNDS_GEP) 2691 InBounds = true; 2692 2693 SmallVector<Constant*, 16> Elts; 2694 Type *Elt0FullTy = nullptr; 2695 while (OpNum != Record.size()) { 2696 if (!Elt0FullTy) 2697 Elt0FullTy = getTypeByID(Record[OpNum]); 2698 Type *ElTy = getTypeByID(Record[OpNum++]); 2699 if (!ElTy) 2700 return error("Invalid record"); 2701 Elts.push_back(ValueList.getConstantFwdRef(Record[OpNum++], ElTy)); 2702 } 2703 2704 if (Elts.size() < 1) 2705 return error("Invalid gep with no operands"); 2706 2707 PointerType *OrigPtrTy = cast<PointerType>(Elt0FullTy->getScalarType()); 2708 if (!PointeeType) 2709 PointeeType = OrigPtrTy->getElementType(); 2710 else if (!OrigPtrTy->isOpaqueOrPointeeTypeMatches(PointeeType)) 2711 return error("Explicit gep operator type does not match pointee type " 2712 "of pointer operand"); 2713 2714 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end()); 2715 V = ConstantExpr::getGetElementPtr(PointeeType, Elts[0], Indices, 2716 InBounds, InRangeIndex); 2717 break; 2718 } 2719 case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#] 2720 if (Record.size() < 3) 2721 return error("Invalid record"); 2722 2723 DelayedSelectors.push_back( 2724 {CurTy, Record[0], Record[1], Record[2], NextCstNo}); 2725 (void)ValueList.getConstantFwdRef(NextCstNo, CurTy); 2726 ++NextCstNo; 2727 continue; 2728 } 2729 case bitc::CST_CODE_CE_EXTRACTELT 2730 : { // CE_EXTRACTELT: [opty, opval, opty, opval] 2731 if (Record.size() < 3) 2732 return error("Invalid record"); 2733 VectorType *OpTy = 2734 dyn_cast_or_null<VectorType>(getTypeByID(Record[0])); 2735 if (!OpTy) 2736 return error("Invalid record"); 2737 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy); 2738 Constant *Op1 = nullptr; 2739 if (Record.size() == 4) { 2740 Type *IdxTy = getTypeByID(Record[2]); 2741 if (!IdxTy) 2742 return error("Invalid record"); 2743 Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy); 2744 } else { 2745 // Deprecated, but still needed to read old bitcode files. 2746 Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context)); 2747 } 2748 if (!Op1) 2749 return error("Invalid record"); 2750 V = ConstantExpr::getExtractElement(Op0, Op1); 2751 break; 2752 } 2753 case bitc::CST_CODE_CE_INSERTELT 2754 : { // CE_INSERTELT: [opval, opval, opty, opval] 2755 VectorType *OpTy = dyn_cast<VectorType>(CurTy); 2756 if (Record.size() < 3 || !OpTy) 2757 return error("Invalid record"); 2758 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy); 2759 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], 2760 OpTy->getElementType()); 2761 Constant *Op2 = nullptr; 2762 if (Record.size() == 4) { 2763 Type *IdxTy = getTypeByID(Record[2]); 2764 if (!IdxTy) 2765 return error("Invalid record"); 2766 Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy); 2767 } else { 2768 // Deprecated, but still needed to read old bitcode files. 2769 Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context)); 2770 } 2771 if (!Op2) 2772 return error("Invalid record"); 2773 V = ConstantExpr::getInsertElement(Op0, Op1, Op2); 2774 break; 2775 } 2776 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval] 2777 VectorType *OpTy = dyn_cast<VectorType>(CurTy); 2778 if (Record.size() < 3 || !OpTy) 2779 return error("Invalid record"); 2780 DelayedShuffles.push_back( 2781 {OpTy, OpTy, Record[0], Record[1], Record[2], NextCstNo}); 2782 ++NextCstNo; 2783 continue; 2784 } 2785 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval] 2786 VectorType *RTy = dyn_cast<VectorType>(CurTy); 2787 VectorType *OpTy = 2788 dyn_cast_or_null<VectorType>(getTypeByID(Record[0])); 2789 if (Record.size() < 4 || !RTy || !OpTy) 2790 return error("Invalid record"); 2791 DelayedShuffles.push_back( 2792 {OpTy, RTy, Record[1], Record[2], Record[3], NextCstNo}); 2793 ++NextCstNo; 2794 continue; 2795 } 2796 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred] 2797 if (Record.size() < 4) 2798 return error("Invalid record"); 2799 Type *OpTy = getTypeByID(Record[0]); 2800 if (!OpTy) 2801 return error("Invalid record"); 2802 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy); 2803 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy); 2804 2805 if (OpTy->isFPOrFPVectorTy()) 2806 V = ConstantExpr::getFCmp(Record[3], Op0, Op1); 2807 else 2808 V = ConstantExpr::getICmp(Record[3], Op0, Op1); 2809 break; 2810 } 2811 // This maintains backward compatibility, pre-asm dialect keywords. 2812 // Deprecated, but still needed to read old bitcode files. 2813 case bitc::CST_CODE_INLINEASM_OLD: { 2814 if (Record.size() < 2) 2815 return error("Invalid record"); 2816 std::string AsmStr, ConstrStr; 2817 bool HasSideEffects = Record[0] & 1; 2818 bool IsAlignStack = Record[0] >> 1; 2819 unsigned AsmStrSize = Record[1]; 2820 if (2+AsmStrSize >= Record.size()) 2821 return error("Invalid record"); 2822 unsigned ConstStrSize = Record[2+AsmStrSize]; 2823 if (3+AsmStrSize+ConstStrSize > Record.size()) 2824 return error("Invalid record"); 2825 2826 for (unsigned i = 0; i != AsmStrSize; ++i) 2827 AsmStr += (char)Record[2+i]; 2828 for (unsigned i = 0; i != ConstStrSize; ++i) 2829 ConstrStr += (char)Record[3+AsmStrSize+i]; 2830 UpgradeInlineAsmString(&AsmStr); 2831 V = InlineAsm::get( 2832 cast<FunctionType>(cast<PointerType>(CurTy)->getElementType()), 2833 AsmStr, ConstrStr, HasSideEffects, IsAlignStack); 2834 break; 2835 } 2836 // This version adds support for the asm dialect keywords (e.g., 2837 // inteldialect). 2838 case bitc::CST_CODE_INLINEASM_OLD2: { 2839 if (Record.size() < 2) 2840 return error("Invalid record"); 2841 std::string AsmStr, ConstrStr; 2842 bool HasSideEffects = Record[0] & 1; 2843 bool IsAlignStack = (Record[0] >> 1) & 1; 2844 unsigned AsmDialect = Record[0] >> 2; 2845 unsigned AsmStrSize = Record[1]; 2846 if (2+AsmStrSize >= Record.size()) 2847 return error("Invalid record"); 2848 unsigned ConstStrSize = Record[2+AsmStrSize]; 2849 if (3+AsmStrSize+ConstStrSize > Record.size()) 2850 return error("Invalid record"); 2851 2852 for (unsigned i = 0; i != AsmStrSize; ++i) 2853 AsmStr += (char)Record[2+i]; 2854 for (unsigned i = 0; i != ConstStrSize; ++i) 2855 ConstrStr += (char)Record[3+AsmStrSize+i]; 2856 UpgradeInlineAsmString(&AsmStr); 2857 V = InlineAsm::get( 2858 cast<FunctionType>(cast<PointerType>(CurTy)->getElementType()), 2859 AsmStr, ConstrStr, HasSideEffects, IsAlignStack, 2860 InlineAsm::AsmDialect(AsmDialect)); 2861 break; 2862 } 2863 // This version adds support for the unwind keyword. 2864 case bitc::CST_CODE_INLINEASM: { 2865 if (Record.size() < 2) 2866 return error("Invalid record"); 2867 std::string AsmStr, ConstrStr; 2868 bool HasSideEffects = Record[0] & 1; 2869 bool IsAlignStack = (Record[0] >> 1) & 1; 2870 unsigned AsmDialect = (Record[0] >> 2) & 1; 2871 bool CanThrow = (Record[0] >> 3) & 1; 2872 unsigned AsmStrSize = Record[1]; 2873 if (2 + AsmStrSize >= Record.size()) 2874 return error("Invalid record"); 2875 unsigned ConstStrSize = Record[2 + AsmStrSize]; 2876 if (3 + AsmStrSize + ConstStrSize > Record.size()) 2877 return error("Invalid record"); 2878 2879 for (unsigned i = 0; i != AsmStrSize; ++i) 2880 AsmStr += (char)Record[2 + i]; 2881 for (unsigned i = 0; i != ConstStrSize; ++i) 2882 ConstrStr += (char)Record[3 + AsmStrSize + i]; 2883 UpgradeInlineAsmString(&AsmStr); 2884 V = InlineAsm::get( 2885 cast<FunctionType>(cast<PointerType>(CurTy)->getElementType()), 2886 AsmStr, ConstrStr, HasSideEffects, IsAlignStack, 2887 InlineAsm::AsmDialect(AsmDialect), CanThrow); 2888 break; 2889 } 2890 case bitc::CST_CODE_BLOCKADDRESS:{ 2891 if (Record.size() < 3) 2892 return error("Invalid record"); 2893 Type *FnTy = getTypeByID(Record[0]); 2894 if (!FnTy) 2895 return error("Invalid record"); 2896 Function *Fn = 2897 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy)); 2898 if (!Fn) 2899 return error("Invalid record"); 2900 2901 // If the function is already parsed we can insert the block address right 2902 // away. 2903 BasicBlock *BB; 2904 unsigned BBID = Record[2]; 2905 if (!BBID) 2906 // Invalid reference to entry block. 2907 return error("Invalid ID"); 2908 if (!Fn->empty()) { 2909 Function::iterator BBI = Fn->begin(), BBE = Fn->end(); 2910 for (size_t I = 0, E = BBID; I != E; ++I) { 2911 if (BBI == BBE) 2912 return error("Invalid ID"); 2913 ++BBI; 2914 } 2915 BB = &*BBI; 2916 } else { 2917 // Otherwise insert a placeholder and remember it so it can be inserted 2918 // when the function is parsed. 2919 auto &FwdBBs = BasicBlockFwdRefs[Fn]; 2920 if (FwdBBs.empty()) 2921 BasicBlockFwdRefQueue.push_back(Fn); 2922 if (FwdBBs.size() < BBID + 1) 2923 FwdBBs.resize(BBID + 1); 2924 if (!FwdBBs[BBID]) 2925 FwdBBs[BBID] = BasicBlock::Create(Context); 2926 BB = FwdBBs[BBID]; 2927 } 2928 V = BlockAddress::get(Fn, BB); 2929 break; 2930 } 2931 case bitc::CST_CODE_DSO_LOCAL_EQUIVALENT: { 2932 if (Record.size() < 2) 2933 return error("Invalid record"); 2934 Type *GVTy = getTypeByID(Record[0]); 2935 if (!GVTy) 2936 return error("Invalid record"); 2937 GlobalValue *GV = dyn_cast_or_null<GlobalValue>( 2938 ValueList.getConstantFwdRef(Record[1], GVTy)); 2939 if (!GV) 2940 return error("Invalid record"); 2941 2942 V = DSOLocalEquivalent::get(GV); 2943 break; 2944 } 2945 } 2946 2947 ValueList.assignValue(V, NextCstNo); 2948 ++NextCstNo; 2949 } 2950 } 2951 2952 Error BitcodeReader::parseUseLists() { 2953 if (Error Err = Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID)) 2954 return Err; 2955 2956 // Read all the records. 2957 SmallVector<uint64_t, 64> Record; 2958 2959 while (true) { 2960 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); 2961 if (!MaybeEntry) 2962 return MaybeEntry.takeError(); 2963 BitstreamEntry Entry = MaybeEntry.get(); 2964 2965 switch (Entry.Kind) { 2966 case BitstreamEntry::SubBlock: // Handled for us already. 2967 case BitstreamEntry::Error: 2968 return error("Malformed block"); 2969 case BitstreamEntry::EndBlock: 2970 return Error::success(); 2971 case BitstreamEntry::Record: 2972 // The interesting case. 2973 break; 2974 } 2975 2976 // Read a use list record. 2977 Record.clear(); 2978 bool IsBB = false; 2979 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record); 2980 if (!MaybeRecord) 2981 return MaybeRecord.takeError(); 2982 switch (MaybeRecord.get()) { 2983 default: // Default behavior: unknown type. 2984 break; 2985 case bitc::USELIST_CODE_BB: 2986 IsBB = true; 2987 LLVM_FALLTHROUGH; 2988 case bitc::USELIST_CODE_DEFAULT: { 2989 unsigned RecordLength = Record.size(); 2990 if (RecordLength < 3) 2991 // Records should have at least an ID and two indexes. 2992 return error("Invalid record"); 2993 unsigned ID = Record.pop_back_val(); 2994 2995 Value *V; 2996 if (IsBB) { 2997 assert(ID < FunctionBBs.size() && "Basic block not found"); 2998 V = FunctionBBs[ID]; 2999 } else 3000 V = ValueList[ID]; 3001 unsigned NumUses = 0; 3002 SmallDenseMap<const Use *, unsigned, 16> Order; 3003 for (const Use &U : V->materialized_uses()) { 3004 if (++NumUses > Record.size()) 3005 break; 3006 Order[&U] = Record[NumUses - 1]; 3007 } 3008 if (Order.size() != Record.size() || NumUses > Record.size()) 3009 // Mismatches can happen if the functions are being materialized lazily 3010 // (out-of-order), or a value has been upgraded. 3011 break; 3012 3013 V->sortUseList([&](const Use &L, const Use &R) { 3014 return Order.lookup(&L) < Order.lookup(&R); 3015 }); 3016 break; 3017 } 3018 } 3019 } 3020 } 3021 3022 /// When we see the block for metadata, remember where it is and then skip it. 3023 /// This lets us lazily deserialize the metadata. 3024 Error BitcodeReader::rememberAndSkipMetadata() { 3025 // Save the current stream state. 3026 uint64_t CurBit = Stream.GetCurrentBitNo(); 3027 DeferredMetadataInfo.push_back(CurBit); 3028 3029 // Skip over the block for now. 3030 if (Error Err = Stream.SkipBlock()) 3031 return Err; 3032 return Error::success(); 3033 } 3034 3035 Error BitcodeReader::materializeMetadata() { 3036 for (uint64_t BitPos : DeferredMetadataInfo) { 3037 // Move the bit stream to the saved position. 3038 if (Error JumpFailed = Stream.JumpToBit(BitPos)) 3039 return JumpFailed; 3040 if (Error Err = MDLoader->parseModuleMetadata()) 3041 return Err; 3042 } 3043 3044 // Upgrade "Linker Options" module flag to "llvm.linker.options" module-level 3045 // metadata. Only upgrade if the new option doesn't exist to avoid upgrade 3046 // multiple times. 3047 if (!TheModule->getNamedMetadata("llvm.linker.options")) { 3048 if (Metadata *Val = TheModule->getModuleFlag("Linker Options")) { 3049 NamedMDNode *LinkerOpts = 3050 TheModule->getOrInsertNamedMetadata("llvm.linker.options"); 3051 for (const MDOperand &MDOptions : cast<MDNode>(Val)->operands()) 3052 LinkerOpts->addOperand(cast<MDNode>(MDOptions)); 3053 } 3054 } 3055 3056 DeferredMetadataInfo.clear(); 3057 return Error::success(); 3058 } 3059 3060 void BitcodeReader::setStripDebugInfo() { StripDebugInfo = true; } 3061 3062 /// When we see the block for a function body, remember where it is and then 3063 /// skip it. This lets us lazily deserialize the functions. 3064 Error BitcodeReader::rememberAndSkipFunctionBody() { 3065 // Get the function we are talking about. 3066 if (FunctionsWithBodies.empty()) 3067 return error("Insufficient function protos"); 3068 3069 Function *Fn = FunctionsWithBodies.back(); 3070 FunctionsWithBodies.pop_back(); 3071 3072 // Save the current stream state. 3073 uint64_t CurBit = Stream.GetCurrentBitNo(); 3074 assert( 3075 (DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo[Fn] == CurBit) && 3076 "Mismatch between VST and scanned function offsets"); 3077 DeferredFunctionInfo[Fn] = CurBit; 3078 3079 // Skip over the function block for now. 3080 if (Error Err = Stream.SkipBlock()) 3081 return Err; 3082 return Error::success(); 3083 } 3084 3085 Error BitcodeReader::globalCleanup() { 3086 // Patch the initializers for globals and aliases up. 3087 if (Error Err = resolveGlobalAndIndirectSymbolInits()) 3088 return Err; 3089 if (!GlobalInits.empty() || !IndirectSymbolInits.empty()) 3090 return error("Malformed global initializer set"); 3091 3092 // Look for intrinsic functions which need to be upgraded at some point 3093 // and functions that need to have their function attributes upgraded. 3094 for (Function &F : *TheModule) { 3095 MDLoader->upgradeDebugIntrinsics(F); 3096 Function *NewFn; 3097 if (UpgradeIntrinsicFunction(&F, NewFn)) 3098 UpgradedIntrinsics[&F] = NewFn; 3099 else if (auto Remangled = Intrinsic::remangleIntrinsicFunction(&F)) 3100 // Some types could be renamed during loading if several modules are 3101 // loaded in the same LLVMContext (LTO scenario). In this case we should 3102 // remangle intrinsics names as well. 3103 RemangledIntrinsics[&F] = Remangled.getValue(); 3104 // Look for functions that rely on old function attribute behavior. 3105 UpgradeFunctionAttributes(F); 3106 } 3107 3108 // Look for global variables which need to be renamed. 3109 std::vector<std::pair<GlobalVariable *, GlobalVariable *>> UpgradedVariables; 3110 for (GlobalVariable &GV : TheModule->globals()) 3111 if (GlobalVariable *Upgraded = UpgradeGlobalVariable(&GV)) 3112 UpgradedVariables.emplace_back(&GV, Upgraded); 3113 for (auto &Pair : UpgradedVariables) { 3114 Pair.first->eraseFromParent(); 3115 TheModule->getGlobalList().push_back(Pair.second); 3116 } 3117 3118 // Force deallocation of memory for these vectors to favor the client that 3119 // want lazy deserialization. 3120 std::vector<std::pair<GlobalVariable *, unsigned>>().swap(GlobalInits); 3121 std::vector<std::pair<GlobalValue *, unsigned>>().swap(IndirectSymbolInits); 3122 return Error::success(); 3123 } 3124 3125 /// Support for lazy parsing of function bodies. This is required if we 3126 /// either have an old bitcode file without a VST forward declaration record, 3127 /// or if we have an anonymous function being materialized, since anonymous 3128 /// functions do not have a name and are therefore not in the VST. 3129 Error BitcodeReader::rememberAndSkipFunctionBodies() { 3130 if (Error JumpFailed = Stream.JumpToBit(NextUnreadBit)) 3131 return JumpFailed; 3132 3133 if (Stream.AtEndOfStream()) 3134 return error("Could not find function in stream"); 3135 3136 if (!SeenFirstFunctionBody) 3137 return error("Trying to materialize functions before seeing function blocks"); 3138 3139 // An old bitcode file with the symbol table at the end would have 3140 // finished the parse greedily. 3141 assert(SeenValueSymbolTable); 3142 3143 SmallVector<uint64_t, 64> Record; 3144 3145 while (true) { 3146 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance(); 3147 if (!MaybeEntry) 3148 return MaybeEntry.takeError(); 3149 llvm::BitstreamEntry Entry = MaybeEntry.get(); 3150 3151 switch (Entry.Kind) { 3152 default: 3153 return error("Expect SubBlock"); 3154 case BitstreamEntry::SubBlock: 3155 switch (Entry.ID) { 3156 default: 3157 return error("Expect function block"); 3158 case bitc::FUNCTION_BLOCK_ID: 3159 if (Error Err = rememberAndSkipFunctionBody()) 3160 return Err; 3161 NextUnreadBit = Stream.GetCurrentBitNo(); 3162 return Error::success(); 3163 } 3164 } 3165 } 3166 } 3167 3168 bool BitcodeReaderBase::readBlockInfo() { 3169 Expected<Optional<BitstreamBlockInfo>> MaybeNewBlockInfo = 3170 Stream.ReadBlockInfoBlock(); 3171 if (!MaybeNewBlockInfo) 3172 return true; // FIXME Handle the error. 3173 Optional<BitstreamBlockInfo> NewBlockInfo = 3174 std::move(MaybeNewBlockInfo.get()); 3175 if (!NewBlockInfo) 3176 return true; 3177 BlockInfo = std::move(*NewBlockInfo); 3178 return false; 3179 } 3180 3181 Error BitcodeReader::parseComdatRecord(ArrayRef<uint64_t> Record) { 3182 // v1: [selection_kind, name] 3183 // v2: [strtab_offset, strtab_size, selection_kind] 3184 StringRef Name; 3185 std::tie(Name, Record) = readNameFromStrtab(Record); 3186 3187 if (Record.empty()) 3188 return error("Invalid record"); 3189 Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]); 3190 std::string OldFormatName; 3191 if (!UseStrtab) { 3192 if (Record.size() < 2) 3193 return error("Invalid record"); 3194 unsigned ComdatNameSize = Record[1]; 3195 OldFormatName.reserve(ComdatNameSize); 3196 for (unsigned i = 0; i != ComdatNameSize; ++i) 3197 OldFormatName += (char)Record[2 + i]; 3198 Name = OldFormatName; 3199 } 3200 Comdat *C = TheModule->getOrInsertComdat(Name); 3201 C->setSelectionKind(SK); 3202 ComdatList.push_back(C); 3203 return Error::success(); 3204 } 3205 3206 static void inferDSOLocal(GlobalValue *GV) { 3207 // infer dso_local from linkage and visibility if it is not encoded. 3208 if (GV->hasLocalLinkage() || 3209 (!GV->hasDefaultVisibility() && !GV->hasExternalWeakLinkage())) 3210 GV->setDSOLocal(true); 3211 } 3212 3213 Error BitcodeReader::parseGlobalVarRecord(ArrayRef<uint64_t> Record) { 3214 // v1: [pointer type, isconst, initid, linkage, alignment, section, 3215 // visibility, threadlocal, unnamed_addr, externally_initialized, 3216 // dllstorageclass, comdat, attributes, preemption specifier, 3217 // partition strtab offset, partition strtab size] (name in VST) 3218 // v2: [strtab_offset, strtab_size, v1] 3219 StringRef Name; 3220 std::tie(Name, Record) = readNameFromStrtab(Record); 3221 3222 if (Record.size() < 6) 3223 return error("Invalid record"); 3224 Type *Ty = getTypeByID(Record[0]); 3225 if (!Ty) 3226 return error("Invalid record"); 3227 bool isConstant = Record[1] & 1; 3228 bool explicitType = Record[1] & 2; 3229 unsigned AddressSpace; 3230 if (explicitType) { 3231 AddressSpace = Record[1] >> 2; 3232 } else { 3233 if (!Ty->isPointerTy()) 3234 return error("Invalid type for value"); 3235 AddressSpace = cast<PointerType>(Ty)->getAddressSpace(); 3236 Ty = cast<PointerType>(Ty)->getElementType(); 3237 } 3238 3239 uint64_t RawLinkage = Record[3]; 3240 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage); 3241 MaybeAlign Alignment; 3242 if (Error Err = parseAlignmentValue(Record[4], Alignment)) 3243 return Err; 3244 std::string Section; 3245 if (Record[5]) { 3246 if (Record[5] - 1 >= SectionTable.size()) 3247 return error("Invalid ID"); 3248 Section = SectionTable[Record[5] - 1]; 3249 } 3250 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility; 3251 // Local linkage must have default visibility. 3252 // auto-upgrade `hidden` and `protected` for old bitcode. 3253 if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage)) 3254 Visibility = getDecodedVisibility(Record[6]); 3255 3256 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal; 3257 if (Record.size() > 7) 3258 TLM = getDecodedThreadLocalMode(Record[7]); 3259 3260 GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None; 3261 if (Record.size() > 8) 3262 UnnamedAddr = getDecodedUnnamedAddrType(Record[8]); 3263 3264 bool ExternallyInitialized = false; 3265 if (Record.size() > 9) 3266 ExternallyInitialized = Record[9]; 3267 3268 GlobalVariable *NewGV = 3269 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, Name, 3270 nullptr, TLM, AddressSpace, ExternallyInitialized); 3271 NewGV->setAlignment(Alignment); 3272 if (!Section.empty()) 3273 NewGV->setSection(Section); 3274 NewGV->setVisibility(Visibility); 3275 NewGV->setUnnamedAddr(UnnamedAddr); 3276 3277 if (Record.size() > 10) 3278 NewGV->setDLLStorageClass(getDecodedDLLStorageClass(Record[10])); 3279 else 3280 upgradeDLLImportExportLinkage(NewGV, RawLinkage); 3281 3282 ValueList.push_back(NewGV); 3283 3284 // Remember which value to use for the global initializer. 3285 if (unsigned InitID = Record[2]) 3286 GlobalInits.push_back(std::make_pair(NewGV, InitID - 1)); 3287 3288 if (Record.size() > 11) { 3289 if (unsigned ComdatID = Record[11]) { 3290 if (ComdatID > ComdatList.size()) 3291 return error("Invalid global variable comdat ID"); 3292 NewGV->setComdat(ComdatList[ComdatID - 1]); 3293 } 3294 } else if (hasImplicitComdat(RawLinkage)) { 3295 NewGV->setComdat(reinterpret_cast<Comdat *>(1)); 3296 } 3297 3298 if (Record.size() > 12) { 3299 auto AS = getAttributes(Record[12]).getFnAttrs(); 3300 NewGV->setAttributes(AS); 3301 } 3302 3303 if (Record.size() > 13) { 3304 NewGV->setDSOLocal(getDecodedDSOLocal(Record[13])); 3305 } 3306 inferDSOLocal(NewGV); 3307 3308 // Check whether we have enough values to read a partition name. 3309 if (Record.size() > 15) 3310 NewGV->setPartition(StringRef(Strtab.data() + Record[14], Record[15])); 3311 3312 return Error::success(); 3313 } 3314 3315 Error BitcodeReader::parseFunctionRecord(ArrayRef<uint64_t> Record) { 3316 // v1: [type, callingconv, isproto, linkage, paramattr, alignment, section, 3317 // visibility, gc, unnamed_addr, prologuedata, dllstorageclass, comdat, 3318 // prefixdata, personalityfn, preemption specifier, addrspace] (name in VST) 3319 // v2: [strtab_offset, strtab_size, v1] 3320 StringRef Name; 3321 std::tie(Name, Record) = readNameFromStrtab(Record); 3322 3323 if (Record.size() < 8) 3324 return error("Invalid record"); 3325 Type *FTy = getTypeByID(Record[0]); 3326 if (!FTy) 3327 return error("Invalid record"); 3328 if (auto *PTy = dyn_cast<PointerType>(FTy)) 3329 FTy = PTy->getElementType(); 3330 3331 if (!isa<FunctionType>(FTy)) 3332 return error("Invalid type for value"); 3333 auto CC = static_cast<CallingConv::ID>(Record[1]); 3334 if (CC & ~CallingConv::MaxID) 3335 return error("Invalid calling convention ID"); 3336 3337 unsigned AddrSpace = TheModule->getDataLayout().getProgramAddressSpace(); 3338 if (Record.size() > 16) 3339 AddrSpace = Record[16]; 3340 3341 Function *Func = 3342 Function::Create(cast<FunctionType>(FTy), GlobalValue::ExternalLinkage, 3343 AddrSpace, Name, TheModule); 3344 3345 assert(Func->getFunctionType() == FTy && 3346 "Incorrect fully specified type provided for function"); 3347 FunctionTypes[Func] = cast<FunctionType>(FTy); 3348 3349 Func->setCallingConv(CC); 3350 bool isProto = Record[2]; 3351 uint64_t RawLinkage = Record[3]; 3352 Func->setLinkage(getDecodedLinkage(RawLinkage)); 3353 Func->setAttributes(getAttributes(Record[4])); 3354 3355 // Upgrade any old-style byval or sret without a type by propagating the 3356 // argument's pointee type. There should be no opaque pointers where the byval 3357 // type is implicit. 3358 for (unsigned i = 0; i != Func->arg_size(); ++i) { 3359 for (Attribute::AttrKind Kind : {Attribute::ByVal, Attribute::StructRet, 3360 Attribute::InAlloca}) { 3361 if (!Func->hasParamAttribute(i, Kind)) 3362 continue; 3363 3364 if (Func->getParamAttribute(i, Kind).getValueAsType()) 3365 continue; 3366 3367 Func->removeParamAttr(i, Kind); 3368 3369 Type *PTy = cast<FunctionType>(FTy)->getParamType(i); 3370 Type *PtrEltTy = cast<PointerType>(PTy)->getElementType(); 3371 Attribute NewAttr; 3372 switch (Kind) { 3373 case Attribute::ByVal: 3374 NewAttr = Attribute::getWithByValType(Context, PtrEltTy); 3375 break; 3376 case Attribute::StructRet: 3377 NewAttr = Attribute::getWithStructRetType(Context, PtrEltTy); 3378 break; 3379 case Attribute::InAlloca: 3380 NewAttr = Attribute::getWithInAllocaType(Context, PtrEltTy); 3381 break; 3382 default: 3383 llvm_unreachable("not an upgraded type attribute"); 3384 } 3385 3386 Func->addParamAttr(i, NewAttr); 3387 } 3388 } 3389 3390 MaybeAlign Alignment; 3391 if (Error Err = parseAlignmentValue(Record[5], Alignment)) 3392 return Err; 3393 Func->setAlignment(Alignment); 3394 if (Record[6]) { 3395 if (Record[6] - 1 >= SectionTable.size()) 3396 return error("Invalid ID"); 3397 Func->setSection(SectionTable[Record[6] - 1]); 3398 } 3399 // Local linkage must have default visibility. 3400 // auto-upgrade `hidden` and `protected` for old bitcode. 3401 if (!Func->hasLocalLinkage()) 3402 Func->setVisibility(getDecodedVisibility(Record[7])); 3403 if (Record.size() > 8 && Record[8]) { 3404 if (Record[8] - 1 >= GCTable.size()) 3405 return error("Invalid ID"); 3406 Func->setGC(GCTable[Record[8] - 1]); 3407 } 3408 GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None; 3409 if (Record.size() > 9) 3410 UnnamedAddr = getDecodedUnnamedAddrType(Record[9]); 3411 Func->setUnnamedAddr(UnnamedAddr); 3412 3413 FunctionOperandInfo OperandInfo = {Func, 0, 0, 0}; 3414 if (Record.size() > 10) 3415 OperandInfo.Prologue = Record[10]; 3416 3417 if (Record.size() > 11) 3418 Func->setDLLStorageClass(getDecodedDLLStorageClass(Record[11])); 3419 else 3420 upgradeDLLImportExportLinkage(Func, RawLinkage); 3421 3422 if (Record.size() > 12) { 3423 if (unsigned ComdatID = Record[12]) { 3424 if (ComdatID > ComdatList.size()) 3425 return error("Invalid function comdat ID"); 3426 Func->setComdat(ComdatList[ComdatID - 1]); 3427 } 3428 } else if (hasImplicitComdat(RawLinkage)) { 3429 Func->setComdat(reinterpret_cast<Comdat *>(1)); 3430 } 3431 3432 if (Record.size() > 13) 3433 OperandInfo.Prefix = Record[13]; 3434 3435 if (Record.size() > 14) 3436 OperandInfo.PersonalityFn = Record[14]; 3437 3438 if (Record.size() > 15) { 3439 Func->setDSOLocal(getDecodedDSOLocal(Record[15])); 3440 } 3441 inferDSOLocal(Func); 3442 3443 // Record[16] is the address space number. 3444 3445 // Check whether we have enough values to read a partition name. Also make 3446 // sure Strtab has enough values. 3447 if (Record.size() > 18 && Strtab.data() && 3448 Record[17] + Record[18] <= Strtab.size()) { 3449 Func->setPartition(StringRef(Strtab.data() + Record[17], Record[18])); 3450 } 3451 3452 ValueList.push_back(Func); 3453 3454 if (OperandInfo.PersonalityFn || OperandInfo.Prefix || OperandInfo.Prologue) 3455 FunctionOperands.push_back(OperandInfo); 3456 3457 // If this is a function with a body, remember the prototype we are 3458 // creating now, so that we can match up the body with them later. 3459 if (!isProto) { 3460 Func->setIsMaterializable(true); 3461 FunctionsWithBodies.push_back(Func); 3462 DeferredFunctionInfo[Func] = 0; 3463 } 3464 return Error::success(); 3465 } 3466 3467 Error BitcodeReader::parseGlobalIndirectSymbolRecord( 3468 unsigned BitCode, ArrayRef<uint64_t> Record) { 3469 // v1 ALIAS_OLD: [alias type, aliasee val#, linkage] (name in VST) 3470 // v1 ALIAS: [alias type, addrspace, aliasee val#, linkage, visibility, 3471 // dllstorageclass, threadlocal, unnamed_addr, 3472 // preemption specifier] (name in VST) 3473 // v1 IFUNC: [alias type, addrspace, aliasee val#, linkage, 3474 // visibility, dllstorageclass, threadlocal, unnamed_addr, 3475 // preemption specifier] (name in VST) 3476 // v2: [strtab_offset, strtab_size, v1] 3477 StringRef Name; 3478 std::tie(Name, Record) = readNameFromStrtab(Record); 3479 3480 bool NewRecord = BitCode != bitc::MODULE_CODE_ALIAS_OLD; 3481 if (Record.size() < (3 + (unsigned)NewRecord)) 3482 return error("Invalid record"); 3483 unsigned OpNum = 0; 3484 Type *Ty = getTypeByID(Record[OpNum++]); 3485 if (!Ty) 3486 return error("Invalid record"); 3487 3488 unsigned AddrSpace; 3489 if (!NewRecord) { 3490 auto *PTy = dyn_cast<PointerType>(Ty); 3491 if (!PTy) 3492 return error("Invalid type for value"); 3493 Ty = PTy->getElementType(); 3494 AddrSpace = PTy->getAddressSpace(); 3495 } else { 3496 AddrSpace = Record[OpNum++]; 3497 } 3498 3499 auto Val = Record[OpNum++]; 3500 auto Linkage = Record[OpNum++]; 3501 GlobalValue *NewGA; 3502 if (BitCode == bitc::MODULE_CODE_ALIAS || 3503 BitCode == bitc::MODULE_CODE_ALIAS_OLD) 3504 NewGA = GlobalAlias::create(Ty, AddrSpace, getDecodedLinkage(Linkage), Name, 3505 TheModule); 3506 else 3507 NewGA = GlobalIFunc::create(Ty, AddrSpace, getDecodedLinkage(Linkage), Name, 3508 nullptr, TheModule); 3509 3510 // Local linkage must have default visibility. 3511 // auto-upgrade `hidden` and `protected` for old bitcode. 3512 if (OpNum != Record.size()) { 3513 auto VisInd = OpNum++; 3514 if (!NewGA->hasLocalLinkage()) 3515 NewGA->setVisibility(getDecodedVisibility(Record[VisInd])); 3516 } 3517 if (BitCode == bitc::MODULE_CODE_ALIAS || 3518 BitCode == bitc::MODULE_CODE_ALIAS_OLD) { 3519 if (OpNum != Record.size()) 3520 NewGA->setDLLStorageClass(getDecodedDLLStorageClass(Record[OpNum++])); 3521 else 3522 upgradeDLLImportExportLinkage(NewGA, Linkage); 3523 if (OpNum != Record.size()) 3524 NewGA->setThreadLocalMode(getDecodedThreadLocalMode(Record[OpNum++])); 3525 if (OpNum != Record.size()) 3526 NewGA->setUnnamedAddr(getDecodedUnnamedAddrType(Record[OpNum++])); 3527 } 3528 if (OpNum != Record.size()) 3529 NewGA->setDSOLocal(getDecodedDSOLocal(Record[OpNum++])); 3530 inferDSOLocal(NewGA); 3531 3532 // Check whether we have enough values to read a partition name. 3533 if (OpNum + 1 < Record.size()) { 3534 NewGA->setPartition( 3535 StringRef(Strtab.data() + Record[OpNum], Record[OpNum + 1])); 3536 OpNum += 2; 3537 } 3538 3539 ValueList.push_back(NewGA); 3540 IndirectSymbolInits.push_back(std::make_pair(NewGA, Val)); 3541 return Error::success(); 3542 } 3543 3544 Error BitcodeReader::parseModule(uint64_t ResumeBit, 3545 bool ShouldLazyLoadMetadata, 3546 DataLayoutCallbackTy DataLayoutCallback) { 3547 if (ResumeBit) { 3548 if (Error JumpFailed = Stream.JumpToBit(ResumeBit)) 3549 return JumpFailed; 3550 } else if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID)) 3551 return Err; 3552 3553 SmallVector<uint64_t, 64> Record; 3554 3555 // Parts of bitcode parsing depend on the datalayout. Make sure we 3556 // finalize the datalayout before we run any of that code. 3557 bool ResolvedDataLayout = false; 3558 auto ResolveDataLayout = [&] { 3559 if (ResolvedDataLayout) 3560 return; 3561 3562 // datalayout and triple can't be parsed after this point. 3563 ResolvedDataLayout = true; 3564 3565 // Upgrade data layout string. 3566 std::string DL = llvm::UpgradeDataLayoutString( 3567 TheModule->getDataLayoutStr(), TheModule->getTargetTriple()); 3568 TheModule->setDataLayout(DL); 3569 3570 if (auto LayoutOverride = 3571 DataLayoutCallback(TheModule->getTargetTriple())) 3572 TheModule->setDataLayout(*LayoutOverride); 3573 }; 3574 3575 // Read all the records for this module. 3576 while (true) { 3577 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance(); 3578 if (!MaybeEntry) 3579 return MaybeEntry.takeError(); 3580 llvm::BitstreamEntry Entry = MaybeEntry.get(); 3581 3582 switch (Entry.Kind) { 3583 case BitstreamEntry::Error: 3584 return error("Malformed block"); 3585 case BitstreamEntry::EndBlock: 3586 ResolveDataLayout(); 3587 return globalCleanup(); 3588 3589 case BitstreamEntry::SubBlock: 3590 switch (Entry.ID) { 3591 default: // Skip unknown content. 3592 if (Error Err = Stream.SkipBlock()) 3593 return Err; 3594 break; 3595 case bitc::BLOCKINFO_BLOCK_ID: 3596 if (readBlockInfo()) 3597 return error("Malformed block"); 3598 break; 3599 case bitc::PARAMATTR_BLOCK_ID: 3600 if (Error Err = parseAttributeBlock()) 3601 return Err; 3602 break; 3603 case bitc::PARAMATTR_GROUP_BLOCK_ID: 3604 if (Error Err = parseAttributeGroupBlock()) 3605 return Err; 3606 break; 3607 case bitc::TYPE_BLOCK_ID_NEW: 3608 if (Error Err = parseTypeTable()) 3609 return Err; 3610 break; 3611 case bitc::VALUE_SYMTAB_BLOCK_ID: 3612 if (!SeenValueSymbolTable) { 3613 // Either this is an old form VST without function index and an 3614 // associated VST forward declaration record (which would have caused 3615 // the VST to be jumped to and parsed before it was encountered 3616 // normally in the stream), or there were no function blocks to 3617 // trigger an earlier parsing of the VST. 3618 assert(VSTOffset == 0 || FunctionsWithBodies.empty()); 3619 if (Error Err = parseValueSymbolTable()) 3620 return Err; 3621 SeenValueSymbolTable = true; 3622 } else { 3623 // We must have had a VST forward declaration record, which caused 3624 // the parser to jump to and parse the VST earlier. 3625 assert(VSTOffset > 0); 3626 if (Error Err = Stream.SkipBlock()) 3627 return Err; 3628 } 3629 break; 3630 case bitc::CONSTANTS_BLOCK_ID: 3631 if (Error Err = parseConstants()) 3632 return Err; 3633 if (Error Err = resolveGlobalAndIndirectSymbolInits()) 3634 return Err; 3635 break; 3636 case bitc::METADATA_BLOCK_ID: 3637 if (ShouldLazyLoadMetadata) { 3638 if (Error Err = rememberAndSkipMetadata()) 3639 return Err; 3640 break; 3641 } 3642 assert(DeferredMetadataInfo.empty() && "Unexpected deferred metadata"); 3643 if (Error Err = MDLoader->parseModuleMetadata()) 3644 return Err; 3645 break; 3646 case bitc::METADATA_KIND_BLOCK_ID: 3647 if (Error Err = MDLoader->parseMetadataKinds()) 3648 return Err; 3649 break; 3650 case bitc::FUNCTION_BLOCK_ID: 3651 ResolveDataLayout(); 3652 3653 // If this is the first function body we've seen, reverse the 3654 // FunctionsWithBodies list. 3655 if (!SeenFirstFunctionBody) { 3656 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end()); 3657 if (Error Err = globalCleanup()) 3658 return Err; 3659 SeenFirstFunctionBody = true; 3660 } 3661 3662 if (VSTOffset > 0) { 3663 // If we have a VST forward declaration record, make sure we 3664 // parse the VST now if we haven't already. It is needed to 3665 // set up the DeferredFunctionInfo vector for lazy reading. 3666 if (!SeenValueSymbolTable) { 3667 if (Error Err = BitcodeReader::parseValueSymbolTable(VSTOffset)) 3668 return Err; 3669 SeenValueSymbolTable = true; 3670 // Fall through so that we record the NextUnreadBit below. 3671 // This is necessary in case we have an anonymous function that 3672 // is later materialized. Since it will not have a VST entry we 3673 // need to fall back to the lazy parse to find its offset. 3674 } else { 3675 // If we have a VST forward declaration record, but have already 3676 // parsed the VST (just above, when the first function body was 3677 // encountered here), then we are resuming the parse after 3678 // materializing functions. The ResumeBit points to the 3679 // start of the last function block recorded in the 3680 // DeferredFunctionInfo map. Skip it. 3681 if (Error Err = Stream.SkipBlock()) 3682 return Err; 3683 continue; 3684 } 3685 } 3686 3687 // Support older bitcode files that did not have the function 3688 // index in the VST, nor a VST forward declaration record, as 3689 // well as anonymous functions that do not have VST entries. 3690 // Build the DeferredFunctionInfo vector on the fly. 3691 if (Error Err = rememberAndSkipFunctionBody()) 3692 return Err; 3693 3694 // Suspend parsing when we reach the function bodies. Subsequent 3695 // materialization calls will resume it when necessary. If the bitcode 3696 // file is old, the symbol table will be at the end instead and will not 3697 // have been seen yet. In this case, just finish the parse now. 3698 if (SeenValueSymbolTable) { 3699 NextUnreadBit = Stream.GetCurrentBitNo(); 3700 // After the VST has been parsed, we need to make sure intrinsic name 3701 // are auto-upgraded. 3702 return globalCleanup(); 3703 } 3704 break; 3705 case bitc::USELIST_BLOCK_ID: 3706 if (Error Err = parseUseLists()) 3707 return Err; 3708 break; 3709 case bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID: 3710 if (Error Err = parseOperandBundleTags()) 3711 return Err; 3712 break; 3713 case bitc::SYNC_SCOPE_NAMES_BLOCK_ID: 3714 if (Error Err = parseSyncScopeNames()) 3715 return Err; 3716 break; 3717 } 3718 continue; 3719 3720 case BitstreamEntry::Record: 3721 // The interesting case. 3722 break; 3723 } 3724 3725 // Read a record. 3726 Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record); 3727 if (!MaybeBitCode) 3728 return MaybeBitCode.takeError(); 3729 switch (unsigned BitCode = MaybeBitCode.get()) { 3730 default: break; // Default behavior, ignore unknown content. 3731 case bitc::MODULE_CODE_VERSION: { 3732 Expected<unsigned> VersionOrErr = parseVersionRecord(Record); 3733 if (!VersionOrErr) 3734 return VersionOrErr.takeError(); 3735 UseRelativeIDs = *VersionOrErr >= 1; 3736 break; 3737 } 3738 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N] 3739 if (ResolvedDataLayout) 3740 return error("target triple too late in module"); 3741 std::string S; 3742 if (convertToString(Record, 0, S)) 3743 return error("Invalid record"); 3744 TheModule->setTargetTriple(S); 3745 break; 3746 } 3747 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N] 3748 if (ResolvedDataLayout) 3749 return error("datalayout too late in module"); 3750 std::string S; 3751 if (convertToString(Record, 0, S)) 3752 return error("Invalid record"); 3753 TheModule->setDataLayout(S); 3754 break; 3755 } 3756 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N] 3757 std::string S; 3758 if (convertToString(Record, 0, S)) 3759 return error("Invalid record"); 3760 TheModule->setModuleInlineAsm(S); 3761 break; 3762 } 3763 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N] 3764 // Deprecated, but still needed to read old bitcode files. 3765 std::string S; 3766 if (convertToString(Record, 0, S)) 3767 return error("Invalid record"); 3768 // Ignore value. 3769 break; 3770 } 3771 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N] 3772 std::string S; 3773 if (convertToString(Record, 0, S)) 3774 return error("Invalid record"); 3775 SectionTable.push_back(S); 3776 break; 3777 } 3778 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N] 3779 std::string S; 3780 if (convertToString(Record, 0, S)) 3781 return error("Invalid record"); 3782 GCTable.push_back(S); 3783 break; 3784 } 3785 case bitc::MODULE_CODE_COMDAT: 3786 if (Error Err = parseComdatRecord(Record)) 3787 return Err; 3788 break; 3789 case bitc::MODULE_CODE_GLOBALVAR: 3790 if (Error Err = parseGlobalVarRecord(Record)) 3791 return Err; 3792 break; 3793 case bitc::MODULE_CODE_FUNCTION: 3794 ResolveDataLayout(); 3795 if (Error Err = parseFunctionRecord(Record)) 3796 return Err; 3797 break; 3798 case bitc::MODULE_CODE_IFUNC: 3799 case bitc::MODULE_CODE_ALIAS: 3800 case bitc::MODULE_CODE_ALIAS_OLD: 3801 if (Error Err = parseGlobalIndirectSymbolRecord(BitCode, Record)) 3802 return Err; 3803 break; 3804 /// MODULE_CODE_VSTOFFSET: [offset] 3805 case bitc::MODULE_CODE_VSTOFFSET: 3806 if (Record.empty()) 3807 return error("Invalid record"); 3808 // Note that we subtract 1 here because the offset is relative to one word 3809 // before the start of the identification or module block, which was 3810 // historically always the start of the regular bitcode header. 3811 VSTOffset = Record[0] - 1; 3812 break; 3813 /// MODULE_CODE_SOURCE_FILENAME: [namechar x N] 3814 case bitc::MODULE_CODE_SOURCE_FILENAME: 3815 SmallString<128> ValueName; 3816 if (convertToString(Record, 0, ValueName)) 3817 return error("Invalid record"); 3818 TheModule->setSourceFileName(ValueName); 3819 break; 3820 } 3821 Record.clear(); 3822 } 3823 } 3824 3825 Error BitcodeReader::parseBitcodeInto(Module *M, bool ShouldLazyLoadMetadata, 3826 bool IsImporting, 3827 DataLayoutCallbackTy DataLayoutCallback) { 3828 TheModule = M; 3829 MDLoader = MetadataLoader(Stream, *M, ValueList, IsImporting, 3830 [&](unsigned ID) { return getTypeByID(ID); }); 3831 return parseModule(0, ShouldLazyLoadMetadata, DataLayoutCallback); 3832 } 3833 3834 Error BitcodeReader::typeCheckLoadStoreInst(Type *ValType, Type *PtrType) { 3835 if (!isa<PointerType>(PtrType)) 3836 return error("Load/Store operand is not a pointer type"); 3837 3838 if (!cast<PointerType>(PtrType)->isOpaqueOrPointeeTypeMatches(ValType)) 3839 return error("Explicit load/store type does not match pointee " 3840 "type of pointer operand"); 3841 if (!PointerType::isLoadableOrStorableType(ValType)) 3842 return error("Cannot load/store from pointer"); 3843 return Error::success(); 3844 } 3845 3846 void BitcodeReader::propagateAttributeTypes(CallBase *CB, 3847 ArrayRef<Type *> ArgsTys) { 3848 for (unsigned i = 0; i != CB->arg_size(); ++i) { 3849 for (Attribute::AttrKind Kind : {Attribute::ByVal, Attribute::StructRet, 3850 Attribute::InAlloca}) { 3851 if (!CB->paramHasAttr(i, Kind)) 3852 continue; 3853 3854 CB->removeParamAttr(i, Kind); 3855 3856 Type *PtrEltTy = cast<PointerType>(ArgsTys[i])->getElementType(); 3857 Attribute NewAttr; 3858 switch (Kind) { 3859 case Attribute::ByVal: 3860 NewAttr = Attribute::getWithByValType(Context, PtrEltTy); 3861 break; 3862 case Attribute::StructRet: 3863 NewAttr = Attribute::getWithStructRetType(Context, PtrEltTy); 3864 break; 3865 case Attribute::InAlloca: 3866 NewAttr = Attribute::getWithInAllocaType(Context, PtrEltTy); 3867 break; 3868 default: 3869 llvm_unreachable("not an upgraded type attribute"); 3870 } 3871 3872 CB->addParamAttr(i, NewAttr); 3873 } 3874 } 3875 3876 switch (CB->getIntrinsicID()) { 3877 case Intrinsic::preserve_array_access_index: 3878 case Intrinsic::preserve_struct_access_index: 3879 if (!CB->getAttributes().getParamElementType(0)) { 3880 Type *ElTy = cast<PointerType>(ArgsTys[0])->getElementType(); 3881 Attribute NewAttr = Attribute::get(Context, Attribute::ElementType, ElTy); 3882 CB->addParamAttr(0, NewAttr); 3883 } 3884 break; 3885 default: 3886 break; 3887 } 3888 } 3889 3890 /// Lazily parse the specified function body block. 3891 Error BitcodeReader::parseFunctionBody(Function *F) { 3892 if (Error Err = Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID)) 3893 return Err; 3894 3895 // Unexpected unresolved metadata when parsing function. 3896 if (MDLoader->hasFwdRefs()) 3897 return error("Invalid function metadata: incoming forward references"); 3898 3899 InstructionList.clear(); 3900 unsigned ModuleValueListSize = ValueList.size(); 3901 unsigned ModuleMDLoaderSize = MDLoader->size(); 3902 3903 // Add all the function arguments to the value table. 3904 #ifndef NDEBUG 3905 unsigned ArgNo = 0; 3906 FunctionType *FTy = FunctionTypes[F]; 3907 #endif 3908 for (Argument &I : F->args()) { 3909 assert(I.getType() == FTy->getParamType(ArgNo++) && 3910 "Incorrect fully specified type for Function Argument"); 3911 ValueList.push_back(&I); 3912 } 3913 unsigned NextValueNo = ValueList.size(); 3914 BasicBlock *CurBB = nullptr; 3915 unsigned CurBBNo = 0; 3916 3917 DebugLoc LastLoc; 3918 auto getLastInstruction = [&]() -> Instruction * { 3919 if (CurBB && !CurBB->empty()) 3920 return &CurBB->back(); 3921 else if (CurBBNo && FunctionBBs[CurBBNo - 1] && 3922 !FunctionBBs[CurBBNo - 1]->empty()) 3923 return &FunctionBBs[CurBBNo - 1]->back(); 3924 return nullptr; 3925 }; 3926 3927 std::vector<OperandBundleDef> OperandBundles; 3928 3929 // Read all the records. 3930 SmallVector<uint64_t, 64> Record; 3931 3932 while (true) { 3933 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance(); 3934 if (!MaybeEntry) 3935 return MaybeEntry.takeError(); 3936 llvm::BitstreamEntry Entry = MaybeEntry.get(); 3937 3938 switch (Entry.Kind) { 3939 case BitstreamEntry::Error: 3940 return error("Malformed block"); 3941 case BitstreamEntry::EndBlock: 3942 goto OutOfRecordLoop; 3943 3944 case BitstreamEntry::SubBlock: 3945 switch (Entry.ID) { 3946 default: // Skip unknown content. 3947 if (Error Err = Stream.SkipBlock()) 3948 return Err; 3949 break; 3950 case bitc::CONSTANTS_BLOCK_ID: 3951 if (Error Err = parseConstants()) 3952 return Err; 3953 NextValueNo = ValueList.size(); 3954 break; 3955 case bitc::VALUE_SYMTAB_BLOCK_ID: 3956 if (Error Err = parseValueSymbolTable()) 3957 return Err; 3958 break; 3959 case bitc::METADATA_ATTACHMENT_ID: 3960 if (Error Err = MDLoader->parseMetadataAttachment(*F, InstructionList)) 3961 return Err; 3962 break; 3963 case bitc::METADATA_BLOCK_ID: 3964 assert(DeferredMetadataInfo.empty() && 3965 "Must read all module-level metadata before function-level"); 3966 if (Error Err = MDLoader->parseFunctionMetadata()) 3967 return Err; 3968 break; 3969 case bitc::USELIST_BLOCK_ID: 3970 if (Error Err = parseUseLists()) 3971 return Err; 3972 break; 3973 } 3974 continue; 3975 3976 case BitstreamEntry::Record: 3977 // The interesting case. 3978 break; 3979 } 3980 3981 // Read a record. 3982 Record.clear(); 3983 Instruction *I = nullptr; 3984 Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record); 3985 if (!MaybeBitCode) 3986 return MaybeBitCode.takeError(); 3987 switch (unsigned BitCode = MaybeBitCode.get()) { 3988 default: // Default behavior: reject 3989 return error("Invalid value"); 3990 case bitc::FUNC_CODE_DECLAREBLOCKS: { // DECLAREBLOCKS: [nblocks] 3991 if (Record.empty() || Record[0] == 0) 3992 return error("Invalid record"); 3993 // Create all the basic blocks for the function. 3994 FunctionBBs.resize(Record[0]); 3995 3996 // See if anything took the address of blocks in this function. 3997 auto BBFRI = BasicBlockFwdRefs.find(F); 3998 if (BBFRI == BasicBlockFwdRefs.end()) { 3999 for (BasicBlock *&BB : FunctionBBs) 4000 BB = BasicBlock::Create(Context, "", F); 4001 } else { 4002 auto &BBRefs = BBFRI->second; 4003 // Check for invalid basic block references. 4004 if (BBRefs.size() > FunctionBBs.size()) 4005 return error("Invalid ID"); 4006 assert(!BBRefs.empty() && "Unexpected empty array"); 4007 assert(!BBRefs.front() && "Invalid reference to entry block"); 4008 for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E; 4009 ++I) 4010 if (I < RE && BBRefs[I]) { 4011 BBRefs[I]->insertInto(F); 4012 FunctionBBs[I] = BBRefs[I]; 4013 } else { 4014 FunctionBBs[I] = BasicBlock::Create(Context, "", F); 4015 } 4016 4017 // Erase from the table. 4018 BasicBlockFwdRefs.erase(BBFRI); 4019 } 4020 4021 CurBB = FunctionBBs[0]; 4022 continue; 4023 } 4024 4025 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN 4026 // This record indicates that the last instruction is at the same 4027 // location as the previous instruction with a location. 4028 I = getLastInstruction(); 4029 4030 if (!I) 4031 return error("Invalid record"); 4032 I->setDebugLoc(LastLoc); 4033 I = nullptr; 4034 continue; 4035 4036 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia] 4037 I = getLastInstruction(); 4038 if (!I || Record.size() < 4) 4039 return error("Invalid record"); 4040 4041 unsigned Line = Record[0], Col = Record[1]; 4042 unsigned ScopeID = Record[2], IAID = Record[3]; 4043 bool isImplicitCode = Record.size() == 5 && Record[4]; 4044 4045 MDNode *Scope = nullptr, *IA = nullptr; 4046 if (ScopeID) { 4047 Scope = dyn_cast_or_null<MDNode>( 4048 MDLoader->getMetadataFwdRefOrLoad(ScopeID - 1)); 4049 if (!Scope) 4050 return error("Invalid record"); 4051 } 4052 if (IAID) { 4053 IA = dyn_cast_or_null<MDNode>( 4054 MDLoader->getMetadataFwdRefOrLoad(IAID - 1)); 4055 if (!IA) 4056 return error("Invalid record"); 4057 } 4058 LastLoc = DILocation::get(Scope->getContext(), Line, Col, Scope, IA, 4059 isImplicitCode); 4060 I->setDebugLoc(LastLoc); 4061 I = nullptr; 4062 continue; 4063 } 4064 case bitc::FUNC_CODE_INST_UNOP: { // UNOP: [opval, ty, opcode] 4065 unsigned OpNum = 0; 4066 Value *LHS; 4067 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) || 4068 OpNum+1 > Record.size()) 4069 return error("Invalid record"); 4070 4071 int Opc = getDecodedUnaryOpcode(Record[OpNum++], LHS->getType()); 4072 if (Opc == -1) 4073 return error("Invalid record"); 4074 I = UnaryOperator::Create((Instruction::UnaryOps)Opc, LHS); 4075 InstructionList.push_back(I); 4076 if (OpNum < Record.size()) { 4077 if (isa<FPMathOperator>(I)) { 4078 FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]); 4079 if (FMF.any()) 4080 I->setFastMathFlags(FMF); 4081 } 4082 } 4083 break; 4084 } 4085 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode] 4086 unsigned OpNum = 0; 4087 Value *LHS, *RHS; 4088 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) || 4089 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) || 4090 OpNum+1 > Record.size()) 4091 return error("Invalid record"); 4092 4093 int Opc = getDecodedBinaryOpcode(Record[OpNum++], LHS->getType()); 4094 if (Opc == -1) 4095 return error("Invalid record"); 4096 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS); 4097 InstructionList.push_back(I); 4098 if (OpNum < Record.size()) { 4099 if (Opc == Instruction::Add || 4100 Opc == Instruction::Sub || 4101 Opc == Instruction::Mul || 4102 Opc == Instruction::Shl) { 4103 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP)) 4104 cast<BinaryOperator>(I)->setHasNoSignedWrap(true); 4105 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP)) 4106 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true); 4107 } else if (Opc == Instruction::SDiv || 4108 Opc == Instruction::UDiv || 4109 Opc == Instruction::LShr || 4110 Opc == Instruction::AShr) { 4111 if (Record[OpNum] & (1 << bitc::PEO_EXACT)) 4112 cast<BinaryOperator>(I)->setIsExact(true); 4113 } else if (isa<FPMathOperator>(I)) { 4114 FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]); 4115 if (FMF.any()) 4116 I->setFastMathFlags(FMF); 4117 } 4118 4119 } 4120 break; 4121 } 4122 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc] 4123 unsigned OpNum = 0; 4124 Value *Op; 4125 if (getValueTypePair(Record, OpNum, NextValueNo, Op) || 4126 OpNum+2 != Record.size()) 4127 return error("Invalid record"); 4128 4129 Type *ResTy = getTypeByID(Record[OpNum]); 4130 int Opc = getDecodedCastOpcode(Record[OpNum + 1]); 4131 if (Opc == -1 || !ResTy) 4132 return error("Invalid record"); 4133 Instruction *Temp = nullptr; 4134 if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) { 4135 if (Temp) { 4136 InstructionList.push_back(Temp); 4137 assert(CurBB && "No current BB?"); 4138 CurBB->getInstList().push_back(Temp); 4139 } 4140 } else { 4141 auto CastOp = (Instruction::CastOps)Opc; 4142 if (!CastInst::castIsValid(CastOp, Op, ResTy)) 4143 return error("Invalid cast"); 4144 I = CastInst::Create(CastOp, Op, ResTy); 4145 } 4146 InstructionList.push_back(I); 4147 break; 4148 } 4149 case bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD: 4150 case bitc::FUNC_CODE_INST_GEP_OLD: 4151 case bitc::FUNC_CODE_INST_GEP: { // GEP: type, [n x operands] 4152 unsigned OpNum = 0; 4153 4154 Type *Ty; 4155 bool InBounds; 4156 4157 if (BitCode == bitc::FUNC_CODE_INST_GEP) { 4158 InBounds = Record[OpNum++]; 4159 Ty = getTypeByID(Record[OpNum++]); 4160 } else { 4161 InBounds = BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD; 4162 Ty = nullptr; 4163 } 4164 4165 Value *BasePtr; 4166 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr)) 4167 return error("Invalid record"); 4168 4169 if (!Ty) { 4170 Ty = cast<PointerType>(BasePtr->getType()->getScalarType()) 4171 ->getElementType(); 4172 } else if (!cast<PointerType>(BasePtr->getType()->getScalarType()) 4173 ->isOpaqueOrPointeeTypeMatches(Ty)) { 4174 return error( 4175 "Explicit gep type does not match pointee type of pointer operand"); 4176 } 4177 4178 SmallVector<Value*, 16> GEPIdx; 4179 while (OpNum != Record.size()) { 4180 Value *Op; 4181 if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 4182 return error("Invalid record"); 4183 GEPIdx.push_back(Op); 4184 } 4185 4186 I = GetElementPtrInst::Create(Ty, BasePtr, GEPIdx); 4187 4188 InstructionList.push_back(I); 4189 if (InBounds) 4190 cast<GetElementPtrInst>(I)->setIsInBounds(true); 4191 break; 4192 } 4193 4194 case bitc::FUNC_CODE_INST_EXTRACTVAL: { 4195 // EXTRACTVAL: [opty, opval, n x indices] 4196 unsigned OpNum = 0; 4197 Value *Agg; 4198 if (getValueTypePair(Record, OpNum, NextValueNo, Agg)) 4199 return error("Invalid record"); 4200 Type *Ty = Agg->getType(); 4201 4202 unsigned RecSize = Record.size(); 4203 if (OpNum == RecSize) 4204 return error("EXTRACTVAL: Invalid instruction with 0 indices"); 4205 4206 SmallVector<unsigned, 4> EXTRACTVALIdx; 4207 for (; OpNum != RecSize; ++OpNum) { 4208 bool IsArray = Ty->isArrayTy(); 4209 bool IsStruct = Ty->isStructTy(); 4210 uint64_t Index = Record[OpNum]; 4211 4212 if (!IsStruct && !IsArray) 4213 return error("EXTRACTVAL: Invalid type"); 4214 if ((unsigned)Index != Index) 4215 return error("Invalid value"); 4216 if (IsStruct && Index >= Ty->getStructNumElements()) 4217 return error("EXTRACTVAL: Invalid struct index"); 4218 if (IsArray && Index >= Ty->getArrayNumElements()) 4219 return error("EXTRACTVAL: Invalid array index"); 4220 EXTRACTVALIdx.push_back((unsigned)Index); 4221 4222 if (IsStruct) 4223 Ty = Ty->getStructElementType(Index); 4224 else 4225 Ty = Ty->getArrayElementType(); 4226 } 4227 4228 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx); 4229 InstructionList.push_back(I); 4230 break; 4231 } 4232 4233 case bitc::FUNC_CODE_INST_INSERTVAL: { 4234 // INSERTVAL: [opty, opval, opty, opval, n x indices] 4235 unsigned OpNum = 0; 4236 Value *Agg; 4237 if (getValueTypePair(Record, OpNum, NextValueNo, Agg)) 4238 return error("Invalid record"); 4239 Value *Val; 4240 if (getValueTypePair(Record, OpNum, NextValueNo, Val)) 4241 return error("Invalid record"); 4242 4243 unsigned RecSize = Record.size(); 4244 if (OpNum == RecSize) 4245 return error("INSERTVAL: Invalid instruction with 0 indices"); 4246 4247 SmallVector<unsigned, 4> INSERTVALIdx; 4248 Type *CurTy = Agg->getType(); 4249 for (; OpNum != RecSize; ++OpNum) { 4250 bool IsArray = CurTy->isArrayTy(); 4251 bool IsStruct = CurTy->isStructTy(); 4252 uint64_t Index = Record[OpNum]; 4253 4254 if (!IsStruct && !IsArray) 4255 return error("INSERTVAL: Invalid type"); 4256 if ((unsigned)Index != Index) 4257 return error("Invalid value"); 4258 if (IsStruct && Index >= CurTy->getStructNumElements()) 4259 return error("INSERTVAL: Invalid struct index"); 4260 if (IsArray && Index >= CurTy->getArrayNumElements()) 4261 return error("INSERTVAL: Invalid array index"); 4262 4263 INSERTVALIdx.push_back((unsigned)Index); 4264 if (IsStruct) 4265 CurTy = CurTy->getStructElementType(Index); 4266 else 4267 CurTy = CurTy->getArrayElementType(); 4268 } 4269 4270 if (CurTy != Val->getType()) 4271 return error("Inserted value type doesn't match aggregate type"); 4272 4273 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx); 4274 InstructionList.push_back(I); 4275 break; 4276 } 4277 4278 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval] 4279 // obsolete form of select 4280 // handles select i1 ... in old bitcode 4281 unsigned OpNum = 0; 4282 Value *TrueVal, *FalseVal, *Cond; 4283 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) || 4284 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) || 4285 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond)) 4286 return error("Invalid record"); 4287 4288 I = SelectInst::Create(Cond, TrueVal, FalseVal); 4289 InstructionList.push_back(I); 4290 break; 4291 } 4292 4293 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred] 4294 // new form of select 4295 // handles select i1 or select [N x i1] 4296 unsigned OpNum = 0; 4297 Value *TrueVal, *FalseVal, *Cond; 4298 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) || 4299 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) || 4300 getValueTypePair(Record, OpNum, NextValueNo, Cond)) 4301 return error("Invalid record"); 4302 4303 // select condition can be either i1 or [N x i1] 4304 if (VectorType* vector_type = 4305 dyn_cast<VectorType>(Cond->getType())) { 4306 // expect <n x i1> 4307 if (vector_type->getElementType() != Type::getInt1Ty(Context)) 4308 return error("Invalid type for value"); 4309 } else { 4310 // expect i1 4311 if (Cond->getType() != Type::getInt1Ty(Context)) 4312 return error("Invalid type for value"); 4313 } 4314 4315 I = SelectInst::Create(Cond, TrueVal, FalseVal); 4316 InstructionList.push_back(I); 4317 if (OpNum < Record.size() && isa<FPMathOperator>(I)) { 4318 FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]); 4319 if (FMF.any()) 4320 I->setFastMathFlags(FMF); 4321 } 4322 break; 4323 } 4324 4325 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval] 4326 unsigned OpNum = 0; 4327 Value *Vec, *Idx; 4328 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) || 4329 getValueTypePair(Record, OpNum, NextValueNo, Idx)) 4330 return error("Invalid record"); 4331 if (!Vec->getType()->isVectorTy()) 4332 return error("Invalid type for value"); 4333 I = ExtractElementInst::Create(Vec, Idx); 4334 InstructionList.push_back(I); 4335 break; 4336 } 4337 4338 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval] 4339 unsigned OpNum = 0; 4340 Value *Vec, *Elt, *Idx; 4341 if (getValueTypePair(Record, OpNum, NextValueNo, Vec)) 4342 return error("Invalid record"); 4343 if (!Vec->getType()->isVectorTy()) 4344 return error("Invalid type for value"); 4345 if (popValue(Record, OpNum, NextValueNo, 4346 cast<VectorType>(Vec->getType())->getElementType(), Elt) || 4347 getValueTypePair(Record, OpNum, NextValueNo, Idx)) 4348 return error("Invalid record"); 4349 I = InsertElementInst::Create(Vec, Elt, Idx); 4350 InstructionList.push_back(I); 4351 break; 4352 } 4353 4354 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval] 4355 unsigned OpNum = 0; 4356 Value *Vec1, *Vec2, *Mask; 4357 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) || 4358 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2)) 4359 return error("Invalid record"); 4360 4361 if (getValueTypePair(Record, OpNum, NextValueNo, Mask)) 4362 return error("Invalid record"); 4363 if (!Vec1->getType()->isVectorTy() || !Vec2->getType()->isVectorTy()) 4364 return error("Invalid type for value"); 4365 4366 I = new ShuffleVectorInst(Vec1, Vec2, Mask); 4367 InstructionList.push_back(I); 4368 break; 4369 } 4370 4371 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred] 4372 // Old form of ICmp/FCmp returning bool 4373 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were 4374 // both legal on vectors but had different behaviour. 4375 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred] 4376 // FCmp/ICmp returning bool or vector of bool 4377 4378 unsigned OpNum = 0; 4379 Value *LHS, *RHS; 4380 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) || 4381 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS)) 4382 return error("Invalid record"); 4383 4384 if (OpNum >= Record.size()) 4385 return error( 4386 "Invalid record: operand number exceeded available operands"); 4387 4388 unsigned PredVal = Record[OpNum]; 4389 bool IsFP = LHS->getType()->isFPOrFPVectorTy(); 4390 FastMathFlags FMF; 4391 if (IsFP && Record.size() > OpNum+1) 4392 FMF = getDecodedFastMathFlags(Record[++OpNum]); 4393 4394 if (OpNum+1 != Record.size()) 4395 return error("Invalid record"); 4396 4397 if (LHS->getType()->isFPOrFPVectorTy()) 4398 I = new FCmpInst((FCmpInst::Predicate)PredVal, LHS, RHS); 4399 else 4400 I = new ICmpInst((ICmpInst::Predicate)PredVal, LHS, RHS); 4401 4402 if (FMF.any()) 4403 I->setFastMathFlags(FMF); 4404 InstructionList.push_back(I); 4405 break; 4406 } 4407 4408 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>] 4409 { 4410 unsigned Size = Record.size(); 4411 if (Size == 0) { 4412 I = ReturnInst::Create(Context); 4413 InstructionList.push_back(I); 4414 break; 4415 } 4416 4417 unsigned OpNum = 0; 4418 Value *Op = nullptr; 4419 if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 4420 return error("Invalid record"); 4421 if (OpNum != Record.size()) 4422 return error("Invalid record"); 4423 4424 I = ReturnInst::Create(Context, Op); 4425 InstructionList.push_back(I); 4426 break; 4427 } 4428 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#] 4429 if (Record.size() != 1 && Record.size() != 3) 4430 return error("Invalid record"); 4431 BasicBlock *TrueDest = getBasicBlock(Record[0]); 4432 if (!TrueDest) 4433 return error("Invalid record"); 4434 4435 if (Record.size() == 1) { 4436 I = BranchInst::Create(TrueDest); 4437 InstructionList.push_back(I); 4438 } 4439 else { 4440 BasicBlock *FalseDest = getBasicBlock(Record[1]); 4441 Value *Cond = getValue(Record, 2, NextValueNo, 4442 Type::getInt1Ty(Context)); 4443 if (!FalseDest || !Cond) 4444 return error("Invalid record"); 4445 I = BranchInst::Create(TrueDest, FalseDest, Cond); 4446 InstructionList.push_back(I); 4447 } 4448 break; 4449 } 4450 case bitc::FUNC_CODE_INST_CLEANUPRET: { // CLEANUPRET: [val] or [val,bb#] 4451 if (Record.size() != 1 && Record.size() != 2) 4452 return error("Invalid record"); 4453 unsigned Idx = 0; 4454 Value *CleanupPad = 4455 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context)); 4456 if (!CleanupPad) 4457 return error("Invalid record"); 4458 BasicBlock *UnwindDest = nullptr; 4459 if (Record.size() == 2) { 4460 UnwindDest = getBasicBlock(Record[Idx++]); 4461 if (!UnwindDest) 4462 return error("Invalid record"); 4463 } 4464 4465 I = CleanupReturnInst::Create(CleanupPad, UnwindDest); 4466 InstructionList.push_back(I); 4467 break; 4468 } 4469 case bitc::FUNC_CODE_INST_CATCHRET: { // CATCHRET: [val,bb#] 4470 if (Record.size() != 2) 4471 return error("Invalid record"); 4472 unsigned Idx = 0; 4473 Value *CatchPad = 4474 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context)); 4475 if (!CatchPad) 4476 return error("Invalid record"); 4477 BasicBlock *BB = getBasicBlock(Record[Idx++]); 4478 if (!BB) 4479 return error("Invalid record"); 4480 4481 I = CatchReturnInst::Create(CatchPad, BB); 4482 InstructionList.push_back(I); 4483 break; 4484 } 4485 case bitc::FUNC_CODE_INST_CATCHSWITCH: { // CATCHSWITCH: [tok,num,(bb)*,bb?] 4486 // We must have, at minimum, the outer scope and the number of arguments. 4487 if (Record.size() < 2) 4488 return error("Invalid record"); 4489 4490 unsigned Idx = 0; 4491 4492 Value *ParentPad = 4493 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context)); 4494 4495 unsigned NumHandlers = Record[Idx++]; 4496 4497 SmallVector<BasicBlock *, 2> Handlers; 4498 for (unsigned Op = 0; Op != NumHandlers; ++Op) { 4499 BasicBlock *BB = getBasicBlock(Record[Idx++]); 4500 if (!BB) 4501 return error("Invalid record"); 4502 Handlers.push_back(BB); 4503 } 4504 4505 BasicBlock *UnwindDest = nullptr; 4506 if (Idx + 1 == Record.size()) { 4507 UnwindDest = getBasicBlock(Record[Idx++]); 4508 if (!UnwindDest) 4509 return error("Invalid record"); 4510 } 4511 4512 if (Record.size() != Idx) 4513 return error("Invalid record"); 4514 4515 auto *CatchSwitch = 4516 CatchSwitchInst::Create(ParentPad, UnwindDest, NumHandlers); 4517 for (BasicBlock *Handler : Handlers) 4518 CatchSwitch->addHandler(Handler); 4519 I = CatchSwitch; 4520 InstructionList.push_back(I); 4521 break; 4522 } 4523 case bitc::FUNC_CODE_INST_CATCHPAD: 4524 case bitc::FUNC_CODE_INST_CLEANUPPAD: { // [tok,num,(ty,val)*] 4525 // We must have, at minimum, the outer scope and the number of arguments. 4526 if (Record.size() < 2) 4527 return error("Invalid record"); 4528 4529 unsigned Idx = 0; 4530 4531 Value *ParentPad = 4532 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context)); 4533 4534 unsigned NumArgOperands = Record[Idx++]; 4535 4536 SmallVector<Value *, 2> Args; 4537 for (unsigned Op = 0; Op != NumArgOperands; ++Op) { 4538 Value *Val; 4539 if (getValueTypePair(Record, Idx, NextValueNo, Val)) 4540 return error("Invalid record"); 4541 Args.push_back(Val); 4542 } 4543 4544 if (Record.size() != Idx) 4545 return error("Invalid record"); 4546 4547 if (BitCode == bitc::FUNC_CODE_INST_CLEANUPPAD) 4548 I = CleanupPadInst::Create(ParentPad, Args); 4549 else 4550 I = CatchPadInst::Create(ParentPad, Args); 4551 InstructionList.push_back(I); 4552 break; 4553 } 4554 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...] 4555 // Check magic 4556 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) { 4557 // "New" SwitchInst format with case ranges. The changes to write this 4558 // format were reverted but we still recognize bitcode that uses it. 4559 // Hopefully someday we will have support for case ranges and can use 4560 // this format again. 4561 4562 Type *OpTy = getTypeByID(Record[1]); 4563 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth(); 4564 4565 Value *Cond = getValue(Record, 2, NextValueNo, OpTy); 4566 BasicBlock *Default = getBasicBlock(Record[3]); 4567 if (!OpTy || !Cond || !Default) 4568 return error("Invalid record"); 4569 4570 unsigned NumCases = Record[4]; 4571 4572 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases); 4573 InstructionList.push_back(SI); 4574 4575 unsigned CurIdx = 5; 4576 for (unsigned i = 0; i != NumCases; ++i) { 4577 SmallVector<ConstantInt*, 1> CaseVals; 4578 unsigned NumItems = Record[CurIdx++]; 4579 for (unsigned ci = 0; ci != NumItems; ++ci) { 4580 bool isSingleNumber = Record[CurIdx++]; 4581 4582 APInt Low; 4583 unsigned ActiveWords = 1; 4584 if (ValueBitWidth > 64) 4585 ActiveWords = Record[CurIdx++]; 4586 Low = readWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords), 4587 ValueBitWidth); 4588 CurIdx += ActiveWords; 4589 4590 if (!isSingleNumber) { 4591 ActiveWords = 1; 4592 if (ValueBitWidth > 64) 4593 ActiveWords = Record[CurIdx++]; 4594 APInt High = readWideAPInt( 4595 makeArrayRef(&Record[CurIdx], ActiveWords), ValueBitWidth); 4596 CurIdx += ActiveWords; 4597 4598 // FIXME: It is not clear whether values in the range should be 4599 // compared as signed or unsigned values. The partially 4600 // implemented changes that used this format in the past used 4601 // unsigned comparisons. 4602 for ( ; Low.ule(High); ++Low) 4603 CaseVals.push_back(ConstantInt::get(Context, Low)); 4604 } else 4605 CaseVals.push_back(ConstantInt::get(Context, Low)); 4606 } 4607 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]); 4608 for (ConstantInt *Cst : CaseVals) 4609 SI->addCase(Cst, DestBB); 4610 } 4611 I = SI; 4612 break; 4613 } 4614 4615 // Old SwitchInst format without case ranges. 4616 4617 if (Record.size() < 3 || (Record.size() & 1) == 0) 4618 return error("Invalid record"); 4619 Type *OpTy = getTypeByID(Record[0]); 4620 Value *Cond = getValue(Record, 1, NextValueNo, OpTy); 4621 BasicBlock *Default = getBasicBlock(Record[2]); 4622 if (!OpTy || !Cond || !Default) 4623 return error("Invalid record"); 4624 unsigned NumCases = (Record.size()-3)/2; 4625 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases); 4626 InstructionList.push_back(SI); 4627 for (unsigned i = 0, e = NumCases; i != e; ++i) { 4628 ConstantInt *CaseVal = 4629 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy)); 4630 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]); 4631 if (!CaseVal || !DestBB) { 4632 delete SI; 4633 return error("Invalid record"); 4634 } 4635 SI->addCase(CaseVal, DestBB); 4636 } 4637 I = SI; 4638 break; 4639 } 4640 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...] 4641 if (Record.size() < 2) 4642 return error("Invalid record"); 4643 Type *OpTy = getTypeByID(Record[0]); 4644 Value *Address = getValue(Record, 1, NextValueNo, OpTy); 4645 if (!OpTy || !Address) 4646 return error("Invalid record"); 4647 unsigned NumDests = Record.size()-2; 4648 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests); 4649 InstructionList.push_back(IBI); 4650 for (unsigned i = 0, e = NumDests; i != e; ++i) { 4651 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) { 4652 IBI->addDestination(DestBB); 4653 } else { 4654 delete IBI; 4655 return error("Invalid record"); 4656 } 4657 } 4658 I = IBI; 4659 break; 4660 } 4661 4662 case bitc::FUNC_CODE_INST_INVOKE: { 4663 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...] 4664 if (Record.size() < 4) 4665 return error("Invalid record"); 4666 unsigned OpNum = 0; 4667 AttributeList PAL = getAttributes(Record[OpNum++]); 4668 unsigned CCInfo = Record[OpNum++]; 4669 BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]); 4670 BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]); 4671 4672 FunctionType *FTy = nullptr; 4673 if ((CCInfo >> 13) & 1) { 4674 FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++])); 4675 if (!FTy) 4676 return error("Explicit invoke type is not a function type"); 4677 } 4678 4679 Value *Callee; 4680 if (getValueTypePair(Record, OpNum, NextValueNo, Callee)) 4681 return error("Invalid record"); 4682 4683 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType()); 4684 if (!CalleeTy) 4685 return error("Callee is not a pointer"); 4686 if (!FTy) { 4687 FTy = dyn_cast<FunctionType>( 4688 cast<PointerType>(Callee->getType())->getElementType()); 4689 if (!FTy) 4690 return error("Callee is not of pointer to function type"); 4691 } else if (!CalleeTy->isOpaqueOrPointeeTypeMatches(FTy)) 4692 return error("Explicit invoke type does not match pointee type of " 4693 "callee operand"); 4694 if (Record.size() < FTy->getNumParams() + OpNum) 4695 return error("Insufficient operands to call"); 4696 4697 SmallVector<Value*, 16> Ops; 4698 SmallVector<Type *, 16> ArgsTys; 4699 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) { 4700 Ops.push_back(getValue(Record, OpNum, NextValueNo, 4701 FTy->getParamType(i))); 4702 ArgsTys.push_back(FTy->getParamType(i)); 4703 if (!Ops.back()) 4704 return error("Invalid record"); 4705 } 4706 4707 if (!FTy->isVarArg()) { 4708 if (Record.size() != OpNum) 4709 return error("Invalid record"); 4710 } else { 4711 // Read type/value pairs for varargs params. 4712 while (OpNum != Record.size()) { 4713 Value *Op; 4714 if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 4715 return error("Invalid record"); 4716 Ops.push_back(Op); 4717 ArgsTys.push_back(Op->getType()); 4718 } 4719 } 4720 4721 I = InvokeInst::Create(FTy, Callee, NormalBB, UnwindBB, Ops, 4722 OperandBundles); 4723 OperandBundles.clear(); 4724 InstructionList.push_back(I); 4725 cast<InvokeInst>(I)->setCallingConv( 4726 static_cast<CallingConv::ID>(CallingConv::MaxID & CCInfo)); 4727 cast<InvokeInst>(I)->setAttributes(PAL); 4728 propagateAttributeTypes(cast<CallBase>(I), ArgsTys); 4729 4730 break; 4731 } 4732 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval] 4733 unsigned Idx = 0; 4734 Value *Val = nullptr; 4735 if (getValueTypePair(Record, Idx, NextValueNo, Val)) 4736 return error("Invalid record"); 4737 I = ResumeInst::Create(Val); 4738 InstructionList.push_back(I); 4739 break; 4740 } 4741 case bitc::FUNC_CODE_INST_CALLBR: { 4742 // CALLBR: [attr, cc, norm, transfs, fty, fnid, args] 4743 unsigned OpNum = 0; 4744 AttributeList PAL = getAttributes(Record[OpNum++]); 4745 unsigned CCInfo = Record[OpNum++]; 4746 4747 BasicBlock *DefaultDest = getBasicBlock(Record[OpNum++]); 4748 unsigned NumIndirectDests = Record[OpNum++]; 4749 SmallVector<BasicBlock *, 16> IndirectDests; 4750 for (unsigned i = 0, e = NumIndirectDests; i != e; ++i) 4751 IndirectDests.push_back(getBasicBlock(Record[OpNum++])); 4752 4753 FunctionType *FTy = nullptr; 4754 if ((CCInfo >> bitc::CALL_EXPLICIT_TYPE) & 1) { 4755 FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++])); 4756 if (!FTy) 4757 return error("Explicit call type is not a function type"); 4758 } 4759 4760 Value *Callee; 4761 if (getValueTypePair(Record, OpNum, NextValueNo, Callee)) 4762 return error("Invalid record"); 4763 4764 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType()); 4765 if (!OpTy) 4766 return error("Callee is not a pointer type"); 4767 if (!FTy) { 4768 FTy = dyn_cast<FunctionType>( 4769 cast<PointerType>(Callee->getType())->getElementType()); 4770 if (!FTy) 4771 return error("Callee is not of pointer to function type"); 4772 } else if (cast<PointerType>(Callee->getType())->getElementType() != FTy) 4773 return error("Explicit call type does not match pointee type of " 4774 "callee operand"); 4775 if (Record.size() < FTy->getNumParams() + OpNum) 4776 return error("Insufficient operands to call"); 4777 4778 SmallVector<Value*, 16> Args; 4779 // Read the fixed params. 4780 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) { 4781 if (FTy->getParamType(i)->isLabelTy()) 4782 Args.push_back(getBasicBlock(Record[OpNum])); 4783 else 4784 Args.push_back(getValue(Record, OpNum, NextValueNo, 4785 FTy->getParamType(i))); 4786 if (!Args.back()) 4787 return error("Invalid record"); 4788 } 4789 4790 // Read type/value pairs for varargs params. 4791 if (!FTy->isVarArg()) { 4792 if (OpNum != Record.size()) 4793 return error("Invalid record"); 4794 } else { 4795 while (OpNum != Record.size()) { 4796 Value *Op; 4797 if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 4798 return error("Invalid record"); 4799 Args.push_back(Op); 4800 } 4801 } 4802 4803 I = CallBrInst::Create(FTy, Callee, DefaultDest, IndirectDests, Args, 4804 OperandBundles); 4805 OperandBundles.clear(); 4806 InstructionList.push_back(I); 4807 cast<CallBrInst>(I)->setCallingConv( 4808 static_cast<CallingConv::ID>((0x7ff & CCInfo) >> bitc::CALL_CCONV)); 4809 cast<CallBrInst>(I)->setAttributes(PAL); 4810 break; 4811 } 4812 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE 4813 I = new UnreachableInst(Context); 4814 InstructionList.push_back(I); 4815 break; 4816 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...] 4817 if (Record.empty()) 4818 return error("Invalid record"); 4819 // The first record specifies the type. 4820 Type *Ty = getTypeByID(Record[0]); 4821 if (!Ty) 4822 return error("Invalid record"); 4823 4824 // Phi arguments are pairs of records of [value, basic block]. 4825 // There is an optional final record for fast-math-flags if this phi has a 4826 // floating-point type. 4827 size_t NumArgs = (Record.size() - 1) / 2; 4828 PHINode *PN = PHINode::Create(Ty, NumArgs); 4829 if ((Record.size() - 1) % 2 == 1 && !isa<FPMathOperator>(PN)) 4830 return error("Invalid record"); 4831 InstructionList.push_back(PN); 4832 4833 for (unsigned i = 0; i != NumArgs; i++) { 4834 Value *V; 4835 // With the new function encoding, it is possible that operands have 4836 // negative IDs (for forward references). Use a signed VBR 4837 // representation to keep the encoding small. 4838 if (UseRelativeIDs) 4839 V = getValueSigned(Record, i * 2 + 1, NextValueNo, Ty); 4840 else 4841 V = getValue(Record, i * 2 + 1, NextValueNo, Ty); 4842 BasicBlock *BB = getBasicBlock(Record[i * 2 + 2]); 4843 if (!V || !BB) 4844 return error("Invalid record"); 4845 PN->addIncoming(V, BB); 4846 } 4847 I = PN; 4848 4849 // If there are an even number of records, the final record must be FMF. 4850 if (Record.size() % 2 == 0) { 4851 assert(isa<FPMathOperator>(I) && "Unexpected phi type"); 4852 FastMathFlags FMF = getDecodedFastMathFlags(Record[Record.size() - 1]); 4853 if (FMF.any()) 4854 I->setFastMathFlags(FMF); 4855 } 4856 4857 break; 4858 } 4859 4860 case bitc::FUNC_CODE_INST_LANDINGPAD: 4861 case bitc::FUNC_CODE_INST_LANDINGPAD_OLD: { 4862 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?] 4863 unsigned Idx = 0; 4864 if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD) { 4865 if (Record.size() < 3) 4866 return error("Invalid record"); 4867 } else { 4868 assert(BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD); 4869 if (Record.size() < 4) 4870 return error("Invalid record"); 4871 } 4872 Type *Ty = getTypeByID(Record[Idx++]); 4873 if (!Ty) 4874 return error("Invalid record"); 4875 if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD) { 4876 Value *PersFn = nullptr; 4877 if (getValueTypePair(Record, Idx, NextValueNo, PersFn)) 4878 return error("Invalid record"); 4879 4880 if (!F->hasPersonalityFn()) 4881 F->setPersonalityFn(cast<Constant>(PersFn)); 4882 else if (F->getPersonalityFn() != cast<Constant>(PersFn)) 4883 return error("Personality function mismatch"); 4884 } 4885 4886 bool IsCleanup = !!Record[Idx++]; 4887 unsigned NumClauses = Record[Idx++]; 4888 LandingPadInst *LP = LandingPadInst::Create(Ty, NumClauses); 4889 LP->setCleanup(IsCleanup); 4890 for (unsigned J = 0; J != NumClauses; ++J) { 4891 LandingPadInst::ClauseType CT = 4892 LandingPadInst::ClauseType(Record[Idx++]); (void)CT; 4893 Value *Val; 4894 4895 if (getValueTypePair(Record, Idx, NextValueNo, Val)) { 4896 delete LP; 4897 return error("Invalid record"); 4898 } 4899 4900 assert((CT != LandingPadInst::Catch || 4901 !isa<ArrayType>(Val->getType())) && 4902 "Catch clause has a invalid type!"); 4903 assert((CT != LandingPadInst::Filter || 4904 isa<ArrayType>(Val->getType())) && 4905 "Filter clause has invalid type!"); 4906 LP->addClause(cast<Constant>(Val)); 4907 } 4908 4909 I = LP; 4910 InstructionList.push_back(I); 4911 break; 4912 } 4913 4914 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align] 4915 if (Record.size() != 4) 4916 return error("Invalid record"); 4917 using APV = AllocaPackedValues; 4918 const uint64_t Rec = Record[3]; 4919 const bool InAlloca = Bitfield::get<APV::UsedWithInAlloca>(Rec); 4920 const bool SwiftError = Bitfield::get<APV::SwiftError>(Rec); 4921 Type *Ty = getTypeByID(Record[0]); 4922 if (!Bitfield::get<APV::ExplicitType>(Rec)) { 4923 auto *PTy = dyn_cast_or_null<PointerType>(Ty); 4924 if (!PTy) 4925 return error("Old-style alloca with a non-pointer type"); 4926 Ty = PTy->getElementType(); 4927 } 4928 Type *OpTy = getTypeByID(Record[1]); 4929 Value *Size = getFnValueByID(Record[2], OpTy); 4930 MaybeAlign Align; 4931 uint64_t AlignExp = 4932 Bitfield::get<APV::AlignLower>(Rec) | 4933 (Bitfield::get<APV::AlignUpper>(Rec) << APV::AlignLower::Bits); 4934 if (Error Err = parseAlignmentValue(AlignExp, Align)) { 4935 return Err; 4936 } 4937 if (!Ty || !Size) 4938 return error("Invalid record"); 4939 4940 // FIXME: Make this an optional field. 4941 const DataLayout &DL = TheModule->getDataLayout(); 4942 unsigned AS = DL.getAllocaAddrSpace(); 4943 4944 SmallPtrSet<Type *, 4> Visited; 4945 if (!Align && !Ty->isSized(&Visited)) 4946 return error("alloca of unsized type"); 4947 if (!Align) 4948 Align = DL.getPrefTypeAlign(Ty); 4949 4950 AllocaInst *AI = new AllocaInst(Ty, AS, Size, *Align); 4951 AI->setUsedWithInAlloca(InAlloca); 4952 AI->setSwiftError(SwiftError); 4953 I = AI; 4954 InstructionList.push_back(I); 4955 break; 4956 } 4957 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol] 4958 unsigned OpNum = 0; 4959 Value *Op; 4960 if (getValueTypePair(Record, OpNum, NextValueNo, Op) || 4961 (OpNum + 2 != Record.size() && OpNum + 3 != Record.size())) 4962 return error("Invalid record"); 4963 4964 if (!isa<PointerType>(Op->getType())) 4965 return error("Load operand is not a pointer type"); 4966 4967 Type *Ty = nullptr; 4968 if (OpNum + 3 == Record.size()) { 4969 Ty = getTypeByID(Record[OpNum++]); 4970 } else { 4971 Ty = cast<PointerType>(Op->getType())->getElementType(); 4972 } 4973 4974 if (Error Err = typeCheckLoadStoreInst(Ty, Op->getType())) 4975 return Err; 4976 4977 MaybeAlign Align; 4978 if (Error Err = parseAlignmentValue(Record[OpNum], Align)) 4979 return Err; 4980 SmallPtrSet<Type *, 4> Visited; 4981 if (!Align && !Ty->isSized(&Visited)) 4982 return error("load of unsized type"); 4983 if (!Align) 4984 Align = TheModule->getDataLayout().getABITypeAlign(Ty); 4985 I = new LoadInst(Ty, Op, "", Record[OpNum + 1], *Align); 4986 InstructionList.push_back(I); 4987 break; 4988 } 4989 case bitc::FUNC_CODE_INST_LOADATOMIC: { 4990 // LOADATOMIC: [opty, op, align, vol, ordering, ssid] 4991 unsigned OpNum = 0; 4992 Value *Op; 4993 if (getValueTypePair(Record, OpNum, NextValueNo, Op) || 4994 (OpNum + 4 != Record.size() && OpNum + 5 != Record.size())) 4995 return error("Invalid record"); 4996 4997 if (!isa<PointerType>(Op->getType())) 4998 return error("Load operand is not a pointer type"); 4999 5000 Type *Ty = nullptr; 5001 if (OpNum + 5 == Record.size()) { 5002 Ty = getTypeByID(Record[OpNum++]); 5003 } else { 5004 Ty = cast<PointerType>(Op->getType())->getElementType(); 5005 } 5006 5007 if (Error Err = typeCheckLoadStoreInst(Ty, Op->getType())) 5008 return Err; 5009 5010 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]); 5011 if (Ordering == AtomicOrdering::NotAtomic || 5012 Ordering == AtomicOrdering::Release || 5013 Ordering == AtomicOrdering::AcquireRelease) 5014 return error("Invalid record"); 5015 if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0) 5016 return error("Invalid record"); 5017 SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]); 5018 5019 MaybeAlign Align; 5020 if (Error Err = parseAlignmentValue(Record[OpNum], Align)) 5021 return Err; 5022 if (!Align) 5023 return error("Alignment missing from atomic load"); 5024 I = new LoadInst(Ty, Op, "", Record[OpNum + 1], *Align, Ordering, SSID); 5025 InstructionList.push_back(I); 5026 break; 5027 } 5028 case bitc::FUNC_CODE_INST_STORE: 5029 case bitc::FUNC_CODE_INST_STORE_OLD: { // STORE2:[ptrty, ptr, val, align, vol] 5030 unsigned OpNum = 0; 5031 Value *Val, *Ptr; 5032 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) || 5033 (BitCode == bitc::FUNC_CODE_INST_STORE 5034 ? getValueTypePair(Record, OpNum, NextValueNo, Val) 5035 : popValue(Record, OpNum, NextValueNo, 5036 cast<PointerType>(Ptr->getType())->getElementType(), 5037 Val)) || 5038 OpNum + 2 != Record.size()) 5039 return error("Invalid record"); 5040 5041 if (Error Err = typeCheckLoadStoreInst(Val->getType(), Ptr->getType())) 5042 return Err; 5043 MaybeAlign Align; 5044 if (Error Err = parseAlignmentValue(Record[OpNum], Align)) 5045 return Err; 5046 SmallPtrSet<Type *, 4> Visited; 5047 if (!Align && !Val->getType()->isSized(&Visited)) 5048 return error("store of unsized type"); 5049 if (!Align) 5050 Align = TheModule->getDataLayout().getABITypeAlign(Val->getType()); 5051 I = new StoreInst(Val, Ptr, Record[OpNum + 1], *Align); 5052 InstructionList.push_back(I); 5053 break; 5054 } 5055 case bitc::FUNC_CODE_INST_STOREATOMIC: 5056 case bitc::FUNC_CODE_INST_STOREATOMIC_OLD: { 5057 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, ssid] 5058 unsigned OpNum = 0; 5059 Value *Val, *Ptr; 5060 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) || 5061 !isa<PointerType>(Ptr->getType()) || 5062 (BitCode == bitc::FUNC_CODE_INST_STOREATOMIC 5063 ? getValueTypePair(Record, OpNum, NextValueNo, Val) 5064 : popValue(Record, OpNum, NextValueNo, 5065 cast<PointerType>(Ptr->getType())->getElementType(), 5066 Val)) || 5067 OpNum + 4 != Record.size()) 5068 return error("Invalid record"); 5069 5070 if (Error Err = typeCheckLoadStoreInst(Val->getType(), Ptr->getType())) 5071 return Err; 5072 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]); 5073 if (Ordering == AtomicOrdering::NotAtomic || 5074 Ordering == AtomicOrdering::Acquire || 5075 Ordering == AtomicOrdering::AcquireRelease) 5076 return error("Invalid record"); 5077 SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]); 5078 if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0) 5079 return error("Invalid record"); 5080 5081 MaybeAlign Align; 5082 if (Error Err = parseAlignmentValue(Record[OpNum], Align)) 5083 return Err; 5084 if (!Align) 5085 return error("Alignment missing from atomic store"); 5086 I = new StoreInst(Val, Ptr, Record[OpNum + 1], *Align, Ordering, SSID); 5087 InstructionList.push_back(I); 5088 break; 5089 } 5090 case bitc::FUNC_CODE_INST_CMPXCHG_OLD: { 5091 // CMPXCHG_OLD: [ptrty, ptr, cmp, val, vol, ordering, synchscope, 5092 // failure_ordering?, weak?] 5093 const size_t NumRecords = Record.size(); 5094 unsigned OpNum = 0; 5095 Value *Ptr = nullptr; 5096 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr)) 5097 return error("Invalid record"); 5098 5099 if (!isa<PointerType>(Ptr->getType())) 5100 return error("Cmpxchg operand is not a pointer type"); 5101 5102 Value *Cmp = nullptr; 5103 if (popValue(Record, OpNum, NextValueNo, 5104 cast<PointerType>(Ptr->getType())->getPointerElementType(), 5105 Cmp)) 5106 return error("Invalid record"); 5107 5108 Value *New = nullptr; 5109 if (popValue(Record, OpNum, NextValueNo, Cmp->getType(), New) || 5110 NumRecords < OpNum + 3 || NumRecords > OpNum + 5) 5111 return error("Invalid record"); 5112 5113 const AtomicOrdering SuccessOrdering = 5114 getDecodedOrdering(Record[OpNum + 1]); 5115 if (SuccessOrdering == AtomicOrdering::NotAtomic || 5116 SuccessOrdering == AtomicOrdering::Unordered) 5117 return error("Invalid record"); 5118 5119 const SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 2]); 5120 5121 if (Error Err = typeCheckLoadStoreInst(Cmp->getType(), Ptr->getType())) 5122 return Err; 5123 5124 const AtomicOrdering FailureOrdering = 5125 NumRecords < 7 5126 ? AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering) 5127 : getDecodedOrdering(Record[OpNum + 3]); 5128 5129 if (FailureOrdering == AtomicOrdering::NotAtomic || 5130 FailureOrdering == AtomicOrdering::Unordered) 5131 return error("Invalid record"); 5132 5133 const Align Alignment( 5134 TheModule->getDataLayout().getTypeStoreSize(Cmp->getType())); 5135 5136 I = new AtomicCmpXchgInst(Ptr, Cmp, New, Alignment, SuccessOrdering, 5137 FailureOrdering, SSID); 5138 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]); 5139 5140 if (NumRecords < 8) { 5141 // Before weak cmpxchgs existed, the instruction simply returned the 5142 // value loaded from memory, so bitcode files from that era will be 5143 // expecting the first component of a modern cmpxchg. 5144 CurBB->getInstList().push_back(I); 5145 I = ExtractValueInst::Create(I, 0); 5146 } else { 5147 cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum + 4]); 5148 } 5149 5150 InstructionList.push_back(I); 5151 break; 5152 } 5153 case bitc::FUNC_CODE_INST_CMPXCHG: { 5154 // CMPXCHG: [ptrty, ptr, cmp, val, vol, success_ordering, synchscope, 5155 // failure_ordering, weak, align?] 5156 const size_t NumRecords = Record.size(); 5157 unsigned OpNum = 0; 5158 Value *Ptr = nullptr; 5159 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr)) 5160 return error("Invalid record"); 5161 5162 if (!isa<PointerType>(Ptr->getType())) 5163 return error("Cmpxchg operand is not a pointer type"); 5164 5165 Value *Cmp = nullptr; 5166 if (getValueTypePair(Record, OpNum, NextValueNo, Cmp)) 5167 return error("Invalid record"); 5168 5169 Value *Val = nullptr; 5170 if (popValue(Record, OpNum, NextValueNo, Cmp->getType(), Val)) 5171 return error("Invalid record"); 5172 5173 if (NumRecords < OpNum + 3 || NumRecords > OpNum + 6) 5174 return error("Invalid record"); 5175 5176 const bool IsVol = Record[OpNum]; 5177 5178 const AtomicOrdering SuccessOrdering = 5179 getDecodedOrdering(Record[OpNum + 1]); 5180 if (!AtomicCmpXchgInst::isValidSuccessOrdering(SuccessOrdering)) 5181 return error("Invalid cmpxchg success ordering"); 5182 5183 const SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 2]); 5184 5185 if (Error Err = typeCheckLoadStoreInst(Cmp->getType(), Ptr->getType())) 5186 return Err; 5187 5188 const AtomicOrdering FailureOrdering = 5189 getDecodedOrdering(Record[OpNum + 3]); 5190 if (!AtomicCmpXchgInst::isValidFailureOrdering(FailureOrdering)) 5191 return error("Invalid cmpxchg failure ordering"); 5192 5193 const bool IsWeak = Record[OpNum + 4]; 5194 5195 MaybeAlign Alignment; 5196 5197 if (NumRecords == (OpNum + 6)) { 5198 if (Error Err = parseAlignmentValue(Record[OpNum + 5], Alignment)) 5199 return Err; 5200 } 5201 if (!Alignment) 5202 Alignment = 5203 Align(TheModule->getDataLayout().getTypeStoreSize(Cmp->getType())); 5204 5205 I = new AtomicCmpXchgInst(Ptr, Cmp, Val, *Alignment, SuccessOrdering, 5206 FailureOrdering, SSID); 5207 cast<AtomicCmpXchgInst>(I)->setVolatile(IsVol); 5208 cast<AtomicCmpXchgInst>(I)->setWeak(IsWeak); 5209 5210 InstructionList.push_back(I); 5211 break; 5212 } 5213 case bitc::FUNC_CODE_INST_ATOMICRMW_OLD: 5214 case bitc::FUNC_CODE_INST_ATOMICRMW: { 5215 // ATOMICRMW_OLD: [ptrty, ptr, val, op, vol, ordering, ssid, align?] 5216 // ATOMICRMW: [ptrty, ptr, valty, val, op, vol, ordering, ssid, align?] 5217 const size_t NumRecords = Record.size(); 5218 unsigned OpNum = 0; 5219 5220 Value *Ptr = nullptr; 5221 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr)) 5222 return error("Invalid record"); 5223 5224 if (!isa<PointerType>(Ptr->getType())) 5225 return error("Invalid record"); 5226 5227 Value *Val = nullptr; 5228 if (BitCode == bitc::FUNC_CODE_INST_ATOMICRMW_OLD) { 5229 if (popValue(Record, OpNum, NextValueNo, 5230 cast<PointerType>(Ptr->getType())->getPointerElementType(), 5231 Val)) 5232 return error("Invalid record"); 5233 } else { 5234 if (getValueTypePair(Record, OpNum, NextValueNo, Val)) 5235 return error("Invalid record"); 5236 } 5237 5238 if (!(NumRecords == (OpNum + 4) || NumRecords == (OpNum + 5))) 5239 return error("Invalid record"); 5240 5241 const AtomicRMWInst::BinOp Operation = 5242 getDecodedRMWOperation(Record[OpNum]); 5243 if (Operation < AtomicRMWInst::FIRST_BINOP || 5244 Operation > AtomicRMWInst::LAST_BINOP) 5245 return error("Invalid record"); 5246 5247 const bool IsVol = Record[OpNum + 1]; 5248 5249 const AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]); 5250 if (Ordering == AtomicOrdering::NotAtomic || 5251 Ordering == AtomicOrdering::Unordered) 5252 return error("Invalid record"); 5253 5254 const SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]); 5255 5256 MaybeAlign Alignment; 5257 5258 if (NumRecords == (OpNum + 5)) { 5259 if (Error Err = parseAlignmentValue(Record[OpNum + 4], Alignment)) 5260 return Err; 5261 } 5262 5263 if (!Alignment) 5264 Alignment = 5265 Align(TheModule->getDataLayout().getTypeStoreSize(Val->getType())); 5266 5267 I = new AtomicRMWInst(Operation, Ptr, Val, *Alignment, Ordering, SSID); 5268 cast<AtomicRMWInst>(I)->setVolatile(IsVol); 5269 5270 InstructionList.push_back(I); 5271 break; 5272 } 5273 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, ssid] 5274 if (2 != Record.size()) 5275 return error("Invalid record"); 5276 AtomicOrdering Ordering = getDecodedOrdering(Record[0]); 5277 if (Ordering == AtomicOrdering::NotAtomic || 5278 Ordering == AtomicOrdering::Unordered || 5279 Ordering == AtomicOrdering::Monotonic) 5280 return error("Invalid record"); 5281 SyncScope::ID SSID = getDecodedSyncScopeID(Record[1]); 5282 I = new FenceInst(Context, Ordering, SSID); 5283 InstructionList.push_back(I); 5284 break; 5285 } 5286 case bitc::FUNC_CODE_INST_CALL: { 5287 // CALL: [paramattrs, cc, fmf, fnty, fnid, arg0, arg1...] 5288 if (Record.size() < 3) 5289 return error("Invalid record"); 5290 5291 unsigned OpNum = 0; 5292 AttributeList PAL = getAttributes(Record[OpNum++]); 5293 unsigned CCInfo = Record[OpNum++]; 5294 5295 FastMathFlags FMF; 5296 if ((CCInfo >> bitc::CALL_FMF) & 1) { 5297 FMF = getDecodedFastMathFlags(Record[OpNum++]); 5298 if (!FMF.any()) 5299 return error("Fast math flags indicator set for call with no FMF"); 5300 } 5301 5302 FunctionType *FTy = nullptr; 5303 if ((CCInfo >> bitc::CALL_EXPLICIT_TYPE) & 1) { 5304 FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++])); 5305 if (!FTy) 5306 return error("Explicit call type is not a function type"); 5307 } 5308 5309 Value *Callee; 5310 if (getValueTypePair(Record, OpNum, NextValueNo, Callee)) 5311 return error("Invalid record"); 5312 5313 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType()); 5314 if (!OpTy) 5315 return error("Callee is not a pointer type"); 5316 if (!FTy) { 5317 FTy = dyn_cast<FunctionType>( 5318 cast<PointerType>(Callee->getType())->getElementType()); 5319 if (!FTy) 5320 return error("Callee is not of pointer to function type"); 5321 } else if (!OpTy->isOpaqueOrPointeeTypeMatches(FTy)) 5322 return error("Explicit call type does not match pointee type of " 5323 "callee operand"); 5324 if (Record.size() < FTy->getNumParams() + OpNum) 5325 return error("Insufficient operands to call"); 5326 5327 SmallVector<Value*, 16> Args; 5328 SmallVector<Type *, 16> ArgsTys; 5329 // Read the fixed params. 5330 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) { 5331 if (FTy->getParamType(i)->isLabelTy()) 5332 Args.push_back(getBasicBlock(Record[OpNum])); 5333 else 5334 Args.push_back(getValue(Record, OpNum, NextValueNo, 5335 FTy->getParamType(i))); 5336 ArgsTys.push_back(FTy->getParamType(i)); 5337 if (!Args.back()) 5338 return error("Invalid record"); 5339 } 5340 5341 // Read type/value pairs for varargs params. 5342 if (!FTy->isVarArg()) { 5343 if (OpNum != Record.size()) 5344 return error("Invalid record"); 5345 } else { 5346 while (OpNum != Record.size()) { 5347 Value *Op; 5348 if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 5349 return error("Invalid record"); 5350 Args.push_back(Op); 5351 ArgsTys.push_back(Op->getType()); 5352 } 5353 } 5354 5355 I = CallInst::Create(FTy, Callee, Args, OperandBundles); 5356 OperandBundles.clear(); 5357 InstructionList.push_back(I); 5358 cast<CallInst>(I)->setCallingConv( 5359 static_cast<CallingConv::ID>((0x7ff & CCInfo) >> bitc::CALL_CCONV)); 5360 CallInst::TailCallKind TCK = CallInst::TCK_None; 5361 if (CCInfo & 1 << bitc::CALL_TAIL) 5362 TCK = CallInst::TCK_Tail; 5363 if (CCInfo & (1 << bitc::CALL_MUSTTAIL)) 5364 TCK = CallInst::TCK_MustTail; 5365 if (CCInfo & (1 << bitc::CALL_NOTAIL)) 5366 TCK = CallInst::TCK_NoTail; 5367 cast<CallInst>(I)->setTailCallKind(TCK); 5368 cast<CallInst>(I)->setAttributes(PAL); 5369 propagateAttributeTypes(cast<CallBase>(I), ArgsTys); 5370 if (FMF.any()) { 5371 if (!isa<FPMathOperator>(I)) 5372 return error("Fast-math-flags specified for call without " 5373 "floating-point scalar or vector return type"); 5374 I->setFastMathFlags(FMF); 5375 } 5376 break; 5377 } 5378 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty] 5379 if (Record.size() < 3) 5380 return error("Invalid record"); 5381 Type *OpTy = getTypeByID(Record[0]); 5382 Value *Op = getValue(Record, 1, NextValueNo, OpTy); 5383 Type *ResTy = getTypeByID(Record[2]); 5384 if (!OpTy || !Op || !ResTy) 5385 return error("Invalid record"); 5386 I = new VAArgInst(Op, ResTy); 5387 InstructionList.push_back(I); 5388 break; 5389 } 5390 5391 case bitc::FUNC_CODE_OPERAND_BUNDLE: { 5392 // A call or an invoke can be optionally prefixed with some variable 5393 // number of operand bundle blocks. These blocks are read into 5394 // OperandBundles and consumed at the next call or invoke instruction. 5395 5396 if (Record.empty() || Record[0] >= BundleTags.size()) 5397 return error("Invalid record"); 5398 5399 std::vector<Value *> Inputs; 5400 5401 unsigned OpNum = 1; 5402 while (OpNum != Record.size()) { 5403 Value *Op; 5404 if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 5405 return error("Invalid record"); 5406 Inputs.push_back(Op); 5407 } 5408 5409 OperandBundles.emplace_back(BundleTags[Record[0]], std::move(Inputs)); 5410 continue; 5411 } 5412 5413 case bitc::FUNC_CODE_INST_FREEZE: { // FREEZE: [opty,opval] 5414 unsigned OpNum = 0; 5415 Value *Op = nullptr; 5416 if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 5417 return error("Invalid record"); 5418 if (OpNum != Record.size()) 5419 return error("Invalid record"); 5420 5421 I = new FreezeInst(Op); 5422 InstructionList.push_back(I); 5423 break; 5424 } 5425 } 5426 5427 // Add instruction to end of current BB. If there is no current BB, reject 5428 // this file. 5429 if (!CurBB) { 5430 I->deleteValue(); 5431 return error("Invalid instruction with no BB"); 5432 } 5433 if (!OperandBundles.empty()) { 5434 I->deleteValue(); 5435 return error("Operand bundles found with no consumer"); 5436 } 5437 CurBB->getInstList().push_back(I); 5438 5439 // If this was a terminator instruction, move to the next block. 5440 if (I->isTerminator()) { 5441 ++CurBBNo; 5442 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr; 5443 } 5444 5445 // Non-void values get registered in the value table for future use. 5446 if (!I->getType()->isVoidTy()) 5447 ValueList.assignValue(I, NextValueNo++); 5448 } 5449 5450 OutOfRecordLoop: 5451 5452 if (!OperandBundles.empty()) 5453 return error("Operand bundles found with no consumer"); 5454 5455 // Check the function list for unresolved values. 5456 if (Argument *A = dyn_cast<Argument>(ValueList.back())) { 5457 if (!A->getParent()) { 5458 // We found at least one unresolved value. Nuke them all to avoid leaks. 5459 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){ 5460 if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) { 5461 A->replaceAllUsesWith(UndefValue::get(A->getType())); 5462 delete A; 5463 } 5464 } 5465 return error("Never resolved value found in function"); 5466 } 5467 } 5468 5469 // Unexpected unresolved metadata about to be dropped. 5470 if (MDLoader->hasFwdRefs()) 5471 return error("Invalid function metadata: outgoing forward refs"); 5472 5473 // Trim the value list down to the size it was before we parsed this function. 5474 ValueList.shrinkTo(ModuleValueListSize); 5475 MDLoader->shrinkTo(ModuleMDLoaderSize); 5476 std::vector<BasicBlock*>().swap(FunctionBBs); 5477 return Error::success(); 5478 } 5479 5480 /// Find the function body in the bitcode stream 5481 Error BitcodeReader::findFunctionInStream( 5482 Function *F, 5483 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) { 5484 while (DeferredFunctionInfoIterator->second == 0) { 5485 // This is the fallback handling for the old format bitcode that 5486 // didn't contain the function index in the VST, or when we have 5487 // an anonymous function which would not have a VST entry. 5488 // Assert that we have one of those two cases. 5489 assert(VSTOffset == 0 || !F->hasName()); 5490 // Parse the next body in the stream and set its position in the 5491 // DeferredFunctionInfo map. 5492 if (Error Err = rememberAndSkipFunctionBodies()) 5493 return Err; 5494 } 5495 return Error::success(); 5496 } 5497 5498 SyncScope::ID BitcodeReader::getDecodedSyncScopeID(unsigned Val) { 5499 if (Val == SyncScope::SingleThread || Val == SyncScope::System) 5500 return SyncScope::ID(Val); 5501 if (Val >= SSIDs.size()) 5502 return SyncScope::System; // Map unknown synchronization scopes to system. 5503 return SSIDs[Val]; 5504 } 5505 5506 //===----------------------------------------------------------------------===// 5507 // GVMaterializer implementation 5508 //===----------------------------------------------------------------------===// 5509 5510 Error BitcodeReader::materialize(GlobalValue *GV) { 5511 Function *F = dyn_cast<Function>(GV); 5512 // If it's not a function or is already material, ignore the request. 5513 if (!F || !F->isMaterializable()) 5514 return Error::success(); 5515 5516 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F); 5517 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!"); 5518 // If its position is recorded as 0, its body is somewhere in the stream 5519 // but we haven't seen it yet. 5520 if (DFII->second == 0) 5521 if (Error Err = findFunctionInStream(F, DFII)) 5522 return Err; 5523 5524 // Materialize metadata before parsing any function bodies. 5525 if (Error Err = materializeMetadata()) 5526 return Err; 5527 5528 // Move the bit stream to the saved position of the deferred function body. 5529 if (Error JumpFailed = Stream.JumpToBit(DFII->second)) 5530 return JumpFailed; 5531 if (Error Err = parseFunctionBody(F)) 5532 return Err; 5533 F->setIsMaterializable(false); 5534 5535 if (StripDebugInfo) 5536 stripDebugInfo(*F); 5537 5538 // Upgrade any old intrinsic calls in the function. 5539 for (auto &I : UpgradedIntrinsics) { 5540 for (User *U : llvm::make_early_inc_range(I.first->materialized_users())) 5541 if (CallInst *CI = dyn_cast<CallInst>(U)) 5542 UpgradeIntrinsicCall(CI, I.second); 5543 } 5544 5545 // Update calls to the remangled intrinsics 5546 for (auto &I : RemangledIntrinsics) 5547 for (User *U : llvm::make_early_inc_range(I.first->materialized_users())) 5548 // Don't expect any other users than call sites 5549 cast<CallBase>(U)->setCalledFunction(I.second); 5550 5551 // Finish fn->subprogram upgrade for materialized functions. 5552 if (DISubprogram *SP = MDLoader->lookupSubprogramForFunction(F)) 5553 F->setSubprogram(SP); 5554 5555 // Check if the TBAA Metadata are valid, otherwise we will need to strip them. 5556 if (!MDLoader->isStrippingTBAA()) { 5557 for (auto &I : instructions(F)) { 5558 MDNode *TBAA = I.getMetadata(LLVMContext::MD_tbaa); 5559 if (!TBAA || TBAAVerifyHelper.visitTBAAMetadata(I, TBAA)) 5560 continue; 5561 MDLoader->setStripTBAA(true); 5562 stripTBAA(F->getParent()); 5563 } 5564 } 5565 5566 for (auto &I : instructions(F)) { 5567 // "Upgrade" older incorrect branch weights by dropping them. 5568 if (auto *MD = I.getMetadata(LLVMContext::MD_prof)) { 5569 if (MD->getOperand(0) != nullptr && isa<MDString>(MD->getOperand(0))) { 5570 MDString *MDS = cast<MDString>(MD->getOperand(0)); 5571 StringRef ProfName = MDS->getString(); 5572 // Check consistency of !prof branch_weights metadata. 5573 if (!ProfName.equals("branch_weights")) 5574 continue; 5575 unsigned ExpectedNumOperands = 0; 5576 if (BranchInst *BI = dyn_cast<BranchInst>(&I)) 5577 ExpectedNumOperands = BI->getNumSuccessors(); 5578 else if (SwitchInst *SI = dyn_cast<SwitchInst>(&I)) 5579 ExpectedNumOperands = SI->getNumSuccessors(); 5580 else if (isa<CallInst>(&I)) 5581 ExpectedNumOperands = 1; 5582 else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(&I)) 5583 ExpectedNumOperands = IBI->getNumDestinations(); 5584 else if (isa<SelectInst>(&I)) 5585 ExpectedNumOperands = 2; 5586 else 5587 continue; // ignore and continue. 5588 5589 // If branch weight doesn't match, just strip branch weight. 5590 if (MD->getNumOperands() != 1 + ExpectedNumOperands) 5591 I.setMetadata(LLVMContext::MD_prof, nullptr); 5592 } 5593 } 5594 5595 // Remove incompatible attributes on function calls. 5596 if (auto *CI = dyn_cast<CallBase>(&I)) { 5597 CI->removeRetAttrs(AttributeFuncs::typeIncompatible( 5598 CI->getFunctionType()->getReturnType())); 5599 5600 for (unsigned ArgNo = 0; ArgNo < CI->arg_size(); ++ArgNo) 5601 CI->removeParamAttrs(ArgNo, AttributeFuncs::typeIncompatible( 5602 CI->getArgOperand(ArgNo)->getType())); 5603 } 5604 } 5605 5606 // Look for functions that rely on old function attribute behavior. 5607 UpgradeFunctionAttributes(*F); 5608 5609 // Bring in any functions that this function forward-referenced via 5610 // blockaddresses. 5611 return materializeForwardReferencedFunctions(); 5612 } 5613 5614 Error BitcodeReader::materializeModule() { 5615 if (Error Err = materializeMetadata()) 5616 return Err; 5617 5618 // Promise to materialize all forward references. 5619 WillMaterializeAllForwardRefs = true; 5620 5621 // Iterate over the module, deserializing any functions that are still on 5622 // disk. 5623 for (Function &F : *TheModule) { 5624 if (Error Err = materialize(&F)) 5625 return Err; 5626 } 5627 // At this point, if there are any function bodies, parse the rest of 5628 // the bits in the module past the last function block we have recorded 5629 // through either lazy scanning or the VST. 5630 if (LastFunctionBlockBit || NextUnreadBit) 5631 if (Error Err = parseModule(LastFunctionBlockBit > NextUnreadBit 5632 ? LastFunctionBlockBit 5633 : NextUnreadBit)) 5634 return Err; 5635 5636 // Check that all block address forward references got resolved (as we 5637 // promised above). 5638 if (!BasicBlockFwdRefs.empty()) 5639 return error("Never resolved function from blockaddress"); 5640 5641 // Upgrade any intrinsic calls that slipped through (should not happen!) and 5642 // delete the old functions to clean up. We can't do this unless the entire 5643 // module is materialized because there could always be another function body 5644 // with calls to the old function. 5645 for (auto &I : UpgradedIntrinsics) { 5646 for (auto *U : I.first->users()) { 5647 if (CallInst *CI = dyn_cast<CallInst>(U)) 5648 UpgradeIntrinsicCall(CI, I.second); 5649 } 5650 if (!I.first->use_empty()) 5651 I.first->replaceAllUsesWith(I.second); 5652 I.first->eraseFromParent(); 5653 } 5654 UpgradedIntrinsics.clear(); 5655 // Do the same for remangled intrinsics 5656 for (auto &I : RemangledIntrinsics) { 5657 I.first->replaceAllUsesWith(I.second); 5658 I.first->eraseFromParent(); 5659 } 5660 RemangledIntrinsics.clear(); 5661 5662 UpgradeDebugInfo(*TheModule); 5663 5664 UpgradeModuleFlags(*TheModule); 5665 5666 UpgradeARCRuntime(*TheModule); 5667 5668 return Error::success(); 5669 } 5670 5671 std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const { 5672 return IdentifiedStructTypes; 5673 } 5674 5675 ModuleSummaryIndexBitcodeReader::ModuleSummaryIndexBitcodeReader( 5676 BitstreamCursor Cursor, StringRef Strtab, ModuleSummaryIndex &TheIndex, 5677 StringRef ModulePath, unsigned ModuleId) 5678 : BitcodeReaderBase(std::move(Cursor), Strtab), TheIndex(TheIndex), 5679 ModulePath(ModulePath), ModuleId(ModuleId) {} 5680 5681 void ModuleSummaryIndexBitcodeReader::addThisModule() { 5682 TheIndex.addModule(ModulePath, ModuleId); 5683 } 5684 5685 ModuleSummaryIndex::ModuleInfo * 5686 ModuleSummaryIndexBitcodeReader::getThisModule() { 5687 return TheIndex.getModule(ModulePath); 5688 } 5689 5690 std::pair<ValueInfo, GlobalValue::GUID> 5691 ModuleSummaryIndexBitcodeReader::getValueInfoFromValueId(unsigned ValueId) { 5692 auto VGI = ValueIdToValueInfoMap[ValueId]; 5693 assert(VGI.first); 5694 return VGI; 5695 } 5696 5697 void ModuleSummaryIndexBitcodeReader::setValueGUID( 5698 uint64_t ValueID, StringRef ValueName, GlobalValue::LinkageTypes Linkage, 5699 StringRef SourceFileName) { 5700 std::string GlobalId = 5701 GlobalValue::getGlobalIdentifier(ValueName, Linkage, SourceFileName); 5702 auto ValueGUID = GlobalValue::getGUID(GlobalId); 5703 auto OriginalNameID = ValueGUID; 5704 if (GlobalValue::isLocalLinkage(Linkage)) 5705 OriginalNameID = GlobalValue::getGUID(ValueName); 5706 if (PrintSummaryGUIDs) 5707 dbgs() << "GUID " << ValueGUID << "(" << OriginalNameID << ") is " 5708 << ValueName << "\n"; 5709 5710 // UseStrtab is false for legacy summary formats and value names are 5711 // created on stack. In that case we save the name in a string saver in 5712 // the index so that the value name can be recorded. 5713 ValueIdToValueInfoMap[ValueID] = std::make_pair( 5714 TheIndex.getOrInsertValueInfo( 5715 ValueGUID, 5716 UseStrtab ? ValueName : TheIndex.saveString(ValueName)), 5717 OriginalNameID); 5718 } 5719 5720 // Specialized value symbol table parser used when reading module index 5721 // blocks where we don't actually create global values. The parsed information 5722 // is saved in the bitcode reader for use when later parsing summaries. 5723 Error ModuleSummaryIndexBitcodeReader::parseValueSymbolTable( 5724 uint64_t Offset, 5725 DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap) { 5726 // With a strtab the VST is not required to parse the summary. 5727 if (UseStrtab) 5728 return Error::success(); 5729 5730 assert(Offset > 0 && "Expected non-zero VST offset"); 5731 Expected<uint64_t> MaybeCurrentBit = jumpToValueSymbolTable(Offset, Stream); 5732 if (!MaybeCurrentBit) 5733 return MaybeCurrentBit.takeError(); 5734 uint64_t CurrentBit = MaybeCurrentBit.get(); 5735 5736 if (Error Err = Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID)) 5737 return Err; 5738 5739 SmallVector<uint64_t, 64> Record; 5740 5741 // Read all the records for this value table. 5742 SmallString<128> ValueName; 5743 5744 while (true) { 5745 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); 5746 if (!MaybeEntry) 5747 return MaybeEntry.takeError(); 5748 BitstreamEntry Entry = MaybeEntry.get(); 5749 5750 switch (Entry.Kind) { 5751 case BitstreamEntry::SubBlock: // Handled for us already. 5752 case BitstreamEntry::Error: 5753 return error("Malformed block"); 5754 case BitstreamEntry::EndBlock: 5755 // Done parsing VST, jump back to wherever we came from. 5756 if (Error JumpFailed = Stream.JumpToBit(CurrentBit)) 5757 return JumpFailed; 5758 return Error::success(); 5759 case BitstreamEntry::Record: 5760 // The interesting case. 5761 break; 5762 } 5763 5764 // Read a record. 5765 Record.clear(); 5766 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record); 5767 if (!MaybeRecord) 5768 return MaybeRecord.takeError(); 5769 switch (MaybeRecord.get()) { 5770 default: // Default behavior: ignore (e.g. VST_CODE_BBENTRY records). 5771 break; 5772 case bitc::VST_CODE_ENTRY: { // VST_CODE_ENTRY: [valueid, namechar x N] 5773 if (convertToString(Record, 1, ValueName)) 5774 return error("Invalid record"); 5775 unsigned ValueID = Record[0]; 5776 assert(!SourceFileName.empty()); 5777 auto VLI = ValueIdToLinkageMap.find(ValueID); 5778 assert(VLI != ValueIdToLinkageMap.end() && 5779 "No linkage found for VST entry?"); 5780 auto Linkage = VLI->second; 5781 setValueGUID(ValueID, ValueName, Linkage, SourceFileName); 5782 ValueName.clear(); 5783 break; 5784 } 5785 case bitc::VST_CODE_FNENTRY: { 5786 // VST_CODE_FNENTRY: [valueid, offset, namechar x N] 5787 if (convertToString(Record, 2, ValueName)) 5788 return error("Invalid record"); 5789 unsigned ValueID = Record[0]; 5790 assert(!SourceFileName.empty()); 5791 auto VLI = ValueIdToLinkageMap.find(ValueID); 5792 assert(VLI != ValueIdToLinkageMap.end() && 5793 "No linkage found for VST entry?"); 5794 auto Linkage = VLI->second; 5795 setValueGUID(ValueID, ValueName, Linkage, SourceFileName); 5796 ValueName.clear(); 5797 break; 5798 } 5799 case bitc::VST_CODE_COMBINED_ENTRY: { 5800 // VST_CODE_COMBINED_ENTRY: [valueid, refguid] 5801 unsigned ValueID = Record[0]; 5802 GlobalValue::GUID RefGUID = Record[1]; 5803 // The "original name", which is the second value of the pair will be 5804 // overriden later by a FS_COMBINED_ORIGINAL_NAME in the combined index. 5805 ValueIdToValueInfoMap[ValueID] = 5806 std::make_pair(TheIndex.getOrInsertValueInfo(RefGUID), RefGUID); 5807 break; 5808 } 5809 } 5810 } 5811 } 5812 5813 // Parse just the blocks needed for building the index out of the module. 5814 // At the end of this routine the module Index is populated with a map 5815 // from global value id to GlobalValueSummary objects. 5816 Error ModuleSummaryIndexBitcodeReader::parseModule() { 5817 if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID)) 5818 return Err; 5819 5820 SmallVector<uint64_t, 64> Record; 5821 DenseMap<unsigned, GlobalValue::LinkageTypes> ValueIdToLinkageMap; 5822 unsigned ValueId = 0; 5823 5824 // Read the index for this module. 5825 while (true) { 5826 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance(); 5827 if (!MaybeEntry) 5828 return MaybeEntry.takeError(); 5829 llvm::BitstreamEntry Entry = MaybeEntry.get(); 5830 5831 switch (Entry.Kind) { 5832 case BitstreamEntry::Error: 5833 return error("Malformed block"); 5834 case BitstreamEntry::EndBlock: 5835 return Error::success(); 5836 5837 case BitstreamEntry::SubBlock: 5838 switch (Entry.ID) { 5839 default: // Skip unknown content. 5840 if (Error Err = Stream.SkipBlock()) 5841 return Err; 5842 break; 5843 case bitc::BLOCKINFO_BLOCK_ID: 5844 // Need to parse these to get abbrev ids (e.g. for VST) 5845 if (readBlockInfo()) 5846 return error("Malformed block"); 5847 break; 5848 case bitc::VALUE_SYMTAB_BLOCK_ID: 5849 // Should have been parsed earlier via VSTOffset, unless there 5850 // is no summary section. 5851 assert(((SeenValueSymbolTable && VSTOffset > 0) || 5852 !SeenGlobalValSummary) && 5853 "Expected early VST parse via VSTOffset record"); 5854 if (Error Err = Stream.SkipBlock()) 5855 return Err; 5856 break; 5857 case bitc::GLOBALVAL_SUMMARY_BLOCK_ID: 5858 case bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID: 5859 // Add the module if it is a per-module index (has a source file name). 5860 if (!SourceFileName.empty()) 5861 addThisModule(); 5862 assert(!SeenValueSymbolTable && 5863 "Already read VST when parsing summary block?"); 5864 // We might not have a VST if there were no values in the 5865 // summary. An empty summary block generated when we are 5866 // performing ThinLTO compiles so we don't later invoke 5867 // the regular LTO process on them. 5868 if (VSTOffset > 0) { 5869 if (Error Err = parseValueSymbolTable(VSTOffset, ValueIdToLinkageMap)) 5870 return Err; 5871 SeenValueSymbolTable = true; 5872 } 5873 SeenGlobalValSummary = true; 5874 if (Error Err = parseEntireSummary(Entry.ID)) 5875 return Err; 5876 break; 5877 case bitc::MODULE_STRTAB_BLOCK_ID: 5878 if (Error Err = parseModuleStringTable()) 5879 return Err; 5880 break; 5881 } 5882 continue; 5883 5884 case BitstreamEntry::Record: { 5885 Record.clear(); 5886 Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record); 5887 if (!MaybeBitCode) 5888 return MaybeBitCode.takeError(); 5889 switch (MaybeBitCode.get()) { 5890 default: 5891 break; // Default behavior, ignore unknown content. 5892 case bitc::MODULE_CODE_VERSION: { 5893 if (Error Err = parseVersionRecord(Record).takeError()) 5894 return Err; 5895 break; 5896 } 5897 /// MODULE_CODE_SOURCE_FILENAME: [namechar x N] 5898 case bitc::MODULE_CODE_SOURCE_FILENAME: { 5899 SmallString<128> ValueName; 5900 if (convertToString(Record, 0, ValueName)) 5901 return error("Invalid record"); 5902 SourceFileName = ValueName.c_str(); 5903 break; 5904 } 5905 /// MODULE_CODE_HASH: [5*i32] 5906 case bitc::MODULE_CODE_HASH: { 5907 if (Record.size() != 5) 5908 return error("Invalid hash length " + Twine(Record.size()).str()); 5909 auto &Hash = getThisModule()->second.second; 5910 int Pos = 0; 5911 for (auto &Val : Record) { 5912 assert(!(Val >> 32) && "Unexpected high bits set"); 5913 Hash[Pos++] = Val; 5914 } 5915 break; 5916 } 5917 /// MODULE_CODE_VSTOFFSET: [offset] 5918 case bitc::MODULE_CODE_VSTOFFSET: 5919 if (Record.empty()) 5920 return error("Invalid record"); 5921 // Note that we subtract 1 here because the offset is relative to one 5922 // word before the start of the identification or module block, which 5923 // was historically always the start of the regular bitcode header. 5924 VSTOffset = Record[0] - 1; 5925 break; 5926 // v1 GLOBALVAR: [pointer type, isconst, initid, linkage, ...] 5927 // v1 FUNCTION: [type, callingconv, isproto, linkage, ...] 5928 // v1 ALIAS: [alias type, addrspace, aliasee val#, linkage, ...] 5929 // v2: [strtab offset, strtab size, v1] 5930 case bitc::MODULE_CODE_GLOBALVAR: 5931 case bitc::MODULE_CODE_FUNCTION: 5932 case bitc::MODULE_CODE_ALIAS: { 5933 StringRef Name; 5934 ArrayRef<uint64_t> GVRecord; 5935 std::tie(Name, GVRecord) = readNameFromStrtab(Record); 5936 if (GVRecord.size() <= 3) 5937 return error("Invalid record"); 5938 uint64_t RawLinkage = GVRecord[3]; 5939 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage); 5940 if (!UseStrtab) { 5941 ValueIdToLinkageMap[ValueId++] = Linkage; 5942 break; 5943 } 5944 5945 setValueGUID(ValueId++, Name, Linkage, SourceFileName); 5946 break; 5947 } 5948 } 5949 } 5950 continue; 5951 } 5952 } 5953 } 5954 5955 std::vector<ValueInfo> 5956 ModuleSummaryIndexBitcodeReader::makeRefList(ArrayRef<uint64_t> Record) { 5957 std::vector<ValueInfo> Ret; 5958 Ret.reserve(Record.size()); 5959 for (uint64_t RefValueId : Record) 5960 Ret.push_back(getValueInfoFromValueId(RefValueId).first); 5961 return Ret; 5962 } 5963 5964 std::vector<FunctionSummary::EdgeTy> 5965 ModuleSummaryIndexBitcodeReader::makeCallList(ArrayRef<uint64_t> Record, 5966 bool IsOldProfileFormat, 5967 bool HasProfile, bool HasRelBF) { 5968 std::vector<FunctionSummary::EdgeTy> Ret; 5969 Ret.reserve(Record.size()); 5970 for (unsigned I = 0, E = Record.size(); I != E; ++I) { 5971 CalleeInfo::HotnessType Hotness = CalleeInfo::HotnessType::Unknown; 5972 uint64_t RelBF = 0; 5973 ValueInfo Callee = getValueInfoFromValueId(Record[I]).first; 5974 if (IsOldProfileFormat) { 5975 I += 1; // Skip old callsitecount field 5976 if (HasProfile) 5977 I += 1; // Skip old profilecount field 5978 } else if (HasProfile) 5979 Hotness = static_cast<CalleeInfo::HotnessType>(Record[++I]); 5980 else if (HasRelBF) 5981 RelBF = Record[++I]; 5982 Ret.push_back(FunctionSummary::EdgeTy{Callee, CalleeInfo(Hotness, RelBF)}); 5983 } 5984 return Ret; 5985 } 5986 5987 static void 5988 parseWholeProgramDevirtResolutionByArg(ArrayRef<uint64_t> Record, size_t &Slot, 5989 WholeProgramDevirtResolution &Wpd) { 5990 uint64_t ArgNum = Record[Slot++]; 5991 WholeProgramDevirtResolution::ByArg &B = 5992 Wpd.ResByArg[{Record.begin() + Slot, Record.begin() + Slot + ArgNum}]; 5993 Slot += ArgNum; 5994 5995 B.TheKind = 5996 static_cast<WholeProgramDevirtResolution::ByArg::Kind>(Record[Slot++]); 5997 B.Info = Record[Slot++]; 5998 B.Byte = Record[Slot++]; 5999 B.Bit = Record[Slot++]; 6000 } 6001 6002 static void parseWholeProgramDevirtResolution(ArrayRef<uint64_t> Record, 6003 StringRef Strtab, size_t &Slot, 6004 TypeIdSummary &TypeId) { 6005 uint64_t Id = Record[Slot++]; 6006 WholeProgramDevirtResolution &Wpd = TypeId.WPDRes[Id]; 6007 6008 Wpd.TheKind = static_cast<WholeProgramDevirtResolution::Kind>(Record[Slot++]); 6009 Wpd.SingleImplName = {Strtab.data() + Record[Slot], 6010 static_cast<size_t>(Record[Slot + 1])}; 6011 Slot += 2; 6012 6013 uint64_t ResByArgNum = Record[Slot++]; 6014 for (uint64_t I = 0; I != ResByArgNum; ++I) 6015 parseWholeProgramDevirtResolutionByArg(Record, Slot, Wpd); 6016 } 6017 6018 static void parseTypeIdSummaryRecord(ArrayRef<uint64_t> Record, 6019 StringRef Strtab, 6020 ModuleSummaryIndex &TheIndex) { 6021 size_t Slot = 0; 6022 TypeIdSummary &TypeId = TheIndex.getOrInsertTypeIdSummary( 6023 {Strtab.data() + Record[Slot], static_cast<size_t>(Record[Slot + 1])}); 6024 Slot += 2; 6025 6026 TypeId.TTRes.TheKind = static_cast<TypeTestResolution::Kind>(Record[Slot++]); 6027 TypeId.TTRes.SizeM1BitWidth = Record[Slot++]; 6028 TypeId.TTRes.AlignLog2 = Record[Slot++]; 6029 TypeId.TTRes.SizeM1 = Record[Slot++]; 6030 TypeId.TTRes.BitMask = Record[Slot++]; 6031 TypeId.TTRes.InlineBits = Record[Slot++]; 6032 6033 while (Slot < Record.size()) 6034 parseWholeProgramDevirtResolution(Record, Strtab, Slot, TypeId); 6035 } 6036 6037 std::vector<FunctionSummary::ParamAccess> 6038 ModuleSummaryIndexBitcodeReader::parseParamAccesses(ArrayRef<uint64_t> Record) { 6039 auto ReadRange = [&]() { 6040 APInt Lower(FunctionSummary::ParamAccess::RangeWidth, 6041 BitcodeReader::decodeSignRotatedValue(Record.front())); 6042 Record = Record.drop_front(); 6043 APInt Upper(FunctionSummary::ParamAccess::RangeWidth, 6044 BitcodeReader::decodeSignRotatedValue(Record.front())); 6045 Record = Record.drop_front(); 6046 ConstantRange Range{Lower, Upper}; 6047 assert(!Range.isFullSet()); 6048 assert(!Range.isUpperSignWrapped()); 6049 return Range; 6050 }; 6051 6052 std::vector<FunctionSummary::ParamAccess> PendingParamAccesses; 6053 while (!Record.empty()) { 6054 PendingParamAccesses.emplace_back(); 6055 FunctionSummary::ParamAccess &ParamAccess = PendingParamAccesses.back(); 6056 ParamAccess.ParamNo = Record.front(); 6057 Record = Record.drop_front(); 6058 ParamAccess.Use = ReadRange(); 6059 ParamAccess.Calls.resize(Record.front()); 6060 Record = Record.drop_front(); 6061 for (auto &Call : ParamAccess.Calls) { 6062 Call.ParamNo = Record.front(); 6063 Record = Record.drop_front(); 6064 Call.Callee = getValueInfoFromValueId(Record.front()).first; 6065 Record = Record.drop_front(); 6066 Call.Offsets = ReadRange(); 6067 } 6068 } 6069 return PendingParamAccesses; 6070 } 6071 6072 void ModuleSummaryIndexBitcodeReader::parseTypeIdCompatibleVtableInfo( 6073 ArrayRef<uint64_t> Record, size_t &Slot, 6074 TypeIdCompatibleVtableInfo &TypeId) { 6075 uint64_t Offset = Record[Slot++]; 6076 ValueInfo Callee = getValueInfoFromValueId(Record[Slot++]).first; 6077 TypeId.push_back({Offset, Callee}); 6078 } 6079 6080 void ModuleSummaryIndexBitcodeReader::parseTypeIdCompatibleVtableSummaryRecord( 6081 ArrayRef<uint64_t> Record) { 6082 size_t Slot = 0; 6083 TypeIdCompatibleVtableInfo &TypeId = 6084 TheIndex.getOrInsertTypeIdCompatibleVtableSummary( 6085 {Strtab.data() + Record[Slot], 6086 static_cast<size_t>(Record[Slot + 1])}); 6087 Slot += 2; 6088 6089 while (Slot < Record.size()) 6090 parseTypeIdCompatibleVtableInfo(Record, Slot, TypeId); 6091 } 6092 6093 static void setSpecialRefs(std::vector<ValueInfo> &Refs, unsigned ROCnt, 6094 unsigned WOCnt) { 6095 // Readonly and writeonly refs are in the end of the refs list. 6096 assert(ROCnt + WOCnt <= Refs.size()); 6097 unsigned FirstWORef = Refs.size() - WOCnt; 6098 unsigned RefNo = FirstWORef - ROCnt; 6099 for (; RefNo < FirstWORef; ++RefNo) 6100 Refs[RefNo].setReadOnly(); 6101 for (; RefNo < Refs.size(); ++RefNo) 6102 Refs[RefNo].setWriteOnly(); 6103 } 6104 6105 // Eagerly parse the entire summary block. This populates the GlobalValueSummary 6106 // objects in the index. 6107 Error ModuleSummaryIndexBitcodeReader::parseEntireSummary(unsigned ID) { 6108 if (Error Err = Stream.EnterSubBlock(ID)) 6109 return Err; 6110 SmallVector<uint64_t, 64> Record; 6111 6112 // Parse version 6113 { 6114 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); 6115 if (!MaybeEntry) 6116 return MaybeEntry.takeError(); 6117 BitstreamEntry Entry = MaybeEntry.get(); 6118 6119 if (Entry.Kind != BitstreamEntry::Record) 6120 return error("Invalid Summary Block: record for version expected"); 6121 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record); 6122 if (!MaybeRecord) 6123 return MaybeRecord.takeError(); 6124 if (MaybeRecord.get() != bitc::FS_VERSION) 6125 return error("Invalid Summary Block: version expected"); 6126 } 6127 const uint64_t Version = Record[0]; 6128 const bool IsOldProfileFormat = Version == 1; 6129 if (Version < 1 || Version > ModuleSummaryIndex::BitcodeSummaryVersion) 6130 return error("Invalid summary version " + Twine(Version) + 6131 ". Version should be in the range [1-" + 6132 Twine(ModuleSummaryIndex::BitcodeSummaryVersion) + 6133 "]."); 6134 Record.clear(); 6135 6136 // Keep around the last seen summary to be used when we see an optional 6137 // "OriginalName" attachement. 6138 GlobalValueSummary *LastSeenSummary = nullptr; 6139 GlobalValue::GUID LastSeenGUID = 0; 6140 6141 // We can expect to see any number of type ID information records before 6142 // each function summary records; these variables store the information 6143 // collected so far so that it can be used to create the summary object. 6144 std::vector<GlobalValue::GUID> PendingTypeTests; 6145 std::vector<FunctionSummary::VFuncId> PendingTypeTestAssumeVCalls, 6146 PendingTypeCheckedLoadVCalls; 6147 std::vector<FunctionSummary::ConstVCall> PendingTypeTestAssumeConstVCalls, 6148 PendingTypeCheckedLoadConstVCalls; 6149 std::vector<FunctionSummary::ParamAccess> PendingParamAccesses; 6150 6151 while (true) { 6152 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); 6153 if (!MaybeEntry) 6154 return MaybeEntry.takeError(); 6155 BitstreamEntry Entry = MaybeEntry.get(); 6156 6157 switch (Entry.Kind) { 6158 case BitstreamEntry::SubBlock: // Handled for us already. 6159 case BitstreamEntry::Error: 6160 return error("Malformed block"); 6161 case BitstreamEntry::EndBlock: 6162 return Error::success(); 6163 case BitstreamEntry::Record: 6164 // The interesting case. 6165 break; 6166 } 6167 6168 // Read a record. The record format depends on whether this 6169 // is a per-module index or a combined index file. In the per-module 6170 // case the records contain the associated value's ID for correlation 6171 // with VST entries. In the combined index the correlation is done 6172 // via the bitcode offset of the summary records (which were saved 6173 // in the combined index VST entries). The records also contain 6174 // information used for ThinLTO renaming and importing. 6175 Record.clear(); 6176 Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record); 6177 if (!MaybeBitCode) 6178 return MaybeBitCode.takeError(); 6179 switch (unsigned BitCode = MaybeBitCode.get()) { 6180 default: // Default behavior: ignore. 6181 break; 6182 case bitc::FS_FLAGS: { // [flags] 6183 TheIndex.setFlags(Record[0]); 6184 break; 6185 } 6186 case bitc::FS_VALUE_GUID: { // [valueid, refguid] 6187 uint64_t ValueID = Record[0]; 6188 GlobalValue::GUID RefGUID = Record[1]; 6189 ValueIdToValueInfoMap[ValueID] = 6190 std::make_pair(TheIndex.getOrInsertValueInfo(RefGUID), RefGUID); 6191 break; 6192 } 6193 // FS_PERMODULE: [valueid, flags, instcount, fflags, numrefs, 6194 // numrefs x valueid, n x (valueid)] 6195 // FS_PERMODULE_PROFILE: [valueid, flags, instcount, fflags, numrefs, 6196 // numrefs x valueid, 6197 // n x (valueid, hotness)] 6198 // FS_PERMODULE_RELBF: [valueid, flags, instcount, fflags, numrefs, 6199 // numrefs x valueid, 6200 // n x (valueid, relblockfreq)] 6201 case bitc::FS_PERMODULE: 6202 case bitc::FS_PERMODULE_RELBF: 6203 case bitc::FS_PERMODULE_PROFILE: { 6204 unsigned ValueID = Record[0]; 6205 uint64_t RawFlags = Record[1]; 6206 unsigned InstCount = Record[2]; 6207 uint64_t RawFunFlags = 0; 6208 unsigned NumRefs = Record[3]; 6209 unsigned NumRORefs = 0, NumWORefs = 0; 6210 int RefListStartIndex = 4; 6211 if (Version >= 4) { 6212 RawFunFlags = Record[3]; 6213 NumRefs = Record[4]; 6214 RefListStartIndex = 5; 6215 if (Version >= 5) { 6216 NumRORefs = Record[5]; 6217 RefListStartIndex = 6; 6218 if (Version >= 7) { 6219 NumWORefs = Record[6]; 6220 RefListStartIndex = 7; 6221 } 6222 } 6223 } 6224 6225 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version); 6226 // The module path string ref set in the summary must be owned by the 6227 // index's module string table. Since we don't have a module path 6228 // string table section in the per-module index, we create a single 6229 // module path string table entry with an empty (0) ID to take 6230 // ownership. 6231 int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs; 6232 assert(Record.size() >= RefListStartIndex + NumRefs && 6233 "Record size inconsistent with number of references"); 6234 std::vector<ValueInfo> Refs = makeRefList( 6235 ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs)); 6236 bool HasProfile = (BitCode == bitc::FS_PERMODULE_PROFILE); 6237 bool HasRelBF = (BitCode == bitc::FS_PERMODULE_RELBF); 6238 std::vector<FunctionSummary::EdgeTy> Calls = makeCallList( 6239 ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex), 6240 IsOldProfileFormat, HasProfile, HasRelBF); 6241 setSpecialRefs(Refs, NumRORefs, NumWORefs); 6242 auto FS = std::make_unique<FunctionSummary>( 6243 Flags, InstCount, getDecodedFFlags(RawFunFlags), /*EntryCount=*/0, 6244 std::move(Refs), std::move(Calls), std::move(PendingTypeTests), 6245 std::move(PendingTypeTestAssumeVCalls), 6246 std::move(PendingTypeCheckedLoadVCalls), 6247 std::move(PendingTypeTestAssumeConstVCalls), 6248 std::move(PendingTypeCheckedLoadConstVCalls), 6249 std::move(PendingParamAccesses)); 6250 auto VIAndOriginalGUID = getValueInfoFromValueId(ValueID); 6251 FS->setModulePath(getThisModule()->first()); 6252 FS->setOriginalName(VIAndOriginalGUID.second); 6253 TheIndex.addGlobalValueSummary(VIAndOriginalGUID.first, std::move(FS)); 6254 break; 6255 } 6256 // FS_ALIAS: [valueid, flags, valueid] 6257 // Aliases must be emitted (and parsed) after all FS_PERMODULE entries, as 6258 // they expect all aliasee summaries to be available. 6259 case bitc::FS_ALIAS: { 6260 unsigned ValueID = Record[0]; 6261 uint64_t RawFlags = Record[1]; 6262 unsigned AliaseeID = Record[2]; 6263 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version); 6264 auto AS = std::make_unique<AliasSummary>(Flags); 6265 // The module path string ref set in the summary must be owned by the 6266 // index's module string table. Since we don't have a module path 6267 // string table section in the per-module index, we create a single 6268 // module path string table entry with an empty (0) ID to take 6269 // ownership. 6270 AS->setModulePath(getThisModule()->first()); 6271 6272 auto AliaseeVI = getValueInfoFromValueId(AliaseeID).first; 6273 auto AliaseeInModule = TheIndex.findSummaryInModule(AliaseeVI, ModulePath); 6274 if (!AliaseeInModule) 6275 return error("Alias expects aliasee summary to be parsed"); 6276 AS->setAliasee(AliaseeVI, AliaseeInModule); 6277 6278 auto GUID = getValueInfoFromValueId(ValueID); 6279 AS->setOriginalName(GUID.second); 6280 TheIndex.addGlobalValueSummary(GUID.first, std::move(AS)); 6281 break; 6282 } 6283 // FS_PERMODULE_GLOBALVAR_INIT_REFS: [valueid, flags, varflags, n x valueid] 6284 case bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS: { 6285 unsigned ValueID = Record[0]; 6286 uint64_t RawFlags = Record[1]; 6287 unsigned RefArrayStart = 2; 6288 GlobalVarSummary::GVarFlags GVF(/* ReadOnly */ false, 6289 /* WriteOnly */ false, 6290 /* Constant */ false, 6291 GlobalObject::VCallVisibilityPublic); 6292 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version); 6293 if (Version >= 5) { 6294 GVF = getDecodedGVarFlags(Record[2]); 6295 RefArrayStart = 3; 6296 } 6297 std::vector<ValueInfo> Refs = 6298 makeRefList(ArrayRef<uint64_t>(Record).slice(RefArrayStart)); 6299 auto FS = 6300 std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs)); 6301 FS->setModulePath(getThisModule()->first()); 6302 auto GUID = getValueInfoFromValueId(ValueID); 6303 FS->setOriginalName(GUID.second); 6304 TheIndex.addGlobalValueSummary(GUID.first, std::move(FS)); 6305 break; 6306 } 6307 // FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS: [valueid, flags, varflags, 6308 // numrefs, numrefs x valueid, 6309 // n x (valueid, offset)] 6310 case bitc::FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS: { 6311 unsigned ValueID = Record[0]; 6312 uint64_t RawFlags = Record[1]; 6313 GlobalVarSummary::GVarFlags GVF = getDecodedGVarFlags(Record[2]); 6314 unsigned NumRefs = Record[3]; 6315 unsigned RefListStartIndex = 4; 6316 unsigned VTableListStartIndex = RefListStartIndex + NumRefs; 6317 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version); 6318 std::vector<ValueInfo> Refs = makeRefList( 6319 ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs)); 6320 VTableFuncList VTableFuncs; 6321 for (unsigned I = VTableListStartIndex, E = Record.size(); I != E; ++I) { 6322 ValueInfo Callee = getValueInfoFromValueId(Record[I]).first; 6323 uint64_t Offset = Record[++I]; 6324 VTableFuncs.push_back({Callee, Offset}); 6325 } 6326 auto VS = 6327 std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs)); 6328 VS->setModulePath(getThisModule()->first()); 6329 VS->setVTableFuncs(VTableFuncs); 6330 auto GUID = getValueInfoFromValueId(ValueID); 6331 VS->setOriginalName(GUID.second); 6332 TheIndex.addGlobalValueSummary(GUID.first, std::move(VS)); 6333 break; 6334 } 6335 // FS_COMBINED: [valueid, modid, flags, instcount, fflags, numrefs, 6336 // numrefs x valueid, n x (valueid)] 6337 // FS_COMBINED_PROFILE: [valueid, modid, flags, instcount, fflags, numrefs, 6338 // numrefs x valueid, n x (valueid, hotness)] 6339 case bitc::FS_COMBINED: 6340 case bitc::FS_COMBINED_PROFILE: { 6341 unsigned ValueID = Record[0]; 6342 uint64_t ModuleId = Record[1]; 6343 uint64_t RawFlags = Record[2]; 6344 unsigned InstCount = Record[3]; 6345 uint64_t RawFunFlags = 0; 6346 uint64_t EntryCount = 0; 6347 unsigned NumRefs = Record[4]; 6348 unsigned NumRORefs = 0, NumWORefs = 0; 6349 int RefListStartIndex = 5; 6350 6351 if (Version >= 4) { 6352 RawFunFlags = Record[4]; 6353 RefListStartIndex = 6; 6354 size_t NumRefsIndex = 5; 6355 if (Version >= 5) { 6356 unsigned NumRORefsOffset = 1; 6357 RefListStartIndex = 7; 6358 if (Version >= 6) { 6359 NumRefsIndex = 6; 6360 EntryCount = Record[5]; 6361 RefListStartIndex = 8; 6362 if (Version >= 7) { 6363 RefListStartIndex = 9; 6364 NumWORefs = Record[8]; 6365 NumRORefsOffset = 2; 6366 } 6367 } 6368 NumRORefs = Record[RefListStartIndex - NumRORefsOffset]; 6369 } 6370 NumRefs = Record[NumRefsIndex]; 6371 } 6372 6373 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version); 6374 int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs; 6375 assert(Record.size() >= RefListStartIndex + NumRefs && 6376 "Record size inconsistent with number of references"); 6377 std::vector<ValueInfo> Refs = makeRefList( 6378 ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs)); 6379 bool HasProfile = (BitCode == bitc::FS_COMBINED_PROFILE); 6380 std::vector<FunctionSummary::EdgeTy> Edges = makeCallList( 6381 ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex), 6382 IsOldProfileFormat, HasProfile, false); 6383 ValueInfo VI = getValueInfoFromValueId(ValueID).first; 6384 setSpecialRefs(Refs, NumRORefs, NumWORefs); 6385 auto FS = std::make_unique<FunctionSummary>( 6386 Flags, InstCount, getDecodedFFlags(RawFunFlags), EntryCount, 6387 std::move(Refs), std::move(Edges), std::move(PendingTypeTests), 6388 std::move(PendingTypeTestAssumeVCalls), 6389 std::move(PendingTypeCheckedLoadVCalls), 6390 std::move(PendingTypeTestAssumeConstVCalls), 6391 std::move(PendingTypeCheckedLoadConstVCalls), 6392 std::move(PendingParamAccesses)); 6393 LastSeenSummary = FS.get(); 6394 LastSeenGUID = VI.getGUID(); 6395 FS->setModulePath(ModuleIdMap[ModuleId]); 6396 TheIndex.addGlobalValueSummary(VI, std::move(FS)); 6397 break; 6398 } 6399 // FS_COMBINED_ALIAS: [valueid, modid, flags, valueid] 6400 // Aliases must be emitted (and parsed) after all FS_COMBINED entries, as 6401 // they expect all aliasee summaries to be available. 6402 case bitc::FS_COMBINED_ALIAS: { 6403 unsigned ValueID = Record[0]; 6404 uint64_t ModuleId = Record[1]; 6405 uint64_t RawFlags = Record[2]; 6406 unsigned AliaseeValueId = Record[3]; 6407 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version); 6408 auto AS = std::make_unique<AliasSummary>(Flags); 6409 LastSeenSummary = AS.get(); 6410 AS->setModulePath(ModuleIdMap[ModuleId]); 6411 6412 auto AliaseeVI = getValueInfoFromValueId(AliaseeValueId).first; 6413 auto AliaseeInModule = TheIndex.findSummaryInModule(AliaseeVI, AS->modulePath()); 6414 AS->setAliasee(AliaseeVI, AliaseeInModule); 6415 6416 ValueInfo VI = getValueInfoFromValueId(ValueID).first; 6417 LastSeenGUID = VI.getGUID(); 6418 TheIndex.addGlobalValueSummary(VI, std::move(AS)); 6419 break; 6420 } 6421 // FS_COMBINED_GLOBALVAR_INIT_REFS: [valueid, modid, flags, n x valueid] 6422 case bitc::FS_COMBINED_GLOBALVAR_INIT_REFS: { 6423 unsigned ValueID = Record[0]; 6424 uint64_t ModuleId = Record[1]; 6425 uint64_t RawFlags = Record[2]; 6426 unsigned RefArrayStart = 3; 6427 GlobalVarSummary::GVarFlags GVF(/* ReadOnly */ false, 6428 /* WriteOnly */ false, 6429 /* Constant */ false, 6430 GlobalObject::VCallVisibilityPublic); 6431 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version); 6432 if (Version >= 5) { 6433 GVF = getDecodedGVarFlags(Record[3]); 6434 RefArrayStart = 4; 6435 } 6436 std::vector<ValueInfo> Refs = 6437 makeRefList(ArrayRef<uint64_t>(Record).slice(RefArrayStart)); 6438 auto FS = 6439 std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs)); 6440 LastSeenSummary = FS.get(); 6441 FS->setModulePath(ModuleIdMap[ModuleId]); 6442 ValueInfo VI = getValueInfoFromValueId(ValueID).first; 6443 LastSeenGUID = VI.getGUID(); 6444 TheIndex.addGlobalValueSummary(VI, std::move(FS)); 6445 break; 6446 } 6447 // FS_COMBINED_ORIGINAL_NAME: [original_name] 6448 case bitc::FS_COMBINED_ORIGINAL_NAME: { 6449 uint64_t OriginalName = Record[0]; 6450 if (!LastSeenSummary) 6451 return error("Name attachment that does not follow a combined record"); 6452 LastSeenSummary->setOriginalName(OriginalName); 6453 TheIndex.addOriginalName(LastSeenGUID, OriginalName); 6454 // Reset the LastSeenSummary 6455 LastSeenSummary = nullptr; 6456 LastSeenGUID = 0; 6457 break; 6458 } 6459 case bitc::FS_TYPE_TESTS: 6460 assert(PendingTypeTests.empty()); 6461 llvm::append_range(PendingTypeTests, Record); 6462 break; 6463 6464 case bitc::FS_TYPE_TEST_ASSUME_VCALLS: 6465 assert(PendingTypeTestAssumeVCalls.empty()); 6466 for (unsigned I = 0; I != Record.size(); I += 2) 6467 PendingTypeTestAssumeVCalls.push_back({Record[I], Record[I+1]}); 6468 break; 6469 6470 case bitc::FS_TYPE_CHECKED_LOAD_VCALLS: 6471 assert(PendingTypeCheckedLoadVCalls.empty()); 6472 for (unsigned I = 0; I != Record.size(); I += 2) 6473 PendingTypeCheckedLoadVCalls.push_back({Record[I], Record[I+1]}); 6474 break; 6475 6476 case bitc::FS_TYPE_TEST_ASSUME_CONST_VCALL: 6477 PendingTypeTestAssumeConstVCalls.push_back( 6478 {{Record[0], Record[1]}, {Record.begin() + 2, Record.end()}}); 6479 break; 6480 6481 case bitc::FS_TYPE_CHECKED_LOAD_CONST_VCALL: 6482 PendingTypeCheckedLoadConstVCalls.push_back( 6483 {{Record[0], Record[1]}, {Record.begin() + 2, Record.end()}}); 6484 break; 6485 6486 case bitc::FS_CFI_FUNCTION_DEFS: { 6487 std::set<std::string> &CfiFunctionDefs = TheIndex.cfiFunctionDefs(); 6488 for (unsigned I = 0; I != Record.size(); I += 2) 6489 CfiFunctionDefs.insert( 6490 {Strtab.data() + Record[I], static_cast<size_t>(Record[I + 1])}); 6491 break; 6492 } 6493 6494 case bitc::FS_CFI_FUNCTION_DECLS: { 6495 std::set<std::string> &CfiFunctionDecls = TheIndex.cfiFunctionDecls(); 6496 for (unsigned I = 0; I != Record.size(); I += 2) 6497 CfiFunctionDecls.insert( 6498 {Strtab.data() + Record[I], static_cast<size_t>(Record[I + 1])}); 6499 break; 6500 } 6501 6502 case bitc::FS_TYPE_ID: 6503 parseTypeIdSummaryRecord(Record, Strtab, TheIndex); 6504 break; 6505 6506 case bitc::FS_TYPE_ID_METADATA: 6507 parseTypeIdCompatibleVtableSummaryRecord(Record); 6508 break; 6509 6510 case bitc::FS_BLOCK_COUNT: 6511 TheIndex.addBlockCount(Record[0]); 6512 break; 6513 6514 case bitc::FS_PARAM_ACCESS: { 6515 PendingParamAccesses = parseParamAccesses(Record); 6516 break; 6517 } 6518 } 6519 } 6520 llvm_unreachable("Exit infinite loop"); 6521 } 6522 6523 // Parse the module string table block into the Index. 6524 // This populates the ModulePathStringTable map in the index. 6525 Error ModuleSummaryIndexBitcodeReader::parseModuleStringTable() { 6526 if (Error Err = Stream.EnterSubBlock(bitc::MODULE_STRTAB_BLOCK_ID)) 6527 return Err; 6528 6529 SmallVector<uint64_t, 64> Record; 6530 6531 SmallString<128> ModulePath; 6532 ModuleSummaryIndex::ModuleInfo *LastSeenModule = nullptr; 6533 6534 while (true) { 6535 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); 6536 if (!MaybeEntry) 6537 return MaybeEntry.takeError(); 6538 BitstreamEntry Entry = MaybeEntry.get(); 6539 6540 switch (Entry.Kind) { 6541 case BitstreamEntry::SubBlock: // Handled for us already. 6542 case BitstreamEntry::Error: 6543 return error("Malformed block"); 6544 case BitstreamEntry::EndBlock: 6545 return Error::success(); 6546 case BitstreamEntry::Record: 6547 // The interesting case. 6548 break; 6549 } 6550 6551 Record.clear(); 6552 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record); 6553 if (!MaybeRecord) 6554 return MaybeRecord.takeError(); 6555 switch (MaybeRecord.get()) { 6556 default: // Default behavior: ignore. 6557 break; 6558 case bitc::MST_CODE_ENTRY: { 6559 // MST_ENTRY: [modid, namechar x N] 6560 uint64_t ModuleId = Record[0]; 6561 6562 if (convertToString(Record, 1, ModulePath)) 6563 return error("Invalid record"); 6564 6565 LastSeenModule = TheIndex.addModule(ModulePath, ModuleId); 6566 ModuleIdMap[ModuleId] = LastSeenModule->first(); 6567 6568 ModulePath.clear(); 6569 break; 6570 } 6571 /// MST_CODE_HASH: [5*i32] 6572 case bitc::MST_CODE_HASH: { 6573 if (Record.size() != 5) 6574 return error("Invalid hash length " + Twine(Record.size()).str()); 6575 if (!LastSeenModule) 6576 return error("Invalid hash that does not follow a module path"); 6577 int Pos = 0; 6578 for (auto &Val : Record) { 6579 assert(!(Val >> 32) && "Unexpected high bits set"); 6580 LastSeenModule->second.second[Pos++] = Val; 6581 } 6582 // Reset LastSeenModule to avoid overriding the hash unexpectedly. 6583 LastSeenModule = nullptr; 6584 break; 6585 } 6586 } 6587 } 6588 llvm_unreachable("Exit infinite loop"); 6589 } 6590 6591 namespace { 6592 6593 // FIXME: This class is only here to support the transition to llvm::Error. It 6594 // will be removed once this transition is complete. Clients should prefer to 6595 // deal with the Error value directly, rather than converting to error_code. 6596 class BitcodeErrorCategoryType : public std::error_category { 6597 const char *name() const noexcept override { 6598 return "llvm.bitcode"; 6599 } 6600 6601 std::string message(int IE) const override { 6602 BitcodeError E = static_cast<BitcodeError>(IE); 6603 switch (E) { 6604 case BitcodeError::CorruptedBitcode: 6605 return "Corrupted bitcode"; 6606 } 6607 llvm_unreachable("Unknown error type!"); 6608 } 6609 }; 6610 6611 } // end anonymous namespace 6612 6613 static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory; 6614 6615 const std::error_category &llvm::BitcodeErrorCategory() { 6616 return *ErrorCategory; 6617 } 6618 6619 static Expected<StringRef> readBlobInRecord(BitstreamCursor &Stream, 6620 unsigned Block, unsigned RecordID) { 6621 if (Error Err = Stream.EnterSubBlock(Block)) 6622 return std::move(Err); 6623 6624 StringRef Strtab; 6625 while (true) { 6626 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance(); 6627 if (!MaybeEntry) 6628 return MaybeEntry.takeError(); 6629 llvm::BitstreamEntry Entry = MaybeEntry.get(); 6630 6631 switch (Entry.Kind) { 6632 case BitstreamEntry::EndBlock: 6633 return Strtab; 6634 6635 case BitstreamEntry::Error: 6636 return error("Malformed block"); 6637 6638 case BitstreamEntry::SubBlock: 6639 if (Error Err = Stream.SkipBlock()) 6640 return std::move(Err); 6641 break; 6642 6643 case BitstreamEntry::Record: 6644 StringRef Blob; 6645 SmallVector<uint64_t, 1> Record; 6646 Expected<unsigned> MaybeRecord = 6647 Stream.readRecord(Entry.ID, Record, &Blob); 6648 if (!MaybeRecord) 6649 return MaybeRecord.takeError(); 6650 if (MaybeRecord.get() == RecordID) 6651 Strtab = Blob; 6652 break; 6653 } 6654 } 6655 } 6656 6657 //===----------------------------------------------------------------------===// 6658 // External interface 6659 //===----------------------------------------------------------------------===// 6660 6661 Expected<std::vector<BitcodeModule>> 6662 llvm::getBitcodeModuleList(MemoryBufferRef Buffer) { 6663 auto FOrErr = getBitcodeFileContents(Buffer); 6664 if (!FOrErr) 6665 return FOrErr.takeError(); 6666 return std::move(FOrErr->Mods); 6667 } 6668 6669 Expected<BitcodeFileContents> 6670 llvm::getBitcodeFileContents(MemoryBufferRef Buffer) { 6671 Expected<BitstreamCursor> StreamOrErr = initStream(Buffer); 6672 if (!StreamOrErr) 6673 return StreamOrErr.takeError(); 6674 BitstreamCursor &Stream = *StreamOrErr; 6675 6676 BitcodeFileContents F; 6677 while (true) { 6678 uint64_t BCBegin = Stream.getCurrentByteNo(); 6679 6680 // We may be consuming bitcode from a client that leaves garbage at the end 6681 // of the bitcode stream (e.g. Apple's ar tool). If we are close enough to 6682 // the end that there cannot possibly be another module, stop looking. 6683 if (BCBegin + 8 >= Stream.getBitcodeBytes().size()) 6684 return F; 6685 6686 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance(); 6687 if (!MaybeEntry) 6688 return MaybeEntry.takeError(); 6689 llvm::BitstreamEntry Entry = MaybeEntry.get(); 6690 6691 switch (Entry.Kind) { 6692 case BitstreamEntry::EndBlock: 6693 case BitstreamEntry::Error: 6694 return error("Malformed block"); 6695 6696 case BitstreamEntry::SubBlock: { 6697 uint64_t IdentificationBit = -1ull; 6698 if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) { 6699 IdentificationBit = Stream.GetCurrentBitNo() - BCBegin * 8; 6700 if (Error Err = Stream.SkipBlock()) 6701 return std::move(Err); 6702 6703 { 6704 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance(); 6705 if (!MaybeEntry) 6706 return MaybeEntry.takeError(); 6707 Entry = MaybeEntry.get(); 6708 } 6709 6710 if (Entry.Kind != BitstreamEntry::SubBlock || 6711 Entry.ID != bitc::MODULE_BLOCK_ID) 6712 return error("Malformed block"); 6713 } 6714 6715 if (Entry.ID == bitc::MODULE_BLOCK_ID) { 6716 uint64_t ModuleBit = Stream.GetCurrentBitNo() - BCBegin * 8; 6717 if (Error Err = Stream.SkipBlock()) 6718 return std::move(Err); 6719 6720 F.Mods.push_back({Stream.getBitcodeBytes().slice( 6721 BCBegin, Stream.getCurrentByteNo() - BCBegin), 6722 Buffer.getBufferIdentifier(), IdentificationBit, 6723 ModuleBit}); 6724 continue; 6725 } 6726 6727 if (Entry.ID == bitc::STRTAB_BLOCK_ID) { 6728 Expected<StringRef> Strtab = 6729 readBlobInRecord(Stream, bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB); 6730 if (!Strtab) 6731 return Strtab.takeError(); 6732 // This string table is used by every preceding bitcode module that does 6733 // not have its own string table. A bitcode file may have multiple 6734 // string tables if it was created by binary concatenation, for example 6735 // with "llvm-cat -b". 6736 for (auto I = F.Mods.rbegin(), E = F.Mods.rend(); I != E; ++I) { 6737 if (!I->Strtab.empty()) 6738 break; 6739 I->Strtab = *Strtab; 6740 } 6741 // Similarly, the string table is used by every preceding symbol table; 6742 // normally there will be just one unless the bitcode file was created 6743 // by binary concatenation. 6744 if (!F.Symtab.empty() && F.StrtabForSymtab.empty()) 6745 F.StrtabForSymtab = *Strtab; 6746 continue; 6747 } 6748 6749 if (Entry.ID == bitc::SYMTAB_BLOCK_ID) { 6750 Expected<StringRef> SymtabOrErr = 6751 readBlobInRecord(Stream, bitc::SYMTAB_BLOCK_ID, bitc::SYMTAB_BLOB); 6752 if (!SymtabOrErr) 6753 return SymtabOrErr.takeError(); 6754 6755 // We can expect the bitcode file to have multiple symbol tables if it 6756 // was created by binary concatenation. In that case we silently 6757 // ignore any subsequent symbol tables, which is fine because this is a 6758 // low level function. The client is expected to notice that the number 6759 // of modules in the symbol table does not match the number of modules 6760 // in the input file and regenerate the symbol table. 6761 if (F.Symtab.empty()) 6762 F.Symtab = *SymtabOrErr; 6763 continue; 6764 } 6765 6766 if (Error Err = Stream.SkipBlock()) 6767 return std::move(Err); 6768 continue; 6769 } 6770 case BitstreamEntry::Record: 6771 if (Error E = Stream.skipRecord(Entry.ID).takeError()) 6772 return std::move(E); 6773 continue; 6774 } 6775 } 6776 } 6777 6778 /// Get a lazy one-at-time loading module from bitcode. 6779 /// 6780 /// This isn't always used in a lazy context. In particular, it's also used by 6781 /// \a parseModule(). If this is truly lazy, then we need to eagerly pull 6782 /// in forward-referenced functions from block address references. 6783 /// 6784 /// \param[in] MaterializeAll Set to \c true if we should materialize 6785 /// everything. 6786 Expected<std::unique_ptr<Module>> 6787 BitcodeModule::getModuleImpl(LLVMContext &Context, bool MaterializeAll, 6788 bool ShouldLazyLoadMetadata, bool IsImporting, 6789 DataLayoutCallbackTy DataLayoutCallback) { 6790 BitstreamCursor Stream(Buffer); 6791 6792 std::string ProducerIdentification; 6793 if (IdentificationBit != -1ull) { 6794 if (Error JumpFailed = Stream.JumpToBit(IdentificationBit)) 6795 return std::move(JumpFailed); 6796 if (Error E = 6797 readIdentificationBlock(Stream).moveInto(ProducerIdentification)) 6798 return std::move(E); 6799 } 6800 6801 if (Error JumpFailed = Stream.JumpToBit(ModuleBit)) 6802 return std::move(JumpFailed); 6803 auto *R = new BitcodeReader(std::move(Stream), Strtab, ProducerIdentification, 6804 Context); 6805 6806 std::unique_ptr<Module> M = 6807 std::make_unique<Module>(ModuleIdentifier, Context); 6808 M->setMaterializer(R); 6809 6810 // Delay parsing Metadata if ShouldLazyLoadMetadata is true. 6811 if (Error Err = R->parseBitcodeInto(M.get(), ShouldLazyLoadMetadata, 6812 IsImporting, DataLayoutCallback)) 6813 return std::move(Err); 6814 6815 if (MaterializeAll) { 6816 // Read in the entire module, and destroy the BitcodeReader. 6817 if (Error Err = M->materializeAll()) 6818 return std::move(Err); 6819 } else { 6820 // Resolve forward references from blockaddresses. 6821 if (Error Err = R->materializeForwardReferencedFunctions()) 6822 return std::move(Err); 6823 } 6824 return std::move(M); 6825 } 6826 6827 Expected<std::unique_ptr<Module>> 6828 BitcodeModule::getLazyModule(LLVMContext &Context, bool ShouldLazyLoadMetadata, 6829 bool IsImporting) { 6830 return getModuleImpl(Context, false, ShouldLazyLoadMetadata, IsImporting, 6831 [](StringRef) { return None; }); 6832 } 6833 6834 // Parse the specified bitcode buffer and merge the index into CombinedIndex. 6835 // We don't use ModuleIdentifier here because the client may need to control the 6836 // module path used in the combined summary (e.g. when reading summaries for 6837 // regular LTO modules). 6838 Error BitcodeModule::readSummary(ModuleSummaryIndex &CombinedIndex, 6839 StringRef ModulePath, uint64_t ModuleId) { 6840 BitstreamCursor Stream(Buffer); 6841 if (Error JumpFailed = Stream.JumpToBit(ModuleBit)) 6842 return JumpFailed; 6843 6844 ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, CombinedIndex, 6845 ModulePath, ModuleId); 6846 return R.parseModule(); 6847 } 6848 6849 // Parse the specified bitcode buffer, returning the function info index. 6850 Expected<std::unique_ptr<ModuleSummaryIndex>> BitcodeModule::getSummary() { 6851 BitstreamCursor Stream(Buffer); 6852 if (Error JumpFailed = Stream.JumpToBit(ModuleBit)) 6853 return std::move(JumpFailed); 6854 6855 auto Index = std::make_unique<ModuleSummaryIndex>(/*HaveGVs=*/false); 6856 ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, *Index, 6857 ModuleIdentifier, 0); 6858 6859 if (Error Err = R.parseModule()) 6860 return std::move(Err); 6861 6862 return std::move(Index); 6863 } 6864 6865 static Expected<bool> getEnableSplitLTOUnitFlag(BitstreamCursor &Stream, 6866 unsigned ID) { 6867 if (Error Err = Stream.EnterSubBlock(ID)) 6868 return std::move(Err); 6869 SmallVector<uint64_t, 64> Record; 6870 6871 while (true) { 6872 BitstreamEntry Entry; 6873 if (Error E = Stream.advanceSkippingSubblocks().moveInto(Entry)) 6874 return std::move(E); 6875 6876 switch (Entry.Kind) { 6877 case BitstreamEntry::SubBlock: // Handled for us already. 6878 case BitstreamEntry::Error: 6879 return error("Malformed block"); 6880 case BitstreamEntry::EndBlock: 6881 // If no flags record found, conservatively return true to mimic 6882 // behavior before this flag was added. 6883 return true; 6884 case BitstreamEntry::Record: 6885 // The interesting case. 6886 break; 6887 } 6888 6889 // Look for the FS_FLAGS record. 6890 Record.clear(); 6891 Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record); 6892 if (!MaybeBitCode) 6893 return MaybeBitCode.takeError(); 6894 switch (MaybeBitCode.get()) { 6895 default: // Default behavior: ignore. 6896 break; 6897 case bitc::FS_FLAGS: { // [flags] 6898 uint64_t Flags = Record[0]; 6899 // Scan flags. 6900 assert(Flags <= 0x7f && "Unexpected bits in flag"); 6901 6902 return Flags & 0x8; 6903 } 6904 } 6905 } 6906 llvm_unreachable("Exit infinite loop"); 6907 } 6908 6909 // Check if the given bitcode buffer contains a global value summary block. 6910 Expected<BitcodeLTOInfo> BitcodeModule::getLTOInfo() { 6911 BitstreamCursor Stream(Buffer); 6912 if (Error JumpFailed = Stream.JumpToBit(ModuleBit)) 6913 return std::move(JumpFailed); 6914 6915 if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID)) 6916 return std::move(Err); 6917 6918 while (true) { 6919 llvm::BitstreamEntry Entry; 6920 if (Error E = Stream.advance().moveInto(Entry)) 6921 return std::move(E); 6922 6923 switch (Entry.Kind) { 6924 case BitstreamEntry::Error: 6925 return error("Malformed block"); 6926 case BitstreamEntry::EndBlock: 6927 return BitcodeLTOInfo{/*IsThinLTO=*/false, /*HasSummary=*/false, 6928 /*EnableSplitLTOUnit=*/false}; 6929 6930 case BitstreamEntry::SubBlock: 6931 if (Entry.ID == bitc::GLOBALVAL_SUMMARY_BLOCK_ID) { 6932 Expected<bool> EnableSplitLTOUnit = 6933 getEnableSplitLTOUnitFlag(Stream, Entry.ID); 6934 if (!EnableSplitLTOUnit) 6935 return EnableSplitLTOUnit.takeError(); 6936 return BitcodeLTOInfo{/*IsThinLTO=*/true, /*HasSummary=*/true, 6937 *EnableSplitLTOUnit}; 6938 } 6939 6940 if (Entry.ID == bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID) { 6941 Expected<bool> EnableSplitLTOUnit = 6942 getEnableSplitLTOUnitFlag(Stream, Entry.ID); 6943 if (!EnableSplitLTOUnit) 6944 return EnableSplitLTOUnit.takeError(); 6945 return BitcodeLTOInfo{/*IsThinLTO=*/false, /*HasSummary=*/true, 6946 *EnableSplitLTOUnit}; 6947 } 6948 6949 // Ignore other sub-blocks. 6950 if (Error Err = Stream.SkipBlock()) 6951 return std::move(Err); 6952 continue; 6953 6954 case BitstreamEntry::Record: 6955 if (Expected<unsigned> StreamFailed = Stream.skipRecord(Entry.ID)) 6956 continue; 6957 else 6958 return StreamFailed.takeError(); 6959 } 6960 } 6961 } 6962 6963 static Expected<BitcodeModule> getSingleModule(MemoryBufferRef Buffer) { 6964 Expected<std::vector<BitcodeModule>> MsOrErr = getBitcodeModuleList(Buffer); 6965 if (!MsOrErr) 6966 return MsOrErr.takeError(); 6967 6968 if (MsOrErr->size() != 1) 6969 return error("Expected a single module"); 6970 6971 return (*MsOrErr)[0]; 6972 } 6973 6974 Expected<std::unique_ptr<Module>> 6975 llvm::getLazyBitcodeModule(MemoryBufferRef Buffer, LLVMContext &Context, 6976 bool ShouldLazyLoadMetadata, bool IsImporting) { 6977 Expected<BitcodeModule> BM = getSingleModule(Buffer); 6978 if (!BM) 6979 return BM.takeError(); 6980 6981 return BM->getLazyModule(Context, ShouldLazyLoadMetadata, IsImporting); 6982 } 6983 6984 Expected<std::unique_ptr<Module>> llvm::getOwningLazyBitcodeModule( 6985 std::unique_ptr<MemoryBuffer> &&Buffer, LLVMContext &Context, 6986 bool ShouldLazyLoadMetadata, bool IsImporting) { 6987 auto MOrErr = getLazyBitcodeModule(*Buffer, Context, ShouldLazyLoadMetadata, 6988 IsImporting); 6989 if (MOrErr) 6990 (*MOrErr)->setOwnedMemoryBuffer(std::move(Buffer)); 6991 return MOrErr; 6992 } 6993 6994 Expected<std::unique_ptr<Module>> 6995 BitcodeModule::parseModule(LLVMContext &Context, 6996 DataLayoutCallbackTy DataLayoutCallback) { 6997 return getModuleImpl(Context, true, false, false, DataLayoutCallback); 6998 // TODO: Restore the use-lists to the in-memory state when the bitcode was 6999 // written. We must defer until the Module has been fully materialized. 7000 } 7001 7002 Expected<std::unique_ptr<Module>> 7003 llvm::parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context, 7004 DataLayoutCallbackTy DataLayoutCallback) { 7005 Expected<BitcodeModule> BM = getSingleModule(Buffer); 7006 if (!BM) 7007 return BM.takeError(); 7008 7009 return BM->parseModule(Context, DataLayoutCallback); 7010 } 7011 7012 Expected<std::string> llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer) { 7013 Expected<BitstreamCursor> StreamOrErr = initStream(Buffer); 7014 if (!StreamOrErr) 7015 return StreamOrErr.takeError(); 7016 7017 return readTriple(*StreamOrErr); 7018 } 7019 7020 Expected<bool> llvm::isBitcodeContainingObjCCategory(MemoryBufferRef Buffer) { 7021 Expected<BitstreamCursor> StreamOrErr = initStream(Buffer); 7022 if (!StreamOrErr) 7023 return StreamOrErr.takeError(); 7024 7025 return hasObjCCategory(*StreamOrErr); 7026 } 7027 7028 Expected<std::string> llvm::getBitcodeProducerString(MemoryBufferRef Buffer) { 7029 Expected<BitstreamCursor> StreamOrErr = initStream(Buffer); 7030 if (!StreamOrErr) 7031 return StreamOrErr.takeError(); 7032 7033 return readIdentificationCode(*StreamOrErr); 7034 } 7035 7036 Error llvm::readModuleSummaryIndex(MemoryBufferRef Buffer, 7037 ModuleSummaryIndex &CombinedIndex, 7038 uint64_t ModuleId) { 7039 Expected<BitcodeModule> BM = getSingleModule(Buffer); 7040 if (!BM) 7041 return BM.takeError(); 7042 7043 return BM->readSummary(CombinedIndex, BM->getModuleIdentifier(), ModuleId); 7044 } 7045 7046 Expected<std::unique_ptr<ModuleSummaryIndex>> 7047 llvm::getModuleSummaryIndex(MemoryBufferRef Buffer) { 7048 Expected<BitcodeModule> BM = getSingleModule(Buffer); 7049 if (!BM) 7050 return BM.takeError(); 7051 7052 return BM->getSummary(); 7053 } 7054 7055 Expected<BitcodeLTOInfo> llvm::getBitcodeLTOInfo(MemoryBufferRef Buffer) { 7056 Expected<BitcodeModule> BM = getSingleModule(Buffer); 7057 if (!BM) 7058 return BM.takeError(); 7059 7060 return BM->getLTOInfo(); 7061 } 7062 7063 Expected<std::unique_ptr<ModuleSummaryIndex>> 7064 llvm::getModuleSummaryIndexForFile(StringRef Path, 7065 bool IgnoreEmptyThinLTOIndexFile) { 7066 ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr = 7067 MemoryBuffer::getFileOrSTDIN(Path); 7068 if (!FileOrErr) 7069 return errorCodeToError(FileOrErr.getError()); 7070 if (IgnoreEmptyThinLTOIndexFile && !(*FileOrErr)->getBufferSize()) 7071 return nullptr; 7072 return getModuleSummaryIndex(**FileOrErr); 7073 } 7074