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