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