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