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