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 (Ty != getPointerElementFlatType(FullBaseTy->getScalarType())) 4172 return error( 4173 "Explicit gep type does not match pointee type of pointer operand"); 4174 4175 SmallVector<Value*, 16> GEPIdx; 4176 while (OpNum != Record.size()) { 4177 Value *Op; 4178 if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 4179 return error("Invalid record"); 4180 GEPIdx.push_back(Op); 4181 } 4182 4183 I = GetElementPtrInst::Create(Ty, BasePtr, GEPIdx); 4184 FullTy = GetElementPtrInst::getGEPReturnType(FullTy, I, GEPIdx); 4185 4186 InstructionList.push_back(I); 4187 if (InBounds) 4188 cast<GetElementPtrInst>(I)->setIsInBounds(true); 4189 break; 4190 } 4191 4192 case bitc::FUNC_CODE_INST_EXTRACTVAL: { 4193 // EXTRACTVAL: [opty, opval, n x indices] 4194 unsigned OpNum = 0; 4195 Value *Agg; 4196 if (getValueTypePair(Record, OpNum, NextValueNo, Agg, &FullTy)) 4197 return error("Invalid record"); 4198 4199 unsigned RecSize = Record.size(); 4200 if (OpNum == RecSize) 4201 return error("EXTRACTVAL: Invalid instruction with 0 indices"); 4202 4203 SmallVector<unsigned, 4> EXTRACTVALIdx; 4204 for (; OpNum != RecSize; ++OpNum) { 4205 bool IsArray = FullTy->isArrayTy(); 4206 bool IsStruct = FullTy->isStructTy(); 4207 uint64_t Index = Record[OpNum]; 4208 4209 if (!IsStruct && !IsArray) 4210 return error("EXTRACTVAL: Invalid type"); 4211 if ((unsigned)Index != Index) 4212 return error("Invalid value"); 4213 if (IsStruct && Index >= FullTy->getStructNumElements()) 4214 return error("EXTRACTVAL: Invalid struct index"); 4215 if (IsArray && Index >= FullTy->getArrayNumElements()) 4216 return error("EXTRACTVAL: Invalid array index"); 4217 EXTRACTVALIdx.push_back((unsigned)Index); 4218 4219 if (IsStruct) 4220 FullTy = FullTy->getStructElementType(Index); 4221 else 4222 FullTy = FullTy->getArrayElementType(); 4223 } 4224 4225 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx); 4226 InstructionList.push_back(I); 4227 break; 4228 } 4229 4230 case bitc::FUNC_CODE_INST_INSERTVAL: { 4231 // INSERTVAL: [opty, opval, opty, opval, n x indices] 4232 unsigned OpNum = 0; 4233 Value *Agg; 4234 if (getValueTypePair(Record, OpNum, NextValueNo, Agg, &FullTy)) 4235 return error("Invalid record"); 4236 Value *Val; 4237 if (getValueTypePair(Record, OpNum, NextValueNo, Val)) 4238 return error("Invalid record"); 4239 4240 unsigned RecSize = Record.size(); 4241 if (OpNum == RecSize) 4242 return error("INSERTVAL: Invalid instruction with 0 indices"); 4243 4244 SmallVector<unsigned, 4> INSERTVALIdx; 4245 Type *CurTy = Agg->getType(); 4246 for (; OpNum != RecSize; ++OpNum) { 4247 bool IsArray = CurTy->isArrayTy(); 4248 bool IsStruct = CurTy->isStructTy(); 4249 uint64_t Index = Record[OpNum]; 4250 4251 if (!IsStruct && !IsArray) 4252 return error("INSERTVAL: Invalid type"); 4253 if ((unsigned)Index != Index) 4254 return error("Invalid value"); 4255 if (IsStruct && Index >= CurTy->getStructNumElements()) 4256 return error("INSERTVAL: Invalid struct index"); 4257 if (IsArray && Index >= CurTy->getArrayNumElements()) 4258 return error("INSERTVAL: Invalid array index"); 4259 4260 INSERTVALIdx.push_back((unsigned)Index); 4261 if (IsStruct) 4262 CurTy = CurTy->getStructElementType(Index); 4263 else 4264 CurTy = CurTy->getArrayElementType(); 4265 } 4266 4267 if (CurTy != Val->getType()) 4268 return error("Inserted value type doesn't match aggregate type"); 4269 4270 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx); 4271 InstructionList.push_back(I); 4272 break; 4273 } 4274 4275 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval] 4276 // obsolete form of select 4277 // handles select i1 ... in old bitcode 4278 unsigned OpNum = 0; 4279 Value *TrueVal, *FalseVal, *Cond; 4280 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal, &FullTy) || 4281 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) || 4282 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond)) 4283 return error("Invalid record"); 4284 4285 I = SelectInst::Create(Cond, TrueVal, FalseVal); 4286 InstructionList.push_back(I); 4287 break; 4288 } 4289 4290 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred] 4291 // new form of select 4292 // handles select i1 or select [N x i1] 4293 unsigned OpNum = 0; 4294 Value *TrueVal, *FalseVal, *Cond; 4295 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal, &FullTy) || 4296 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) || 4297 getValueTypePair(Record, OpNum, NextValueNo, Cond)) 4298 return error("Invalid record"); 4299 4300 // select condition can be either i1 or [N x i1] 4301 if (VectorType* vector_type = 4302 dyn_cast<VectorType>(Cond->getType())) { 4303 // expect <n x i1> 4304 if (vector_type->getElementType() != Type::getInt1Ty(Context)) 4305 return error("Invalid type for value"); 4306 } else { 4307 // expect i1 4308 if (Cond->getType() != Type::getInt1Ty(Context)) 4309 return error("Invalid type for value"); 4310 } 4311 4312 I = SelectInst::Create(Cond, TrueVal, FalseVal); 4313 InstructionList.push_back(I); 4314 if (OpNum < Record.size() && isa<FPMathOperator>(I)) { 4315 FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]); 4316 if (FMF.any()) 4317 I->setFastMathFlags(FMF); 4318 } 4319 break; 4320 } 4321 4322 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval] 4323 unsigned OpNum = 0; 4324 Value *Vec, *Idx; 4325 if (getValueTypePair(Record, OpNum, NextValueNo, Vec, &FullTy) || 4326 getValueTypePair(Record, OpNum, NextValueNo, Idx)) 4327 return error("Invalid record"); 4328 if (!Vec->getType()->isVectorTy()) 4329 return error("Invalid type for value"); 4330 I = ExtractElementInst::Create(Vec, Idx); 4331 FullTy = cast<VectorType>(FullTy)->getElementType(); 4332 InstructionList.push_back(I); 4333 break; 4334 } 4335 4336 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval] 4337 unsigned OpNum = 0; 4338 Value *Vec, *Elt, *Idx; 4339 if (getValueTypePair(Record, OpNum, NextValueNo, Vec, &FullTy)) 4340 return error("Invalid record"); 4341 if (!Vec->getType()->isVectorTy()) 4342 return error("Invalid type for value"); 4343 if (popValue(Record, OpNum, NextValueNo, 4344 cast<VectorType>(Vec->getType())->getElementType(), Elt) || 4345 getValueTypePair(Record, OpNum, NextValueNo, Idx)) 4346 return error("Invalid record"); 4347 I = InsertElementInst::Create(Vec, Elt, Idx); 4348 InstructionList.push_back(I); 4349 break; 4350 } 4351 4352 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval] 4353 unsigned OpNum = 0; 4354 Value *Vec1, *Vec2, *Mask; 4355 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1, &FullTy) || 4356 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2)) 4357 return error("Invalid record"); 4358 4359 if (getValueTypePair(Record, OpNum, NextValueNo, Mask)) 4360 return error("Invalid record"); 4361 if (!Vec1->getType()->isVectorTy() || !Vec2->getType()->isVectorTy()) 4362 return error("Invalid type for value"); 4363 4364 I = new ShuffleVectorInst(Vec1, Vec2, Mask); 4365 FullTy = 4366 VectorType::get(cast<VectorType>(FullTy)->getElementType(), 4367 cast<VectorType>(Mask->getType())->getElementCount()); 4368 InstructionList.push_back(I); 4369 break; 4370 } 4371 4372 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred] 4373 // Old form of ICmp/FCmp returning bool 4374 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were 4375 // both legal on vectors but had different behaviour. 4376 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred] 4377 // FCmp/ICmp returning bool or vector of bool 4378 4379 unsigned OpNum = 0; 4380 Value *LHS, *RHS; 4381 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) || 4382 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS)) 4383 return error("Invalid record"); 4384 4385 if (OpNum >= Record.size()) 4386 return error( 4387 "Invalid record: operand number exceeded available operands"); 4388 4389 unsigned PredVal = Record[OpNum]; 4390 bool IsFP = LHS->getType()->isFPOrFPVectorTy(); 4391 FastMathFlags FMF; 4392 if (IsFP && Record.size() > OpNum+1) 4393 FMF = getDecodedFastMathFlags(Record[++OpNum]); 4394 4395 if (OpNum+1 != Record.size()) 4396 return error("Invalid record"); 4397 4398 if (LHS->getType()->isFPOrFPVectorTy()) 4399 I = new FCmpInst((FCmpInst::Predicate)PredVal, LHS, RHS); 4400 else 4401 I = new ICmpInst((ICmpInst::Predicate)PredVal, LHS, RHS); 4402 4403 if (FMF.any()) 4404 I->setFastMathFlags(FMF); 4405 InstructionList.push_back(I); 4406 break; 4407 } 4408 4409 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>] 4410 { 4411 unsigned Size = Record.size(); 4412 if (Size == 0) { 4413 I = ReturnInst::Create(Context); 4414 InstructionList.push_back(I); 4415 break; 4416 } 4417 4418 unsigned OpNum = 0; 4419 Value *Op = nullptr; 4420 if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 4421 return error("Invalid record"); 4422 if (OpNum != Record.size()) 4423 return error("Invalid record"); 4424 4425 I = ReturnInst::Create(Context, Op); 4426 InstructionList.push_back(I); 4427 break; 4428 } 4429 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#] 4430 if (Record.size() != 1 && Record.size() != 3) 4431 return error("Invalid record"); 4432 BasicBlock *TrueDest = getBasicBlock(Record[0]); 4433 if (!TrueDest) 4434 return error("Invalid record"); 4435 4436 if (Record.size() == 1) { 4437 I = BranchInst::Create(TrueDest); 4438 InstructionList.push_back(I); 4439 } 4440 else { 4441 BasicBlock *FalseDest = getBasicBlock(Record[1]); 4442 Value *Cond = getValue(Record, 2, NextValueNo, 4443 Type::getInt1Ty(Context)); 4444 if (!FalseDest || !Cond) 4445 return error("Invalid record"); 4446 I = BranchInst::Create(TrueDest, FalseDest, Cond); 4447 InstructionList.push_back(I); 4448 } 4449 break; 4450 } 4451 case bitc::FUNC_CODE_INST_CLEANUPRET: { // CLEANUPRET: [val] or [val,bb#] 4452 if (Record.size() != 1 && Record.size() != 2) 4453 return error("Invalid record"); 4454 unsigned Idx = 0; 4455 Value *CleanupPad = 4456 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context)); 4457 if (!CleanupPad) 4458 return error("Invalid record"); 4459 BasicBlock *UnwindDest = nullptr; 4460 if (Record.size() == 2) { 4461 UnwindDest = getBasicBlock(Record[Idx++]); 4462 if (!UnwindDest) 4463 return error("Invalid record"); 4464 } 4465 4466 I = CleanupReturnInst::Create(CleanupPad, UnwindDest); 4467 InstructionList.push_back(I); 4468 break; 4469 } 4470 case bitc::FUNC_CODE_INST_CATCHRET: { // CATCHRET: [val,bb#] 4471 if (Record.size() != 2) 4472 return error("Invalid record"); 4473 unsigned Idx = 0; 4474 Value *CatchPad = 4475 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context)); 4476 if (!CatchPad) 4477 return error("Invalid record"); 4478 BasicBlock *BB = getBasicBlock(Record[Idx++]); 4479 if (!BB) 4480 return error("Invalid record"); 4481 4482 I = CatchReturnInst::Create(CatchPad, BB); 4483 InstructionList.push_back(I); 4484 break; 4485 } 4486 case bitc::FUNC_CODE_INST_CATCHSWITCH: { // CATCHSWITCH: [tok,num,(bb)*,bb?] 4487 // We must have, at minimum, the outer scope and the number of arguments. 4488 if (Record.size() < 2) 4489 return error("Invalid record"); 4490 4491 unsigned Idx = 0; 4492 4493 Value *ParentPad = 4494 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context)); 4495 4496 unsigned NumHandlers = Record[Idx++]; 4497 4498 SmallVector<BasicBlock *, 2> Handlers; 4499 for (unsigned Op = 0; Op != NumHandlers; ++Op) { 4500 BasicBlock *BB = getBasicBlock(Record[Idx++]); 4501 if (!BB) 4502 return error("Invalid record"); 4503 Handlers.push_back(BB); 4504 } 4505 4506 BasicBlock *UnwindDest = nullptr; 4507 if (Idx + 1 == Record.size()) { 4508 UnwindDest = getBasicBlock(Record[Idx++]); 4509 if (!UnwindDest) 4510 return error("Invalid record"); 4511 } 4512 4513 if (Record.size() != Idx) 4514 return error("Invalid record"); 4515 4516 auto *CatchSwitch = 4517 CatchSwitchInst::Create(ParentPad, UnwindDest, NumHandlers); 4518 for (BasicBlock *Handler : Handlers) 4519 CatchSwitch->addHandler(Handler); 4520 I = CatchSwitch; 4521 InstructionList.push_back(I); 4522 break; 4523 } 4524 case bitc::FUNC_CODE_INST_CATCHPAD: 4525 case bitc::FUNC_CODE_INST_CLEANUPPAD: { // [tok,num,(ty,val)*] 4526 // We must have, at minimum, the outer scope and the number of arguments. 4527 if (Record.size() < 2) 4528 return error("Invalid record"); 4529 4530 unsigned Idx = 0; 4531 4532 Value *ParentPad = 4533 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context)); 4534 4535 unsigned NumArgOperands = Record[Idx++]; 4536 4537 SmallVector<Value *, 2> Args; 4538 for (unsigned Op = 0; Op != NumArgOperands; ++Op) { 4539 Value *Val; 4540 if (getValueTypePair(Record, Idx, NextValueNo, Val)) 4541 return error("Invalid record"); 4542 Args.push_back(Val); 4543 } 4544 4545 if (Record.size() != Idx) 4546 return error("Invalid record"); 4547 4548 if (BitCode == bitc::FUNC_CODE_INST_CLEANUPPAD) 4549 I = CleanupPadInst::Create(ParentPad, Args); 4550 else 4551 I = CatchPadInst::Create(ParentPad, Args); 4552 InstructionList.push_back(I); 4553 break; 4554 } 4555 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...] 4556 // Check magic 4557 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) { 4558 // "New" SwitchInst format with case ranges. The changes to write this 4559 // format were reverted but we still recognize bitcode that uses it. 4560 // Hopefully someday we will have support for case ranges and can use 4561 // this format again. 4562 4563 Type *OpTy = getTypeByID(Record[1]); 4564 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth(); 4565 4566 Value *Cond = getValue(Record, 2, NextValueNo, OpTy); 4567 BasicBlock *Default = getBasicBlock(Record[3]); 4568 if (!OpTy || !Cond || !Default) 4569 return error("Invalid record"); 4570 4571 unsigned NumCases = Record[4]; 4572 4573 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases); 4574 InstructionList.push_back(SI); 4575 4576 unsigned CurIdx = 5; 4577 for (unsigned i = 0; i != NumCases; ++i) { 4578 SmallVector<ConstantInt*, 1> CaseVals; 4579 unsigned NumItems = Record[CurIdx++]; 4580 for (unsigned ci = 0; ci != NumItems; ++ci) { 4581 bool isSingleNumber = Record[CurIdx++]; 4582 4583 APInt Low; 4584 unsigned ActiveWords = 1; 4585 if (ValueBitWidth > 64) 4586 ActiveWords = Record[CurIdx++]; 4587 Low = readWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords), 4588 ValueBitWidth); 4589 CurIdx += ActiveWords; 4590 4591 if (!isSingleNumber) { 4592 ActiveWords = 1; 4593 if (ValueBitWidth > 64) 4594 ActiveWords = Record[CurIdx++]; 4595 APInt High = readWideAPInt( 4596 makeArrayRef(&Record[CurIdx], ActiveWords), ValueBitWidth); 4597 CurIdx += ActiveWords; 4598 4599 // FIXME: It is not clear whether values in the range should be 4600 // compared as signed or unsigned values. The partially 4601 // implemented changes that used this format in the past used 4602 // unsigned comparisons. 4603 for ( ; Low.ule(High); ++Low) 4604 CaseVals.push_back(ConstantInt::get(Context, Low)); 4605 } else 4606 CaseVals.push_back(ConstantInt::get(Context, Low)); 4607 } 4608 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]); 4609 for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(), 4610 cve = CaseVals.end(); cvi != cve; ++cvi) 4611 SI->addCase(*cvi, DestBB); 4612 } 4613 I = SI; 4614 break; 4615 } 4616 4617 // Old SwitchInst format without case ranges. 4618 4619 if (Record.size() < 3 || (Record.size() & 1) == 0) 4620 return error("Invalid record"); 4621 Type *OpTy = getTypeByID(Record[0]); 4622 Value *Cond = getValue(Record, 1, NextValueNo, OpTy); 4623 BasicBlock *Default = getBasicBlock(Record[2]); 4624 if (!OpTy || !Cond || !Default) 4625 return error("Invalid record"); 4626 unsigned NumCases = (Record.size()-3)/2; 4627 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases); 4628 InstructionList.push_back(SI); 4629 for (unsigned i = 0, e = NumCases; i != e; ++i) { 4630 ConstantInt *CaseVal = 4631 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy)); 4632 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]); 4633 if (!CaseVal || !DestBB) { 4634 delete SI; 4635 return error("Invalid record"); 4636 } 4637 SI->addCase(CaseVal, DestBB); 4638 } 4639 I = SI; 4640 break; 4641 } 4642 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...] 4643 if (Record.size() < 2) 4644 return error("Invalid record"); 4645 Type *OpTy = getTypeByID(Record[0]); 4646 Value *Address = getValue(Record, 1, NextValueNo, OpTy); 4647 if (!OpTy || !Address) 4648 return error("Invalid record"); 4649 unsigned NumDests = Record.size()-2; 4650 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests); 4651 InstructionList.push_back(IBI); 4652 for (unsigned i = 0, e = NumDests; i != e; ++i) { 4653 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) { 4654 IBI->addDestination(DestBB); 4655 } else { 4656 delete IBI; 4657 return error("Invalid record"); 4658 } 4659 } 4660 I = IBI; 4661 break; 4662 } 4663 4664 case bitc::FUNC_CODE_INST_INVOKE: { 4665 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...] 4666 if (Record.size() < 4) 4667 return error("Invalid record"); 4668 unsigned OpNum = 0; 4669 AttributeList PAL = getAttributes(Record[OpNum++]); 4670 unsigned CCInfo = Record[OpNum++]; 4671 BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]); 4672 BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]); 4673 4674 FunctionType *FTy = nullptr; 4675 FunctionType *FullFTy = nullptr; 4676 if ((CCInfo >> 13) & 1) { 4677 FullFTy = 4678 dyn_cast<FunctionType>(getFullyStructuredTypeByID(Record[OpNum++])); 4679 if (!FullFTy) 4680 return error("Explicit invoke type is not a function type"); 4681 FTy = cast<FunctionType>(flattenPointerTypes(FullFTy)); 4682 } 4683 4684 Value *Callee; 4685 if (getValueTypePair(Record, OpNum, NextValueNo, Callee, &FullTy)) 4686 return error("Invalid record"); 4687 4688 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType()); 4689 if (!CalleeTy) 4690 return error("Callee is not a pointer"); 4691 if (!FTy) { 4692 FullFTy = 4693 dyn_cast<FunctionType>(cast<PointerType>(FullTy)->getElementType()); 4694 if (!FullFTy) 4695 return error("Callee is not of pointer to function type"); 4696 FTy = cast<FunctionType>(flattenPointerTypes(FullFTy)); 4697 } else if (getPointerElementFlatType(FullTy) != FTy) 4698 return error("Explicit invoke type does not match pointee type of " 4699 "callee operand"); 4700 if (Record.size() < FTy->getNumParams() + OpNum) 4701 return error("Insufficient operands to call"); 4702 4703 SmallVector<Value*, 16> Ops; 4704 SmallVector<Type *, 16> ArgsFullTys; 4705 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) { 4706 Ops.push_back(getValue(Record, OpNum, NextValueNo, 4707 FTy->getParamType(i))); 4708 ArgsFullTys.push_back(FullFTy->getParamType(i)); 4709 if (!Ops.back()) 4710 return error("Invalid record"); 4711 } 4712 4713 if (!FTy->isVarArg()) { 4714 if (Record.size() != OpNum) 4715 return error("Invalid record"); 4716 } else { 4717 // Read type/value pairs for varargs params. 4718 while (OpNum != Record.size()) { 4719 Value *Op; 4720 Type *FullTy; 4721 if (getValueTypePair(Record, OpNum, NextValueNo, Op, &FullTy)) 4722 return error("Invalid record"); 4723 Ops.push_back(Op); 4724 ArgsFullTys.push_back(FullTy); 4725 } 4726 } 4727 4728 I = InvokeInst::Create(FTy, Callee, NormalBB, UnwindBB, Ops, 4729 OperandBundles); 4730 FullTy = FullFTy->getReturnType(); 4731 OperandBundles.clear(); 4732 InstructionList.push_back(I); 4733 cast<InvokeInst>(I)->setCallingConv( 4734 static_cast<CallingConv::ID>(CallingConv::MaxID & CCInfo)); 4735 cast<InvokeInst>(I)->setAttributes(PAL); 4736 propagateByValSRetTypes(cast<CallBase>(I), ArgsFullTys); 4737 4738 break; 4739 } 4740 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval] 4741 unsigned Idx = 0; 4742 Value *Val = nullptr; 4743 if (getValueTypePair(Record, Idx, NextValueNo, Val)) 4744 return error("Invalid record"); 4745 I = ResumeInst::Create(Val); 4746 InstructionList.push_back(I); 4747 break; 4748 } 4749 case bitc::FUNC_CODE_INST_CALLBR: { 4750 // CALLBR: [attr, cc, norm, transfs, fty, fnid, args] 4751 unsigned OpNum = 0; 4752 AttributeList PAL = getAttributes(Record[OpNum++]); 4753 unsigned CCInfo = Record[OpNum++]; 4754 4755 BasicBlock *DefaultDest = getBasicBlock(Record[OpNum++]); 4756 unsigned NumIndirectDests = Record[OpNum++]; 4757 SmallVector<BasicBlock *, 16> IndirectDests; 4758 for (unsigned i = 0, e = NumIndirectDests; i != e; ++i) 4759 IndirectDests.push_back(getBasicBlock(Record[OpNum++])); 4760 4761 FunctionType *FTy = nullptr; 4762 FunctionType *FullFTy = nullptr; 4763 if ((CCInfo >> bitc::CALL_EXPLICIT_TYPE) & 1) { 4764 FullFTy = 4765 dyn_cast<FunctionType>(getFullyStructuredTypeByID(Record[OpNum++])); 4766 if (!FullFTy) 4767 return error("Explicit call type is not a function type"); 4768 FTy = cast<FunctionType>(flattenPointerTypes(FullFTy)); 4769 } 4770 4771 Value *Callee; 4772 if (getValueTypePair(Record, OpNum, NextValueNo, Callee, &FullTy)) 4773 return error("Invalid record"); 4774 4775 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType()); 4776 if (!OpTy) 4777 return error("Callee is not a pointer type"); 4778 if (!FTy) { 4779 FullFTy = 4780 dyn_cast<FunctionType>(cast<PointerType>(FullTy)->getElementType()); 4781 if (!FullFTy) 4782 return error("Callee is not of pointer to function type"); 4783 FTy = cast<FunctionType>(flattenPointerTypes(FullFTy)); 4784 } else if (getPointerElementFlatType(FullTy) != FTy) 4785 return error("Explicit call type does not match pointee type of " 4786 "callee operand"); 4787 if (Record.size() < FTy->getNumParams() + OpNum) 4788 return error("Insufficient operands to call"); 4789 4790 SmallVector<Value*, 16> Args; 4791 // Read the fixed params. 4792 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) { 4793 if (FTy->getParamType(i)->isLabelTy()) 4794 Args.push_back(getBasicBlock(Record[OpNum])); 4795 else 4796 Args.push_back(getValue(Record, OpNum, NextValueNo, 4797 FTy->getParamType(i))); 4798 if (!Args.back()) 4799 return error("Invalid record"); 4800 } 4801 4802 // Read type/value pairs for varargs params. 4803 if (!FTy->isVarArg()) { 4804 if (OpNum != Record.size()) 4805 return error("Invalid record"); 4806 } else { 4807 while (OpNum != Record.size()) { 4808 Value *Op; 4809 if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 4810 return error("Invalid record"); 4811 Args.push_back(Op); 4812 } 4813 } 4814 4815 I = CallBrInst::Create(FTy, Callee, DefaultDest, IndirectDests, Args, 4816 OperandBundles); 4817 FullTy = FullFTy->getReturnType(); 4818 OperandBundles.clear(); 4819 InstructionList.push_back(I); 4820 cast<CallBrInst>(I)->setCallingConv( 4821 static_cast<CallingConv::ID>((0x7ff & CCInfo) >> bitc::CALL_CCONV)); 4822 cast<CallBrInst>(I)->setAttributes(PAL); 4823 break; 4824 } 4825 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE 4826 I = new UnreachableInst(Context); 4827 InstructionList.push_back(I); 4828 break; 4829 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...] 4830 if (Record.empty()) 4831 return error("Invalid record"); 4832 // The first record specifies the type. 4833 FullTy = getFullyStructuredTypeByID(Record[0]); 4834 Type *Ty = flattenPointerTypes(FullTy); 4835 if (!Ty) 4836 return error("Invalid record"); 4837 4838 // Phi arguments are pairs of records of [value, basic block]. 4839 // There is an optional final record for fast-math-flags if this phi has a 4840 // floating-point type. 4841 size_t NumArgs = (Record.size() - 1) / 2; 4842 PHINode *PN = PHINode::Create(Ty, NumArgs); 4843 if ((Record.size() - 1) % 2 == 1 && !isa<FPMathOperator>(PN)) 4844 return error("Invalid record"); 4845 InstructionList.push_back(PN); 4846 4847 for (unsigned i = 0; i != NumArgs; i++) { 4848 Value *V; 4849 // With the new function encoding, it is possible that operands have 4850 // negative IDs (for forward references). Use a signed VBR 4851 // representation to keep the encoding small. 4852 if (UseRelativeIDs) 4853 V = getValueSigned(Record, i * 2 + 1, NextValueNo, Ty); 4854 else 4855 V = getValue(Record, i * 2 + 1, NextValueNo, Ty); 4856 BasicBlock *BB = getBasicBlock(Record[i * 2 + 2]); 4857 if (!V || !BB) 4858 return error("Invalid record"); 4859 PN->addIncoming(V, BB); 4860 } 4861 I = PN; 4862 4863 // If there are an even number of records, the final record must be FMF. 4864 if (Record.size() % 2 == 0) { 4865 assert(isa<FPMathOperator>(I) && "Unexpected phi type"); 4866 FastMathFlags FMF = getDecodedFastMathFlags(Record[Record.size() - 1]); 4867 if (FMF.any()) 4868 I->setFastMathFlags(FMF); 4869 } 4870 4871 break; 4872 } 4873 4874 case bitc::FUNC_CODE_INST_LANDINGPAD: 4875 case bitc::FUNC_CODE_INST_LANDINGPAD_OLD: { 4876 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?] 4877 unsigned Idx = 0; 4878 if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD) { 4879 if (Record.size() < 3) 4880 return error("Invalid record"); 4881 } else { 4882 assert(BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD); 4883 if (Record.size() < 4) 4884 return error("Invalid record"); 4885 } 4886 FullTy = getFullyStructuredTypeByID(Record[Idx++]); 4887 Type *Ty = flattenPointerTypes(FullTy); 4888 if (!Ty) 4889 return error("Invalid record"); 4890 if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD) { 4891 Value *PersFn = nullptr; 4892 if (getValueTypePair(Record, Idx, NextValueNo, PersFn)) 4893 return error("Invalid record"); 4894 4895 if (!F->hasPersonalityFn()) 4896 F->setPersonalityFn(cast<Constant>(PersFn)); 4897 else if (F->getPersonalityFn() != cast<Constant>(PersFn)) 4898 return error("Personality function mismatch"); 4899 } 4900 4901 bool IsCleanup = !!Record[Idx++]; 4902 unsigned NumClauses = Record[Idx++]; 4903 LandingPadInst *LP = LandingPadInst::Create(Ty, NumClauses); 4904 LP->setCleanup(IsCleanup); 4905 for (unsigned J = 0; J != NumClauses; ++J) { 4906 LandingPadInst::ClauseType CT = 4907 LandingPadInst::ClauseType(Record[Idx++]); (void)CT; 4908 Value *Val; 4909 4910 if (getValueTypePair(Record, Idx, NextValueNo, Val)) { 4911 delete LP; 4912 return error("Invalid record"); 4913 } 4914 4915 assert((CT != LandingPadInst::Catch || 4916 !isa<ArrayType>(Val->getType())) && 4917 "Catch clause has a invalid type!"); 4918 assert((CT != LandingPadInst::Filter || 4919 isa<ArrayType>(Val->getType())) && 4920 "Filter clause has invalid type!"); 4921 LP->addClause(cast<Constant>(Val)); 4922 } 4923 4924 I = LP; 4925 InstructionList.push_back(I); 4926 break; 4927 } 4928 4929 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align] 4930 if (Record.size() != 4) 4931 return error("Invalid record"); 4932 using APV = AllocaPackedValues; 4933 const uint64_t Rec = Record[3]; 4934 const bool InAlloca = Bitfield::get<APV::UsedWithInAlloca>(Rec); 4935 const bool SwiftError = Bitfield::get<APV::SwiftError>(Rec); 4936 FullTy = getFullyStructuredTypeByID(Record[0]); 4937 Type *Ty = flattenPointerTypes(FullTy); 4938 if (!Bitfield::get<APV::ExplicitType>(Rec)) { 4939 auto *PTy = dyn_cast_or_null<PointerType>(Ty); 4940 if (!PTy) 4941 return error("Old-style alloca with a non-pointer type"); 4942 std::tie(FullTy, Ty) = getPointerElementTypes(FullTy); 4943 } 4944 Type *OpTy = getTypeByID(Record[1]); 4945 Value *Size = getFnValueByID(Record[2], OpTy); 4946 MaybeAlign Align; 4947 if (Error Err = 4948 parseAlignmentValue(Bitfield::get<APV::Align>(Rec), Align)) { 4949 return Err; 4950 } 4951 if (!Ty || !Size) 4952 return error("Invalid record"); 4953 4954 // FIXME: Make this an optional field. 4955 const DataLayout &DL = TheModule->getDataLayout(); 4956 unsigned AS = DL.getAllocaAddrSpace(); 4957 4958 SmallPtrSet<Type *, 4> Visited; 4959 if (!Align && !Ty->isSized(&Visited)) 4960 return error("alloca of unsized type"); 4961 if (!Align) 4962 Align = DL.getPrefTypeAlign(Ty); 4963 4964 AllocaInst *AI = new AllocaInst(Ty, AS, Size, *Align); 4965 AI->setUsedWithInAlloca(InAlloca); 4966 AI->setSwiftError(SwiftError); 4967 I = AI; 4968 FullTy = PointerType::get(FullTy, AS); 4969 InstructionList.push_back(I); 4970 break; 4971 } 4972 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol] 4973 unsigned OpNum = 0; 4974 Value *Op; 4975 if (getValueTypePair(Record, OpNum, NextValueNo, Op, &FullTy) || 4976 (OpNum + 2 != Record.size() && OpNum + 3 != Record.size())) 4977 return error("Invalid record"); 4978 4979 if (!isa<PointerType>(Op->getType())) 4980 return error("Load operand is not a pointer type"); 4981 4982 Type *Ty = nullptr; 4983 if (OpNum + 3 == Record.size()) { 4984 FullTy = getFullyStructuredTypeByID(Record[OpNum++]); 4985 Ty = flattenPointerTypes(FullTy); 4986 } else 4987 std::tie(FullTy, Ty) = getPointerElementTypes(FullTy); 4988 4989 if (Error Err = typeCheckLoadStoreInst(Ty, Op->getType())) 4990 return Err; 4991 4992 MaybeAlign Align; 4993 if (Error Err = parseAlignmentValue(Record[OpNum], Align)) 4994 return Err; 4995 SmallPtrSet<Type *, 4> Visited; 4996 if (!Align && !Ty->isSized(&Visited)) 4997 return error("load of unsized type"); 4998 if (!Align) 4999 Align = TheModule->getDataLayout().getABITypeAlign(Ty); 5000 I = new LoadInst(Ty, Op, "", Record[OpNum + 1], *Align); 5001 InstructionList.push_back(I); 5002 break; 5003 } 5004 case bitc::FUNC_CODE_INST_LOADATOMIC: { 5005 // LOADATOMIC: [opty, op, align, vol, ordering, ssid] 5006 unsigned OpNum = 0; 5007 Value *Op; 5008 if (getValueTypePair(Record, OpNum, NextValueNo, Op, &FullTy) || 5009 (OpNum + 4 != Record.size() && OpNum + 5 != Record.size())) 5010 return error("Invalid record"); 5011 5012 if (!isa<PointerType>(Op->getType())) 5013 return error("Load operand is not a pointer type"); 5014 5015 Type *Ty = nullptr; 5016 if (OpNum + 5 == Record.size()) { 5017 FullTy = getFullyStructuredTypeByID(Record[OpNum++]); 5018 Ty = flattenPointerTypes(FullTy); 5019 } else 5020 std::tie(FullTy, Ty) = getPointerElementTypes(FullTy); 5021 5022 if (Error Err = typeCheckLoadStoreInst(Ty, Op->getType())) 5023 return Err; 5024 5025 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]); 5026 if (Ordering == AtomicOrdering::NotAtomic || 5027 Ordering == AtomicOrdering::Release || 5028 Ordering == AtomicOrdering::AcquireRelease) 5029 return error("Invalid record"); 5030 if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0) 5031 return error("Invalid record"); 5032 SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]); 5033 5034 MaybeAlign Align; 5035 if (Error Err = parseAlignmentValue(Record[OpNum], Align)) 5036 return Err; 5037 if (!Align) 5038 return error("Alignment missing from atomic load"); 5039 I = new LoadInst(Ty, Op, "", Record[OpNum + 1], *Align, Ordering, SSID); 5040 InstructionList.push_back(I); 5041 break; 5042 } 5043 case bitc::FUNC_CODE_INST_STORE: 5044 case bitc::FUNC_CODE_INST_STORE_OLD: { // STORE2:[ptrty, ptr, val, align, vol] 5045 unsigned OpNum = 0; 5046 Value *Val, *Ptr; 5047 Type *FullTy; 5048 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, &FullTy) || 5049 (BitCode == bitc::FUNC_CODE_INST_STORE 5050 ? getValueTypePair(Record, OpNum, NextValueNo, Val) 5051 : popValue(Record, OpNum, NextValueNo, 5052 getPointerElementFlatType(FullTy), Val)) || 5053 OpNum + 2 != Record.size()) 5054 return error("Invalid record"); 5055 5056 if (Error Err = typeCheckLoadStoreInst(Val->getType(), Ptr->getType())) 5057 return Err; 5058 MaybeAlign Align; 5059 if (Error Err = parseAlignmentValue(Record[OpNum], Align)) 5060 return Err; 5061 SmallPtrSet<Type *, 4> Visited; 5062 if (!Align && !Val->getType()->isSized(&Visited)) 5063 return error("store of unsized type"); 5064 if (!Align) 5065 Align = TheModule->getDataLayout().getABITypeAlign(Val->getType()); 5066 I = new StoreInst(Val, Ptr, Record[OpNum + 1], *Align); 5067 InstructionList.push_back(I); 5068 break; 5069 } 5070 case bitc::FUNC_CODE_INST_STOREATOMIC: 5071 case bitc::FUNC_CODE_INST_STOREATOMIC_OLD: { 5072 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, ssid] 5073 unsigned OpNum = 0; 5074 Value *Val, *Ptr; 5075 Type *FullTy; 5076 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, &FullTy) || 5077 !isa<PointerType>(Ptr->getType()) || 5078 (BitCode == bitc::FUNC_CODE_INST_STOREATOMIC 5079 ? getValueTypePair(Record, OpNum, NextValueNo, Val) 5080 : popValue(Record, OpNum, NextValueNo, 5081 getPointerElementFlatType(FullTy), Val)) || 5082 OpNum + 4 != Record.size()) 5083 return error("Invalid record"); 5084 5085 if (Error Err = typeCheckLoadStoreInst(Val->getType(), Ptr->getType())) 5086 return Err; 5087 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]); 5088 if (Ordering == AtomicOrdering::NotAtomic || 5089 Ordering == AtomicOrdering::Acquire || 5090 Ordering == AtomicOrdering::AcquireRelease) 5091 return error("Invalid record"); 5092 SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]); 5093 if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0) 5094 return error("Invalid record"); 5095 5096 MaybeAlign Align; 5097 if (Error Err = parseAlignmentValue(Record[OpNum], Align)) 5098 return Err; 5099 if (!Align) 5100 return error("Alignment missing from atomic store"); 5101 I = new StoreInst(Val, Ptr, Record[OpNum + 1], *Align, Ordering, SSID); 5102 InstructionList.push_back(I); 5103 break; 5104 } 5105 case bitc::FUNC_CODE_INST_CMPXCHG_OLD: { 5106 // CMPXCHG_OLD: [ptrty, ptr, cmp, val, vol, ordering, synchscope, 5107 // failure_ordering?, weak?] 5108 const size_t NumRecords = Record.size(); 5109 unsigned OpNum = 0; 5110 Value *Ptr = nullptr; 5111 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, &FullTy)) 5112 return error("Invalid record"); 5113 5114 if (!isa<PointerType>(Ptr->getType())) 5115 return error("Cmpxchg operand is not a pointer type"); 5116 5117 Value *Cmp = nullptr; 5118 if (popValue(Record, OpNum, NextValueNo, 5119 getPointerElementFlatType(FullTy), Cmp)) 5120 return error("Invalid record"); 5121 5122 FullTy = cast<PointerType>(FullTy)->getElementType(); 5123 5124 Value *New = nullptr; 5125 if (popValue(Record, OpNum, NextValueNo, Cmp->getType(), New) || 5126 NumRecords < OpNum + 3 || NumRecords > OpNum + 5) 5127 return error("Invalid record"); 5128 5129 const AtomicOrdering SuccessOrdering = 5130 getDecodedOrdering(Record[OpNum + 1]); 5131 if (SuccessOrdering == AtomicOrdering::NotAtomic || 5132 SuccessOrdering == AtomicOrdering::Unordered) 5133 return error("Invalid record"); 5134 5135 const SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 2]); 5136 5137 if (Error Err = typeCheckLoadStoreInst(Cmp->getType(), Ptr->getType())) 5138 return Err; 5139 5140 const AtomicOrdering FailureOrdering = 5141 NumRecords < 7 5142 ? AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering) 5143 : getDecodedOrdering(Record[OpNum + 3]); 5144 5145 const Align Alignment( 5146 TheModule->getDataLayout().getTypeStoreSize(Cmp->getType())); 5147 5148 I = new AtomicCmpXchgInst(Ptr, Cmp, New, Alignment, SuccessOrdering, 5149 FailureOrdering, SSID); 5150 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]); 5151 FullTy = StructType::get(Context, {FullTy, Type::getInt1Ty(Context)}); 5152 5153 if (NumRecords < 8) { 5154 // Before weak cmpxchgs existed, the instruction simply returned the 5155 // value loaded from memory, so bitcode files from that era will be 5156 // expecting the first component of a modern cmpxchg. 5157 CurBB->getInstList().push_back(I); 5158 I = ExtractValueInst::Create(I, 0); 5159 FullTy = cast<StructType>(FullTy)->getElementType(0); 5160 } else { 5161 cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum + 4]); 5162 } 5163 5164 InstructionList.push_back(I); 5165 break; 5166 } 5167 case bitc::FUNC_CODE_INST_CMPXCHG: { 5168 // CMPXCHG: [ptrty, ptr, cmp, val, vol, success_ordering, synchscope, 5169 // failure_ordering, weak, align?] 5170 const size_t NumRecords = Record.size(); 5171 unsigned OpNum = 0; 5172 Value *Ptr = nullptr; 5173 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, &FullTy)) 5174 return error("Invalid record"); 5175 5176 if (!isa<PointerType>(Ptr->getType())) 5177 return error("Cmpxchg operand is not a pointer type"); 5178 5179 Value *Cmp = nullptr; 5180 if (getValueTypePair(Record, OpNum, NextValueNo, Cmp, &FullTy)) 5181 return error("Invalid record"); 5182 5183 Value *Val = nullptr; 5184 if (popValue(Record, OpNum, NextValueNo, Cmp->getType(), Val)) 5185 return error("Invalid record"); 5186 5187 if (NumRecords < OpNum + 3 || NumRecords > OpNum + 6) 5188 return error("Invalid record"); 5189 5190 const bool IsVol = Record[OpNum]; 5191 5192 const AtomicOrdering SuccessOrdering = 5193 getDecodedOrdering(Record[OpNum + 1]); 5194 if (SuccessOrdering == AtomicOrdering::NotAtomic || 5195 SuccessOrdering == AtomicOrdering::Unordered) 5196 return error("Invalid record"); 5197 5198 const SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 2]); 5199 5200 if (Error Err = typeCheckLoadStoreInst(Cmp->getType(), Ptr->getType())) 5201 return Err; 5202 5203 const AtomicOrdering FailureOrdering = 5204 getDecodedOrdering(Record[OpNum + 3]); 5205 5206 const bool IsWeak = Record[OpNum + 4]; 5207 5208 MaybeAlign Alignment; 5209 5210 if (NumRecords == (OpNum + 6)) { 5211 if (Error Err = parseAlignmentValue(Record[OpNum + 5], Alignment)) 5212 return Err; 5213 } 5214 if (!Alignment) 5215 Alignment = 5216 Align(TheModule->getDataLayout().getTypeStoreSize(Cmp->getType())); 5217 5218 I = new AtomicCmpXchgInst(Ptr, Cmp, Val, *Alignment, SuccessOrdering, 5219 FailureOrdering, SSID); 5220 FullTy = StructType::get(Context, {FullTy, Type::getInt1Ty(Context)}); 5221 cast<AtomicCmpXchgInst>(I)->setVolatile(IsVol); 5222 cast<AtomicCmpXchgInst>(I)->setWeak(IsWeak); 5223 5224 InstructionList.push_back(I); 5225 break; 5226 } 5227 case bitc::FUNC_CODE_INST_ATOMICRMW: { 5228 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, ssid, align?] 5229 const size_t NumRecords = Record.size(); 5230 unsigned OpNum = 0; 5231 5232 Value *Ptr = nullptr; 5233 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, &FullTy)) 5234 return error("Invalid record"); 5235 5236 if (!isa<PointerType>(Ptr->getType())) 5237 return error("Invalid record"); 5238 5239 Value *Val = nullptr; 5240 if (popValue(Record, OpNum, NextValueNo, 5241 getPointerElementFlatType(FullTy), Val)) 5242 return error("Invalid record"); 5243 5244 if (!(NumRecords == (OpNum + 4) || NumRecords == (OpNum + 5))) 5245 return error("Invalid record"); 5246 5247 const AtomicRMWInst::BinOp Operation = 5248 getDecodedRMWOperation(Record[OpNum]); 5249 if (Operation < AtomicRMWInst::FIRST_BINOP || 5250 Operation > AtomicRMWInst::LAST_BINOP) 5251 return error("Invalid record"); 5252 5253 const bool IsVol = Record[OpNum + 1]; 5254 5255 const AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]); 5256 if (Ordering == AtomicOrdering::NotAtomic || 5257 Ordering == AtomicOrdering::Unordered) 5258 return error("Invalid record"); 5259 5260 const SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]); 5261 5262 MaybeAlign Alignment; 5263 5264 if (NumRecords == (OpNum + 5)) { 5265 if (Error Err = parseAlignmentValue(Record[OpNum + 4], Alignment)) 5266 return Err; 5267 } 5268 5269 if (!Alignment) 5270 Alignment = 5271 Align(TheModule->getDataLayout().getTypeStoreSize(Val->getType())); 5272 5273 I = new AtomicRMWInst(Operation, Ptr, Val, *Alignment, Ordering, SSID); 5274 FullTy = getPointerElementFlatType(FullTy); 5275 cast<AtomicRMWInst>(I)->setVolatile(IsVol); 5276 5277 InstructionList.push_back(I); 5278 break; 5279 } 5280 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, ssid] 5281 if (2 != Record.size()) 5282 return error("Invalid record"); 5283 AtomicOrdering Ordering = getDecodedOrdering(Record[0]); 5284 if (Ordering == AtomicOrdering::NotAtomic || 5285 Ordering == AtomicOrdering::Unordered || 5286 Ordering == AtomicOrdering::Monotonic) 5287 return error("Invalid record"); 5288 SyncScope::ID SSID = getDecodedSyncScopeID(Record[1]); 5289 I = new FenceInst(Context, Ordering, SSID); 5290 InstructionList.push_back(I); 5291 break; 5292 } 5293 case bitc::FUNC_CODE_INST_CALL: { 5294 // CALL: [paramattrs, cc, fmf, fnty, fnid, arg0, arg1...] 5295 if (Record.size() < 3) 5296 return error("Invalid record"); 5297 5298 unsigned OpNum = 0; 5299 AttributeList PAL = getAttributes(Record[OpNum++]); 5300 unsigned CCInfo = Record[OpNum++]; 5301 5302 FastMathFlags FMF; 5303 if ((CCInfo >> bitc::CALL_FMF) & 1) { 5304 FMF = getDecodedFastMathFlags(Record[OpNum++]); 5305 if (!FMF.any()) 5306 return error("Fast math flags indicator set for call with no FMF"); 5307 } 5308 5309 FunctionType *FTy = nullptr; 5310 FunctionType *FullFTy = nullptr; 5311 if ((CCInfo >> bitc::CALL_EXPLICIT_TYPE) & 1) { 5312 FullFTy = 5313 dyn_cast<FunctionType>(getFullyStructuredTypeByID(Record[OpNum++])); 5314 if (!FullFTy) 5315 return error("Explicit call type is not a function type"); 5316 FTy = cast<FunctionType>(flattenPointerTypes(FullFTy)); 5317 } 5318 5319 Value *Callee; 5320 if (getValueTypePair(Record, OpNum, NextValueNo, Callee, &FullTy)) 5321 return error("Invalid record"); 5322 5323 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType()); 5324 if (!OpTy) 5325 return error("Callee is not a pointer type"); 5326 if (!FTy) { 5327 FullFTy = 5328 dyn_cast<FunctionType>(cast<PointerType>(FullTy)->getElementType()); 5329 if (!FullFTy) 5330 return error("Callee is not of pointer to function type"); 5331 FTy = cast<FunctionType>(flattenPointerTypes(FullFTy)); 5332 } else if (getPointerElementFlatType(FullTy) != FTy) 5333 return error("Explicit call type does not match pointee type of " 5334 "callee operand"); 5335 if (Record.size() < FTy->getNumParams() + OpNum) 5336 return error("Insufficient operands to call"); 5337 5338 SmallVector<Value*, 16> Args; 5339 SmallVector<Type*, 16> ArgsFullTys; 5340 // Read the fixed params. 5341 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) { 5342 if (FTy->getParamType(i)->isLabelTy()) 5343 Args.push_back(getBasicBlock(Record[OpNum])); 5344 else 5345 Args.push_back(getValue(Record, OpNum, NextValueNo, 5346 FTy->getParamType(i))); 5347 ArgsFullTys.push_back(FullFTy->getParamType(i)); 5348 if (!Args.back()) 5349 return error("Invalid record"); 5350 } 5351 5352 // Read type/value pairs for varargs params. 5353 if (!FTy->isVarArg()) { 5354 if (OpNum != Record.size()) 5355 return error("Invalid record"); 5356 } else { 5357 while (OpNum != Record.size()) { 5358 Value *Op; 5359 Type *FullTy; 5360 if (getValueTypePair(Record, OpNum, NextValueNo, Op, &FullTy)) 5361 return error("Invalid record"); 5362 Args.push_back(Op); 5363 ArgsFullTys.push_back(FullTy); 5364 } 5365 } 5366 5367 I = CallInst::Create(FTy, Callee, Args, OperandBundles); 5368 FullTy = FullFTy->getReturnType(); 5369 OperandBundles.clear(); 5370 InstructionList.push_back(I); 5371 cast<CallInst>(I)->setCallingConv( 5372 static_cast<CallingConv::ID>((0x7ff & CCInfo) >> bitc::CALL_CCONV)); 5373 CallInst::TailCallKind TCK = CallInst::TCK_None; 5374 if (CCInfo & 1 << bitc::CALL_TAIL) 5375 TCK = CallInst::TCK_Tail; 5376 if (CCInfo & (1 << bitc::CALL_MUSTTAIL)) 5377 TCK = CallInst::TCK_MustTail; 5378 if (CCInfo & (1 << bitc::CALL_NOTAIL)) 5379 TCK = CallInst::TCK_NoTail; 5380 cast<CallInst>(I)->setTailCallKind(TCK); 5381 cast<CallInst>(I)->setAttributes(PAL); 5382 propagateByValSRetTypes(cast<CallBase>(I), ArgsFullTys); 5383 if (FMF.any()) { 5384 if (!isa<FPMathOperator>(I)) 5385 return error("Fast-math-flags specified for call without " 5386 "floating-point scalar or vector return type"); 5387 I->setFastMathFlags(FMF); 5388 } 5389 break; 5390 } 5391 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty] 5392 if (Record.size() < 3) 5393 return error("Invalid record"); 5394 Type *OpTy = getTypeByID(Record[0]); 5395 Value *Op = getValue(Record, 1, NextValueNo, OpTy); 5396 FullTy = getFullyStructuredTypeByID(Record[2]); 5397 Type *ResTy = flattenPointerTypes(FullTy); 5398 if (!OpTy || !Op || !ResTy) 5399 return error("Invalid record"); 5400 I = new VAArgInst(Op, ResTy); 5401 InstructionList.push_back(I); 5402 break; 5403 } 5404 5405 case bitc::FUNC_CODE_OPERAND_BUNDLE: { 5406 // A call or an invoke can be optionally prefixed with some variable 5407 // number of operand bundle blocks. These blocks are read into 5408 // OperandBundles and consumed at the next call or invoke instruction. 5409 5410 if (Record.empty() || Record[0] >= BundleTags.size()) 5411 return error("Invalid record"); 5412 5413 std::vector<Value *> Inputs; 5414 5415 unsigned OpNum = 1; 5416 while (OpNum != Record.size()) { 5417 Value *Op; 5418 if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 5419 return error("Invalid record"); 5420 Inputs.push_back(Op); 5421 } 5422 5423 OperandBundles.emplace_back(BundleTags[Record[0]], std::move(Inputs)); 5424 continue; 5425 } 5426 5427 case bitc::FUNC_CODE_INST_FREEZE: { // FREEZE: [opty,opval] 5428 unsigned OpNum = 0; 5429 Value *Op = nullptr; 5430 if (getValueTypePair(Record, OpNum, NextValueNo, Op, &FullTy)) 5431 return error("Invalid record"); 5432 if (OpNum != Record.size()) 5433 return error("Invalid record"); 5434 5435 I = new FreezeInst(Op); 5436 InstructionList.push_back(I); 5437 break; 5438 } 5439 } 5440 5441 // Add instruction to end of current BB. If there is no current BB, reject 5442 // this file. 5443 if (!CurBB) { 5444 I->deleteValue(); 5445 return error("Invalid instruction with no BB"); 5446 } 5447 if (!OperandBundles.empty()) { 5448 I->deleteValue(); 5449 return error("Operand bundles found with no consumer"); 5450 } 5451 CurBB->getInstList().push_back(I); 5452 5453 // If this was a terminator instruction, move to the next block. 5454 if (I->isTerminator()) { 5455 ++CurBBNo; 5456 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr; 5457 } 5458 5459 // Non-void values get registered in the value table for future use. 5460 if (!I->getType()->isVoidTy()) { 5461 if (!FullTy) { 5462 FullTy = I->getType(); 5463 assert( 5464 !FullTy->isPointerTy() && !isa<StructType>(FullTy) && 5465 !isa<ArrayType>(FullTy) && 5466 (!isa<VectorType>(FullTy) || 5467 cast<VectorType>(FullTy)->getElementType()->isFloatingPointTy() || 5468 cast<VectorType>(FullTy)->getElementType()->isIntegerTy()) && 5469 "Structured types must be assigned with corresponding non-opaque " 5470 "pointer type"); 5471 } 5472 5473 assert(I->getType() == flattenPointerTypes(FullTy) && 5474 "Incorrect fully structured type provided for Instruction"); 5475 ValueList.assignValue(I, NextValueNo++, FullTy); 5476 } 5477 } 5478 5479 OutOfRecordLoop: 5480 5481 if (!OperandBundles.empty()) 5482 return error("Operand bundles found with no consumer"); 5483 5484 // Check the function list for unresolved values. 5485 if (Argument *A = dyn_cast<Argument>(ValueList.back())) { 5486 if (!A->getParent()) { 5487 // We found at least one unresolved value. Nuke them all to avoid leaks. 5488 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){ 5489 if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) { 5490 A->replaceAllUsesWith(UndefValue::get(A->getType())); 5491 delete A; 5492 } 5493 } 5494 return error("Never resolved value found in function"); 5495 } 5496 } 5497 5498 // Unexpected unresolved metadata about to be dropped. 5499 if (MDLoader->hasFwdRefs()) 5500 return error("Invalid function metadata: outgoing forward refs"); 5501 5502 // Trim the value list down to the size it was before we parsed this function. 5503 ValueList.shrinkTo(ModuleValueListSize); 5504 MDLoader->shrinkTo(ModuleMDLoaderSize); 5505 std::vector<BasicBlock*>().swap(FunctionBBs); 5506 return Error::success(); 5507 } 5508 5509 /// Find the function body in the bitcode stream 5510 Error BitcodeReader::findFunctionInStream( 5511 Function *F, 5512 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) { 5513 while (DeferredFunctionInfoIterator->second == 0) { 5514 // This is the fallback handling for the old format bitcode that 5515 // didn't contain the function index in the VST, or when we have 5516 // an anonymous function which would not have a VST entry. 5517 // Assert that we have one of those two cases. 5518 assert(VSTOffset == 0 || !F->hasName()); 5519 // Parse the next body in the stream and set its position in the 5520 // DeferredFunctionInfo map. 5521 if (Error Err = rememberAndSkipFunctionBodies()) 5522 return Err; 5523 } 5524 return Error::success(); 5525 } 5526 5527 SyncScope::ID BitcodeReader::getDecodedSyncScopeID(unsigned Val) { 5528 if (Val == SyncScope::SingleThread || Val == SyncScope::System) 5529 return SyncScope::ID(Val); 5530 if (Val >= SSIDs.size()) 5531 return SyncScope::System; // Map unknown synchronization scopes to system. 5532 return SSIDs[Val]; 5533 } 5534 5535 //===----------------------------------------------------------------------===// 5536 // GVMaterializer implementation 5537 //===----------------------------------------------------------------------===// 5538 5539 Error BitcodeReader::materialize(GlobalValue *GV) { 5540 Function *F = dyn_cast<Function>(GV); 5541 // If it's not a function or is already material, ignore the request. 5542 if (!F || !F->isMaterializable()) 5543 return Error::success(); 5544 5545 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F); 5546 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!"); 5547 // If its position is recorded as 0, its body is somewhere in the stream 5548 // but we haven't seen it yet. 5549 if (DFII->second == 0) 5550 if (Error Err = findFunctionInStream(F, DFII)) 5551 return Err; 5552 5553 // Materialize metadata before parsing any function bodies. 5554 if (Error Err = materializeMetadata()) 5555 return Err; 5556 5557 // Move the bit stream to the saved position of the deferred function body. 5558 if (Error JumpFailed = Stream.JumpToBit(DFII->second)) 5559 return JumpFailed; 5560 if (Error Err = parseFunctionBody(F)) 5561 return Err; 5562 F->setIsMaterializable(false); 5563 5564 if (StripDebugInfo) 5565 stripDebugInfo(*F); 5566 5567 // Upgrade any old intrinsic calls in the function. 5568 for (auto &I : UpgradedIntrinsics) { 5569 for (auto UI = I.first->materialized_user_begin(), UE = I.first->user_end(); 5570 UI != UE;) { 5571 User *U = *UI; 5572 ++UI; 5573 if (CallInst *CI = dyn_cast<CallInst>(U)) 5574 UpgradeIntrinsicCall(CI, I.second); 5575 } 5576 } 5577 5578 // Update calls to the remangled intrinsics 5579 for (auto &I : RemangledIntrinsics) 5580 for (auto UI = I.first->materialized_user_begin(), UE = I.first->user_end(); 5581 UI != UE;) 5582 // Don't expect any other users than call sites 5583 cast<CallBase>(*UI++)->setCalledFunction(I.second); 5584 5585 // Finish fn->subprogram upgrade for materialized functions. 5586 if (DISubprogram *SP = MDLoader->lookupSubprogramForFunction(F)) 5587 F->setSubprogram(SP); 5588 5589 // Check if the TBAA Metadata are valid, otherwise we will need to strip them. 5590 if (!MDLoader->isStrippingTBAA()) { 5591 for (auto &I : instructions(F)) { 5592 MDNode *TBAA = I.getMetadata(LLVMContext::MD_tbaa); 5593 if (!TBAA || TBAAVerifyHelper.visitTBAAMetadata(I, TBAA)) 5594 continue; 5595 MDLoader->setStripTBAA(true); 5596 stripTBAA(F->getParent()); 5597 } 5598 } 5599 5600 for (auto &I : instructions(F)) { 5601 // "Upgrade" older incorrect branch weights by dropping them. 5602 if (auto *MD = I.getMetadata(LLVMContext::MD_prof)) { 5603 if (MD->getOperand(0) != nullptr && isa<MDString>(MD->getOperand(0))) { 5604 MDString *MDS = cast<MDString>(MD->getOperand(0)); 5605 StringRef ProfName = MDS->getString(); 5606 // Check consistency of !prof branch_weights metadata. 5607 if (!ProfName.equals("branch_weights")) 5608 continue; 5609 unsigned ExpectedNumOperands = 0; 5610 if (BranchInst *BI = dyn_cast<BranchInst>(&I)) 5611 ExpectedNumOperands = BI->getNumSuccessors(); 5612 else if (SwitchInst *SI = dyn_cast<SwitchInst>(&I)) 5613 ExpectedNumOperands = SI->getNumSuccessors(); 5614 else if (isa<CallInst>(&I)) 5615 ExpectedNumOperands = 1; 5616 else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(&I)) 5617 ExpectedNumOperands = IBI->getNumDestinations(); 5618 else if (isa<SelectInst>(&I)) 5619 ExpectedNumOperands = 2; 5620 else 5621 continue; // ignore and continue. 5622 5623 // If branch weight doesn't match, just strip branch weight. 5624 if (MD->getNumOperands() != 1 + ExpectedNumOperands) 5625 I.setMetadata(LLVMContext::MD_prof, nullptr); 5626 } 5627 } 5628 5629 // Remove align from return attribute on CallInst. 5630 if (auto *CI = dyn_cast<CallInst>(&I)) { 5631 if (CI->getFunctionType()->getReturnType()->isVoidTy()) 5632 CI->removeAttribute(0, Attribute::Alignment); 5633 } 5634 } 5635 5636 // Look for functions that rely on old function attribute behavior. 5637 UpgradeFunctionAttributes(*F); 5638 5639 // Bring in any functions that this function forward-referenced via 5640 // blockaddresses. 5641 return materializeForwardReferencedFunctions(); 5642 } 5643 5644 Error BitcodeReader::materializeModule() { 5645 if (Error Err = materializeMetadata()) 5646 return Err; 5647 5648 // Promise to materialize all forward references. 5649 WillMaterializeAllForwardRefs = true; 5650 5651 // Iterate over the module, deserializing any functions that are still on 5652 // disk. 5653 for (Function &F : *TheModule) { 5654 if (Error Err = materialize(&F)) 5655 return Err; 5656 } 5657 // At this point, if there are any function bodies, parse the rest of 5658 // the bits in the module past the last function block we have recorded 5659 // through either lazy scanning or the VST. 5660 if (LastFunctionBlockBit || NextUnreadBit) 5661 if (Error Err = parseModule(LastFunctionBlockBit > NextUnreadBit 5662 ? LastFunctionBlockBit 5663 : NextUnreadBit)) 5664 return Err; 5665 5666 // Check that all block address forward references got resolved (as we 5667 // promised above). 5668 if (!BasicBlockFwdRefs.empty()) 5669 return error("Never resolved function from blockaddress"); 5670 5671 // Upgrade any intrinsic calls that slipped through (should not happen!) and 5672 // delete the old functions to clean up. We can't do this unless the entire 5673 // module is materialized because there could always be another function body 5674 // with calls to the old function. 5675 for (auto &I : UpgradedIntrinsics) { 5676 for (auto *U : I.first->users()) { 5677 if (CallInst *CI = dyn_cast<CallInst>(U)) 5678 UpgradeIntrinsicCall(CI, I.second); 5679 } 5680 if (!I.first->use_empty()) 5681 I.first->replaceAllUsesWith(I.second); 5682 I.first->eraseFromParent(); 5683 } 5684 UpgradedIntrinsics.clear(); 5685 // Do the same for remangled intrinsics 5686 for (auto &I : RemangledIntrinsics) { 5687 I.first->replaceAllUsesWith(I.second); 5688 I.first->eraseFromParent(); 5689 } 5690 RemangledIntrinsics.clear(); 5691 5692 UpgradeDebugInfo(*TheModule); 5693 5694 UpgradeModuleFlags(*TheModule); 5695 5696 UpgradeARCRuntime(*TheModule); 5697 5698 return Error::success(); 5699 } 5700 5701 std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const { 5702 return IdentifiedStructTypes; 5703 } 5704 5705 ModuleSummaryIndexBitcodeReader::ModuleSummaryIndexBitcodeReader( 5706 BitstreamCursor Cursor, StringRef Strtab, ModuleSummaryIndex &TheIndex, 5707 StringRef ModulePath, unsigned ModuleId) 5708 : BitcodeReaderBase(std::move(Cursor), Strtab), TheIndex(TheIndex), 5709 ModulePath(ModulePath), ModuleId(ModuleId) {} 5710 5711 void ModuleSummaryIndexBitcodeReader::addThisModule() { 5712 TheIndex.addModule(ModulePath, ModuleId); 5713 } 5714 5715 ModuleSummaryIndex::ModuleInfo * 5716 ModuleSummaryIndexBitcodeReader::getThisModule() { 5717 return TheIndex.getModule(ModulePath); 5718 } 5719 5720 std::pair<ValueInfo, GlobalValue::GUID> 5721 ModuleSummaryIndexBitcodeReader::getValueInfoFromValueId(unsigned ValueId) { 5722 auto VGI = ValueIdToValueInfoMap[ValueId]; 5723 assert(VGI.first); 5724 return VGI; 5725 } 5726 5727 void ModuleSummaryIndexBitcodeReader::setValueGUID( 5728 uint64_t ValueID, StringRef ValueName, GlobalValue::LinkageTypes Linkage, 5729 StringRef SourceFileName) { 5730 std::string GlobalId = 5731 GlobalValue::getGlobalIdentifier(ValueName, Linkage, SourceFileName); 5732 auto ValueGUID = GlobalValue::getGUID(GlobalId); 5733 auto OriginalNameID = ValueGUID; 5734 if (GlobalValue::isLocalLinkage(Linkage)) 5735 OriginalNameID = GlobalValue::getGUID(ValueName); 5736 if (PrintSummaryGUIDs) 5737 dbgs() << "GUID " << ValueGUID << "(" << OriginalNameID << ") is " 5738 << ValueName << "\n"; 5739 5740 // UseStrtab is false for legacy summary formats and value names are 5741 // created on stack. In that case we save the name in a string saver in 5742 // the index so that the value name can be recorded. 5743 ValueIdToValueInfoMap[ValueID] = std::make_pair( 5744 TheIndex.getOrInsertValueInfo( 5745 ValueGUID, 5746 UseStrtab ? ValueName : TheIndex.saveString(ValueName)), 5747 OriginalNameID); 5748 } 5749 5750 // Specialized value symbol table parser used when reading module index 5751 // blocks where we don't actually create global values. The parsed information 5752 // is saved in the bitcode reader for use when later parsing summaries. 5753 Error ModuleSummaryIndexBitcodeReader::parseValueSymbolTable( 5754 uint64_t Offset, 5755 DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap) { 5756 // With a strtab the VST is not required to parse the summary. 5757 if (UseStrtab) 5758 return Error::success(); 5759 5760 assert(Offset > 0 && "Expected non-zero VST offset"); 5761 Expected<uint64_t> MaybeCurrentBit = jumpToValueSymbolTable(Offset, Stream); 5762 if (!MaybeCurrentBit) 5763 return MaybeCurrentBit.takeError(); 5764 uint64_t CurrentBit = MaybeCurrentBit.get(); 5765 5766 if (Error Err = Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID)) 5767 return Err; 5768 5769 SmallVector<uint64_t, 64> Record; 5770 5771 // Read all the records for this value table. 5772 SmallString<128> ValueName; 5773 5774 while (true) { 5775 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); 5776 if (!MaybeEntry) 5777 return MaybeEntry.takeError(); 5778 BitstreamEntry Entry = MaybeEntry.get(); 5779 5780 switch (Entry.Kind) { 5781 case BitstreamEntry::SubBlock: // Handled for us already. 5782 case BitstreamEntry::Error: 5783 return error("Malformed block"); 5784 case BitstreamEntry::EndBlock: 5785 // Done parsing VST, jump back to wherever we came from. 5786 if (Error JumpFailed = Stream.JumpToBit(CurrentBit)) 5787 return JumpFailed; 5788 return Error::success(); 5789 case BitstreamEntry::Record: 5790 // The interesting case. 5791 break; 5792 } 5793 5794 // Read a record. 5795 Record.clear(); 5796 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record); 5797 if (!MaybeRecord) 5798 return MaybeRecord.takeError(); 5799 switch (MaybeRecord.get()) { 5800 default: // Default behavior: ignore (e.g. VST_CODE_BBENTRY records). 5801 break; 5802 case bitc::VST_CODE_ENTRY: { // VST_CODE_ENTRY: [valueid, namechar x N] 5803 if (convertToString(Record, 1, ValueName)) 5804 return error("Invalid record"); 5805 unsigned ValueID = Record[0]; 5806 assert(!SourceFileName.empty()); 5807 auto VLI = ValueIdToLinkageMap.find(ValueID); 5808 assert(VLI != ValueIdToLinkageMap.end() && 5809 "No linkage found for VST entry?"); 5810 auto Linkage = VLI->second; 5811 setValueGUID(ValueID, ValueName, Linkage, SourceFileName); 5812 ValueName.clear(); 5813 break; 5814 } 5815 case bitc::VST_CODE_FNENTRY: { 5816 // VST_CODE_FNENTRY: [valueid, offset, namechar x N] 5817 if (convertToString(Record, 2, ValueName)) 5818 return error("Invalid record"); 5819 unsigned ValueID = Record[0]; 5820 assert(!SourceFileName.empty()); 5821 auto VLI = ValueIdToLinkageMap.find(ValueID); 5822 assert(VLI != ValueIdToLinkageMap.end() && 5823 "No linkage found for VST entry?"); 5824 auto Linkage = VLI->second; 5825 setValueGUID(ValueID, ValueName, Linkage, SourceFileName); 5826 ValueName.clear(); 5827 break; 5828 } 5829 case bitc::VST_CODE_COMBINED_ENTRY: { 5830 // VST_CODE_COMBINED_ENTRY: [valueid, refguid] 5831 unsigned ValueID = Record[0]; 5832 GlobalValue::GUID RefGUID = Record[1]; 5833 // The "original name", which is the second value of the pair will be 5834 // overriden later by a FS_COMBINED_ORIGINAL_NAME in the combined index. 5835 ValueIdToValueInfoMap[ValueID] = 5836 std::make_pair(TheIndex.getOrInsertValueInfo(RefGUID), RefGUID); 5837 break; 5838 } 5839 } 5840 } 5841 } 5842 5843 // Parse just the blocks needed for building the index out of the module. 5844 // At the end of this routine the module Index is populated with a map 5845 // from global value id to GlobalValueSummary objects. 5846 Error ModuleSummaryIndexBitcodeReader::parseModule() { 5847 if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID)) 5848 return Err; 5849 5850 SmallVector<uint64_t, 64> Record; 5851 DenseMap<unsigned, GlobalValue::LinkageTypes> ValueIdToLinkageMap; 5852 unsigned ValueId = 0; 5853 5854 // Read the index for this module. 5855 while (true) { 5856 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance(); 5857 if (!MaybeEntry) 5858 return MaybeEntry.takeError(); 5859 llvm::BitstreamEntry Entry = MaybeEntry.get(); 5860 5861 switch (Entry.Kind) { 5862 case BitstreamEntry::Error: 5863 return error("Malformed block"); 5864 case BitstreamEntry::EndBlock: 5865 return Error::success(); 5866 5867 case BitstreamEntry::SubBlock: 5868 switch (Entry.ID) { 5869 default: // Skip unknown content. 5870 if (Error Err = Stream.SkipBlock()) 5871 return Err; 5872 break; 5873 case bitc::BLOCKINFO_BLOCK_ID: 5874 // Need to parse these to get abbrev ids (e.g. for VST) 5875 if (readBlockInfo()) 5876 return error("Malformed block"); 5877 break; 5878 case bitc::VALUE_SYMTAB_BLOCK_ID: 5879 // Should have been parsed earlier via VSTOffset, unless there 5880 // is no summary section. 5881 assert(((SeenValueSymbolTable && VSTOffset > 0) || 5882 !SeenGlobalValSummary) && 5883 "Expected early VST parse via VSTOffset record"); 5884 if (Error Err = Stream.SkipBlock()) 5885 return Err; 5886 break; 5887 case bitc::GLOBALVAL_SUMMARY_BLOCK_ID: 5888 case bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID: 5889 // Add the module if it is a per-module index (has a source file name). 5890 if (!SourceFileName.empty()) 5891 addThisModule(); 5892 assert(!SeenValueSymbolTable && 5893 "Already read VST when parsing summary block?"); 5894 // We might not have a VST if there were no values in the 5895 // summary. An empty summary block generated when we are 5896 // performing ThinLTO compiles so we don't later invoke 5897 // the regular LTO process on them. 5898 if (VSTOffset > 0) { 5899 if (Error Err = parseValueSymbolTable(VSTOffset, ValueIdToLinkageMap)) 5900 return Err; 5901 SeenValueSymbolTable = true; 5902 } 5903 SeenGlobalValSummary = true; 5904 if (Error Err = parseEntireSummary(Entry.ID)) 5905 return Err; 5906 break; 5907 case bitc::MODULE_STRTAB_BLOCK_ID: 5908 if (Error Err = parseModuleStringTable()) 5909 return Err; 5910 break; 5911 } 5912 continue; 5913 5914 case BitstreamEntry::Record: { 5915 Record.clear(); 5916 Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record); 5917 if (!MaybeBitCode) 5918 return MaybeBitCode.takeError(); 5919 switch (MaybeBitCode.get()) { 5920 default: 5921 break; // Default behavior, ignore unknown content. 5922 case bitc::MODULE_CODE_VERSION: { 5923 if (Error Err = parseVersionRecord(Record).takeError()) 5924 return Err; 5925 break; 5926 } 5927 /// MODULE_CODE_SOURCE_FILENAME: [namechar x N] 5928 case bitc::MODULE_CODE_SOURCE_FILENAME: { 5929 SmallString<128> ValueName; 5930 if (convertToString(Record, 0, ValueName)) 5931 return error("Invalid record"); 5932 SourceFileName = ValueName.c_str(); 5933 break; 5934 } 5935 /// MODULE_CODE_HASH: [5*i32] 5936 case bitc::MODULE_CODE_HASH: { 5937 if (Record.size() != 5) 5938 return error("Invalid hash length " + Twine(Record.size()).str()); 5939 auto &Hash = getThisModule()->second.second; 5940 int Pos = 0; 5941 for (auto &Val : Record) { 5942 assert(!(Val >> 32) && "Unexpected high bits set"); 5943 Hash[Pos++] = Val; 5944 } 5945 break; 5946 } 5947 /// MODULE_CODE_VSTOFFSET: [offset] 5948 case bitc::MODULE_CODE_VSTOFFSET: 5949 if (Record.empty()) 5950 return error("Invalid record"); 5951 // Note that we subtract 1 here because the offset is relative to one 5952 // word before the start of the identification or module block, which 5953 // was historically always the start of the regular bitcode header. 5954 VSTOffset = Record[0] - 1; 5955 break; 5956 // v1 GLOBALVAR: [pointer type, isconst, initid, linkage, ...] 5957 // v1 FUNCTION: [type, callingconv, isproto, linkage, ...] 5958 // v1 ALIAS: [alias type, addrspace, aliasee val#, linkage, ...] 5959 // v2: [strtab offset, strtab size, v1] 5960 case bitc::MODULE_CODE_GLOBALVAR: 5961 case bitc::MODULE_CODE_FUNCTION: 5962 case bitc::MODULE_CODE_ALIAS: { 5963 StringRef Name; 5964 ArrayRef<uint64_t> GVRecord; 5965 std::tie(Name, GVRecord) = readNameFromStrtab(Record); 5966 if (GVRecord.size() <= 3) 5967 return error("Invalid record"); 5968 uint64_t RawLinkage = GVRecord[3]; 5969 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage); 5970 if (!UseStrtab) { 5971 ValueIdToLinkageMap[ValueId++] = Linkage; 5972 break; 5973 } 5974 5975 setValueGUID(ValueId++, Name, Linkage, SourceFileName); 5976 break; 5977 } 5978 } 5979 } 5980 continue; 5981 } 5982 } 5983 } 5984 5985 std::vector<ValueInfo> 5986 ModuleSummaryIndexBitcodeReader::makeRefList(ArrayRef<uint64_t> Record) { 5987 std::vector<ValueInfo> Ret; 5988 Ret.reserve(Record.size()); 5989 for (uint64_t RefValueId : Record) 5990 Ret.push_back(getValueInfoFromValueId(RefValueId).first); 5991 return Ret; 5992 } 5993 5994 std::vector<FunctionSummary::EdgeTy> 5995 ModuleSummaryIndexBitcodeReader::makeCallList(ArrayRef<uint64_t> Record, 5996 bool IsOldProfileFormat, 5997 bool HasProfile, bool HasRelBF) { 5998 std::vector<FunctionSummary::EdgeTy> Ret; 5999 Ret.reserve(Record.size()); 6000 for (unsigned I = 0, E = Record.size(); I != E; ++I) { 6001 CalleeInfo::HotnessType Hotness = CalleeInfo::HotnessType::Unknown; 6002 uint64_t RelBF = 0; 6003 ValueInfo Callee = getValueInfoFromValueId(Record[I]).first; 6004 if (IsOldProfileFormat) { 6005 I += 1; // Skip old callsitecount field 6006 if (HasProfile) 6007 I += 1; // Skip old profilecount field 6008 } else if (HasProfile) 6009 Hotness = static_cast<CalleeInfo::HotnessType>(Record[++I]); 6010 else if (HasRelBF) 6011 RelBF = Record[++I]; 6012 Ret.push_back(FunctionSummary::EdgeTy{Callee, CalleeInfo(Hotness, RelBF)}); 6013 } 6014 return Ret; 6015 } 6016 6017 static void 6018 parseWholeProgramDevirtResolutionByArg(ArrayRef<uint64_t> Record, size_t &Slot, 6019 WholeProgramDevirtResolution &Wpd) { 6020 uint64_t ArgNum = Record[Slot++]; 6021 WholeProgramDevirtResolution::ByArg &B = 6022 Wpd.ResByArg[{Record.begin() + Slot, Record.begin() + Slot + ArgNum}]; 6023 Slot += ArgNum; 6024 6025 B.TheKind = 6026 static_cast<WholeProgramDevirtResolution::ByArg::Kind>(Record[Slot++]); 6027 B.Info = Record[Slot++]; 6028 B.Byte = Record[Slot++]; 6029 B.Bit = Record[Slot++]; 6030 } 6031 6032 static void parseWholeProgramDevirtResolution(ArrayRef<uint64_t> Record, 6033 StringRef Strtab, size_t &Slot, 6034 TypeIdSummary &TypeId) { 6035 uint64_t Id = Record[Slot++]; 6036 WholeProgramDevirtResolution &Wpd = TypeId.WPDRes[Id]; 6037 6038 Wpd.TheKind = static_cast<WholeProgramDevirtResolution::Kind>(Record[Slot++]); 6039 Wpd.SingleImplName = {Strtab.data() + Record[Slot], 6040 static_cast<size_t>(Record[Slot + 1])}; 6041 Slot += 2; 6042 6043 uint64_t ResByArgNum = Record[Slot++]; 6044 for (uint64_t I = 0; I != ResByArgNum; ++I) 6045 parseWholeProgramDevirtResolutionByArg(Record, Slot, Wpd); 6046 } 6047 6048 static void parseTypeIdSummaryRecord(ArrayRef<uint64_t> Record, 6049 StringRef Strtab, 6050 ModuleSummaryIndex &TheIndex) { 6051 size_t Slot = 0; 6052 TypeIdSummary &TypeId = TheIndex.getOrInsertTypeIdSummary( 6053 {Strtab.data() + Record[Slot], static_cast<size_t>(Record[Slot + 1])}); 6054 Slot += 2; 6055 6056 TypeId.TTRes.TheKind = static_cast<TypeTestResolution::Kind>(Record[Slot++]); 6057 TypeId.TTRes.SizeM1BitWidth = Record[Slot++]; 6058 TypeId.TTRes.AlignLog2 = Record[Slot++]; 6059 TypeId.TTRes.SizeM1 = Record[Slot++]; 6060 TypeId.TTRes.BitMask = Record[Slot++]; 6061 TypeId.TTRes.InlineBits = Record[Slot++]; 6062 6063 while (Slot < Record.size()) 6064 parseWholeProgramDevirtResolution(Record, Strtab, Slot, TypeId); 6065 } 6066 6067 std::vector<FunctionSummary::ParamAccess> 6068 ModuleSummaryIndexBitcodeReader::parseParamAccesses(ArrayRef<uint64_t> Record) { 6069 auto ReadRange = [&]() { 6070 APInt Lower(FunctionSummary::ParamAccess::RangeWidth, 6071 BitcodeReader::decodeSignRotatedValue(Record.front())); 6072 Record = Record.drop_front(); 6073 APInt Upper(FunctionSummary::ParamAccess::RangeWidth, 6074 BitcodeReader::decodeSignRotatedValue(Record.front())); 6075 Record = Record.drop_front(); 6076 ConstantRange Range{Lower, Upper}; 6077 assert(!Range.isFullSet()); 6078 assert(!Range.isUpperSignWrapped()); 6079 return Range; 6080 }; 6081 6082 std::vector<FunctionSummary::ParamAccess> PendingParamAccesses; 6083 while (!Record.empty()) { 6084 PendingParamAccesses.emplace_back(); 6085 FunctionSummary::ParamAccess &ParamAccess = PendingParamAccesses.back(); 6086 ParamAccess.ParamNo = Record.front(); 6087 Record = Record.drop_front(); 6088 ParamAccess.Use = ReadRange(); 6089 ParamAccess.Calls.resize(Record.front()); 6090 Record = Record.drop_front(); 6091 for (auto &Call : ParamAccess.Calls) { 6092 Call.ParamNo = Record.front(); 6093 Record = Record.drop_front(); 6094 Call.Callee = getValueInfoFromValueId(Record.front()).first; 6095 Record = Record.drop_front(); 6096 Call.Offsets = ReadRange(); 6097 } 6098 } 6099 return PendingParamAccesses; 6100 } 6101 6102 void ModuleSummaryIndexBitcodeReader::parseTypeIdCompatibleVtableInfo( 6103 ArrayRef<uint64_t> Record, size_t &Slot, 6104 TypeIdCompatibleVtableInfo &TypeId) { 6105 uint64_t Offset = Record[Slot++]; 6106 ValueInfo Callee = getValueInfoFromValueId(Record[Slot++]).first; 6107 TypeId.push_back({Offset, Callee}); 6108 } 6109 6110 void ModuleSummaryIndexBitcodeReader::parseTypeIdCompatibleVtableSummaryRecord( 6111 ArrayRef<uint64_t> Record) { 6112 size_t Slot = 0; 6113 TypeIdCompatibleVtableInfo &TypeId = 6114 TheIndex.getOrInsertTypeIdCompatibleVtableSummary( 6115 {Strtab.data() + Record[Slot], 6116 static_cast<size_t>(Record[Slot + 1])}); 6117 Slot += 2; 6118 6119 while (Slot < Record.size()) 6120 parseTypeIdCompatibleVtableInfo(Record, Slot, TypeId); 6121 } 6122 6123 static void setSpecialRefs(std::vector<ValueInfo> &Refs, unsigned ROCnt, 6124 unsigned WOCnt) { 6125 // Readonly and writeonly refs are in the end of the refs list. 6126 assert(ROCnt + WOCnt <= Refs.size()); 6127 unsigned FirstWORef = Refs.size() - WOCnt; 6128 unsigned RefNo = FirstWORef - ROCnt; 6129 for (; RefNo < FirstWORef; ++RefNo) 6130 Refs[RefNo].setReadOnly(); 6131 for (; RefNo < Refs.size(); ++RefNo) 6132 Refs[RefNo].setWriteOnly(); 6133 } 6134 6135 // Eagerly parse the entire summary block. This populates the GlobalValueSummary 6136 // objects in the index. 6137 Error ModuleSummaryIndexBitcodeReader::parseEntireSummary(unsigned ID) { 6138 if (Error Err = Stream.EnterSubBlock(ID)) 6139 return Err; 6140 SmallVector<uint64_t, 64> Record; 6141 6142 // Parse version 6143 { 6144 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); 6145 if (!MaybeEntry) 6146 return MaybeEntry.takeError(); 6147 BitstreamEntry Entry = MaybeEntry.get(); 6148 6149 if (Entry.Kind != BitstreamEntry::Record) 6150 return error("Invalid Summary Block: record for version expected"); 6151 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record); 6152 if (!MaybeRecord) 6153 return MaybeRecord.takeError(); 6154 if (MaybeRecord.get() != bitc::FS_VERSION) 6155 return error("Invalid Summary Block: version expected"); 6156 } 6157 const uint64_t Version = Record[0]; 6158 const bool IsOldProfileFormat = Version == 1; 6159 if (Version < 1 || Version > ModuleSummaryIndex::BitcodeSummaryVersion) 6160 return error("Invalid summary version " + Twine(Version) + 6161 ". Version should be in the range [1-" + 6162 Twine(ModuleSummaryIndex::BitcodeSummaryVersion) + 6163 "]."); 6164 Record.clear(); 6165 6166 // Keep around the last seen summary to be used when we see an optional 6167 // "OriginalName" attachement. 6168 GlobalValueSummary *LastSeenSummary = nullptr; 6169 GlobalValue::GUID LastSeenGUID = 0; 6170 6171 // We can expect to see any number of type ID information records before 6172 // each function summary records; these variables store the information 6173 // collected so far so that it can be used to create the summary object. 6174 std::vector<GlobalValue::GUID> PendingTypeTests; 6175 std::vector<FunctionSummary::VFuncId> PendingTypeTestAssumeVCalls, 6176 PendingTypeCheckedLoadVCalls; 6177 std::vector<FunctionSummary::ConstVCall> PendingTypeTestAssumeConstVCalls, 6178 PendingTypeCheckedLoadConstVCalls; 6179 std::vector<FunctionSummary::ParamAccess> PendingParamAccesses; 6180 6181 while (true) { 6182 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); 6183 if (!MaybeEntry) 6184 return MaybeEntry.takeError(); 6185 BitstreamEntry Entry = MaybeEntry.get(); 6186 6187 switch (Entry.Kind) { 6188 case BitstreamEntry::SubBlock: // Handled for us already. 6189 case BitstreamEntry::Error: 6190 return error("Malformed block"); 6191 case BitstreamEntry::EndBlock: 6192 return Error::success(); 6193 case BitstreamEntry::Record: 6194 // The interesting case. 6195 break; 6196 } 6197 6198 // Read a record. The record format depends on whether this 6199 // is a per-module index or a combined index file. In the per-module 6200 // case the records contain the associated value's ID for correlation 6201 // with VST entries. In the combined index the correlation is done 6202 // via the bitcode offset of the summary records (which were saved 6203 // in the combined index VST entries). The records also contain 6204 // information used for ThinLTO renaming and importing. 6205 Record.clear(); 6206 Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record); 6207 if (!MaybeBitCode) 6208 return MaybeBitCode.takeError(); 6209 switch (unsigned BitCode = MaybeBitCode.get()) { 6210 default: // Default behavior: ignore. 6211 break; 6212 case bitc::FS_FLAGS: { // [flags] 6213 TheIndex.setFlags(Record[0]); 6214 break; 6215 } 6216 case bitc::FS_VALUE_GUID: { // [valueid, refguid] 6217 uint64_t ValueID = Record[0]; 6218 GlobalValue::GUID RefGUID = Record[1]; 6219 ValueIdToValueInfoMap[ValueID] = 6220 std::make_pair(TheIndex.getOrInsertValueInfo(RefGUID), RefGUID); 6221 break; 6222 } 6223 // FS_PERMODULE: [valueid, flags, instcount, fflags, numrefs, 6224 // numrefs x valueid, n x (valueid)] 6225 // FS_PERMODULE_PROFILE: [valueid, flags, instcount, fflags, numrefs, 6226 // numrefs x valueid, 6227 // n x (valueid, hotness)] 6228 // FS_PERMODULE_RELBF: [valueid, flags, instcount, fflags, numrefs, 6229 // numrefs x valueid, 6230 // n x (valueid, relblockfreq)] 6231 case bitc::FS_PERMODULE: 6232 case bitc::FS_PERMODULE_RELBF: 6233 case bitc::FS_PERMODULE_PROFILE: { 6234 unsigned ValueID = Record[0]; 6235 uint64_t RawFlags = Record[1]; 6236 unsigned InstCount = Record[2]; 6237 uint64_t RawFunFlags = 0; 6238 unsigned NumRefs = Record[3]; 6239 unsigned NumRORefs = 0, NumWORefs = 0; 6240 int RefListStartIndex = 4; 6241 if (Version >= 4) { 6242 RawFunFlags = Record[3]; 6243 NumRefs = Record[4]; 6244 RefListStartIndex = 5; 6245 if (Version >= 5) { 6246 NumRORefs = Record[5]; 6247 RefListStartIndex = 6; 6248 if (Version >= 7) { 6249 NumWORefs = Record[6]; 6250 RefListStartIndex = 7; 6251 } 6252 } 6253 } 6254 6255 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version); 6256 // The module path string ref set in the summary must be owned by the 6257 // index's module string table. Since we don't have a module path 6258 // string table section in the per-module index, we create a single 6259 // module path string table entry with an empty (0) ID to take 6260 // ownership. 6261 int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs; 6262 assert(Record.size() >= RefListStartIndex + NumRefs && 6263 "Record size inconsistent with number of references"); 6264 std::vector<ValueInfo> Refs = makeRefList( 6265 ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs)); 6266 bool HasProfile = (BitCode == bitc::FS_PERMODULE_PROFILE); 6267 bool HasRelBF = (BitCode == bitc::FS_PERMODULE_RELBF); 6268 std::vector<FunctionSummary::EdgeTy> Calls = makeCallList( 6269 ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex), 6270 IsOldProfileFormat, HasProfile, HasRelBF); 6271 setSpecialRefs(Refs, NumRORefs, NumWORefs); 6272 auto FS = std::make_unique<FunctionSummary>( 6273 Flags, InstCount, getDecodedFFlags(RawFunFlags), /*EntryCount=*/0, 6274 std::move(Refs), std::move(Calls), std::move(PendingTypeTests), 6275 std::move(PendingTypeTestAssumeVCalls), 6276 std::move(PendingTypeCheckedLoadVCalls), 6277 std::move(PendingTypeTestAssumeConstVCalls), 6278 std::move(PendingTypeCheckedLoadConstVCalls), 6279 std::move(PendingParamAccesses)); 6280 auto VIAndOriginalGUID = getValueInfoFromValueId(ValueID); 6281 FS->setModulePath(getThisModule()->first()); 6282 FS->setOriginalName(VIAndOriginalGUID.second); 6283 TheIndex.addGlobalValueSummary(VIAndOriginalGUID.first, std::move(FS)); 6284 break; 6285 } 6286 // FS_ALIAS: [valueid, flags, valueid] 6287 // Aliases must be emitted (and parsed) after all FS_PERMODULE entries, as 6288 // they expect all aliasee summaries to be available. 6289 case bitc::FS_ALIAS: { 6290 unsigned ValueID = Record[0]; 6291 uint64_t RawFlags = Record[1]; 6292 unsigned AliaseeID = Record[2]; 6293 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version); 6294 auto AS = std::make_unique<AliasSummary>(Flags); 6295 // The module path string ref set in the summary must be owned by the 6296 // index's module string table. Since we don't have a module path 6297 // string table section in the per-module index, we create a single 6298 // module path string table entry with an empty (0) ID to take 6299 // ownership. 6300 AS->setModulePath(getThisModule()->first()); 6301 6302 auto AliaseeVI = getValueInfoFromValueId(AliaseeID).first; 6303 auto AliaseeInModule = TheIndex.findSummaryInModule(AliaseeVI, ModulePath); 6304 if (!AliaseeInModule) 6305 return error("Alias expects aliasee summary to be parsed"); 6306 AS->setAliasee(AliaseeVI, AliaseeInModule); 6307 6308 auto GUID = getValueInfoFromValueId(ValueID); 6309 AS->setOriginalName(GUID.second); 6310 TheIndex.addGlobalValueSummary(GUID.first, std::move(AS)); 6311 break; 6312 } 6313 // FS_PERMODULE_GLOBALVAR_INIT_REFS: [valueid, flags, varflags, n x valueid] 6314 case bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS: { 6315 unsigned ValueID = Record[0]; 6316 uint64_t RawFlags = Record[1]; 6317 unsigned RefArrayStart = 2; 6318 GlobalVarSummary::GVarFlags GVF(/* ReadOnly */ false, 6319 /* WriteOnly */ false, 6320 /* Constant */ false, 6321 GlobalObject::VCallVisibilityPublic); 6322 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version); 6323 if (Version >= 5) { 6324 GVF = getDecodedGVarFlags(Record[2]); 6325 RefArrayStart = 3; 6326 } 6327 std::vector<ValueInfo> Refs = 6328 makeRefList(ArrayRef<uint64_t>(Record).slice(RefArrayStart)); 6329 auto FS = 6330 std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs)); 6331 FS->setModulePath(getThisModule()->first()); 6332 auto GUID = getValueInfoFromValueId(ValueID); 6333 FS->setOriginalName(GUID.second); 6334 TheIndex.addGlobalValueSummary(GUID.first, std::move(FS)); 6335 break; 6336 } 6337 // FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS: [valueid, flags, varflags, 6338 // numrefs, numrefs x valueid, 6339 // n x (valueid, offset)] 6340 case bitc::FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS: { 6341 unsigned ValueID = Record[0]; 6342 uint64_t RawFlags = Record[1]; 6343 GlobalVarSummary::GVarFlags GVF = getDecodedGVarFlags(Record[2]); 6344 unsigned NumRefs = Record[3]; 6345 unsigned RefListStartIndex = 4; 6346 unsigned VTableListStartIndex = RefListStartIndex + NumRefs; 6347 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version); 6348 std::vector<ValueInfo> Refs = makeRefList( 6349 ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs)); 6350 VTableFuncList VTableFuncs; 6351 for (unsigned I = VTableListStartIndex, E = Record.size(); I != E; ++I) { 6352 ValueInfo Callee = getValueInfoFromValueId(Record[I]).first; 6353 uint64_t Offset = Record[++I]; 6354 VTableFuncs.push_back({Callee, Offset}); 6355 } 6356 auto VS = 6357 std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs)); 6358 VS->setModulePath(getThisModule()->first()); 6359 VS->setVTableFuncs(VTableFuncs); 6360 auto GUID = getValueInfoFromValueId(ValueID); 6361 VS->setOriginalName(GUID.second); 6362 TheIndex.addGlobalValueSummary(GUID.first, std::move(VS)); 6363 break; 6364 } 6365 // FS_COMBINED: [valueid, modid, flags, instcount, fflags, numrefs, 6366 // numrefs x valueid, n x (valueid)] 6367 // FS_COMBINED_PROFILE: [valueid, modid, flags, instcount, fflags, numrefs, 6368 // numrefs x valueid, n x (valueid, hotness)] 6369 case bitc::FS_COMBINED: 6370 case bitc::FS_COMBINED_PROFILE: { 6371 unsigned ValueID = Record[0]; 6372 uint64_t ModuleId = Record[1]; 6373 uint64_t RawFlags = Record[2]; 6374 unsigned InstCount = Record[3]; 6375 uint64_t RawFunFlags = 0; 6376 uint64_t EntryCount = 0; 6377 unsigned NumRefs = Record[4]; 6378 unsigned NumRORefs = 0, NumWORefs = 0; 6379 int RefListStartIndex = 5; 6380 6381 if (Version >= 4) { 6382 RawFunFlags = Record[4]; 6383 RefListStartIndex = 6; 6384 size_t NumRefsIndex = 5; 6385 if (Version >= 5) { 6386 unsigned NumRORefsOffset = 1; 6387 RefListStartIndex = 7; 6388 if (Version >= 6) { 6389 NumRefsIndex = 6; 6390 EntryCount = Record[5]; 6391 RefListStartIndex = 8; 6392 if (Version >= 7) { 6393 RefListStartIndex = 9; 6394 NumWORefs = Record[8]; 6395 NumRORefsOffset = 2; 6396 } 6397 } 6398 NumRORefs = Record[RefListStartIndex - NumRORefsOffset]; 6399 } 6400 NumRefs = Record[NumRefsIndex]; 6401 } 6402 6403 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version); 6404 int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs; 6405 assert(Record.size() >= RefListStartIndex + NumRefs && 6406 "Record size inconsistent with number of references"); 6407 std::vector<ValueInfo> Refs = makeRefList( 6408 ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs)); 6409 bool HasProfile = (BitCode == bitc::FS_COMBINED_PROFILE); 6410 std::vector<FunctionSummary::EdgeTy> Edges = makeCallList( 6411 ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex), 6412 IsOldProfileFormat, HasProfile, false); 6413 ValueInfo VI = getValueInfoFromValueId(ValueID).first; 6414 setSpecialRefs(Refs, NumRORefs, NumWORefs); 6415 auto FS = std::make_unique<FunctionSummary>( 6416 Flags, InstCount, getDecodedFFlags(RawFunFlags), EntryCount, 6417 std::move(Refs), std::move(Edges), std::move(PendingTypeTests), 6418 std::move(PendingTypeTestAssumeVCalls), 6419 std::move(PendingTypeCheckedLoadVCalls), 6420 std::move(PendingTypeTestAssumeConstVCalls), 6421 std::move(PendingTypeCheckedLoadConstVCalls), 6422 std::move(PendingParamAccesses)); 6423 LastSeenSummary = FS.get(); 6424 LastSeenGUID = VI.getGUID(); 6425 FS->setModulePath(ModuleIdMap[ModuleId]); 6426 TheIndex.addGlobalValueSummary(VI, std::move(FS)); 6427 break; 6428 } 6429 // FS_COMBINED_ALIAS: [valueid, modid, flags, valueid] 6430 // Aliases must be emitted (and parsed) after all FS_COMBINED entries, as 6431 // they expect all aliasee summaries to be available. 6432 case bitc::FS_COMBINED_ALIAS: { 6433 unsigned ValueID = Record[0]; 6434 uint64_t ModuleId = Record[1]; 6435 uint64_t RawFlags = Record[2]; 6436 unsigned AliaseeValueId = Record[3]; 6437 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version); 6438 auto AS = std::make_unique<AliasSummary>(Flags); 6439 LastSeenSummary = AS.get(); 6440 AS->setModulePath(ModuleIdMap[ModuleId]); 6441 6442 auto AliaseeVI = getValueInfoFromValueId(AliaseeValueId).first; 6443 auto AliaseeInModule = TheIndex.findSummaryInModule(AliaseeVI, AS->modulePath()); 6444 AS->setAliasee(AliaseeVI, AliaseeInModule); 6445 6446 ValueInfo VI = getValueInfoFromValueId(ValueID).first; 6447 LastSeenGUID = VI.getGUID(); 6448 TheIndex.addGlobalValueSummary(VI, std::move(AS)); 6449 break; 6450 } 6451 // FS_COMBINED_GLOBALVAR_INIT_REFS: [valueid, modid, flags, n x valueid] 6452 case bitc::FS_COMBINED_GLOBALVAR_INIT_REFS: { 6453 unsigned ValueID = Record[0]; 6454 uint64_t ModuleId = Record[1]; 6455 uint64_t RawFlags = Record[2]; 6456 unsigned RefArrayStart = 3; 6457 GlobalVarSummary::GVarFlags GVF(/* ReadOnly */ false, 6458 /* WriteOnly */ false, 6459 /* Constant */ false, 6460 GlobalObject::VCallVisibilityPublic); 6461 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version); 6462 if (Version >= 5) { 6463 GVF = getDecodedGVarFlags(Record[3]); 6464 RefArrayStart = 4; 6465 } 6466 std::vector<ValueInfo> Refs = 6467 makeRefList(ArrayRef<uint64_t>(Record).slice(RefArrayStart)); 6468 auto FS = 6469 std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs)); 6470 LastSeenSummary = FS.get(); 6471 FS->setModulePath(ModuleIdMap[ModuleId]); 6472 ValueInfo VI = getValueInfoFromValueId(ValueID).first; 6473 LastSeenGUID = VI.getGUID(); 6474 TheIndex.addGlobalValueSummary(VI, std::move(FS)); 6475 break; 6476 } 6477 // FS_COMBINED_ORIGINAL_NAME: [original_name] 6478 case bitc::FS_COMBINED_ORIGINAL_NAME: { 6479 uint64_t OriginalName = Record[0]; 6480 if (!LastSeenSummary) 6481 return error("Name attachment that does not follow a combined record"); 6482 LastSeenSummary->setOriginalName(OriginalName); 6483 TheIndex.addOriginalName(LastSeenGUID, OriginalName); 6484 // Reset the LastSeenSummary 6485 LastSeenSummary = nullptr; 6486 LastSeenGUID = 0; 6487 break; 6488 } 6489 case bitc::FS_TYPE_TESTS: 6490 assert(PendingTypeTests.empty()); 6491 llvm::append_range(PendingTypeTests, Record); 6492 break; 6493 6494 case bitc::FS_TYPE_TEST_ASSUME_VCALLS: 6495 assert(PendingTypeTestAssumeVCalls.empty()); 6496 for (unsigned I = 0; I != Record.size(); I += 2) 6497 PendingTypeTestAssumeVCalls.push_back({Record[I], Record[I+1]}); 6498 break; 6499 6500 case bitc::FS_TYPE_CHECKED_LOAD_VCALLS: 6501 assert(PendingTypeCheckedLoadVCalls.empty()); 6502 for (unsigned I = 0; I != Record.size(); I += 2) 6503 PendingTypeCheckedLoadVCalls.push_back({Record[I], Record[I+1]}); 6504 break; 6505 6506 case bitc::FS_TYPE_TEST_ASSUME_CONST_VCALL: 6507 PendingTypeTestAssumeConstVCalls.push_back( 6508 {{Record[0], Record[1]}, {Record.begin() + 2, Record.end()}}); 6509 break; 6510 6511 case bitc::FS_TYPE_CHECKED_LOAD_CONST_VCALL: 6512 PendingTypeCheckedLoadConstVCalls.push_back( 6513 {{Record[0], Record[1]}, {Record.begin() + 2, Record.end()}}); 6514 break; 6515 6516 case bitc::FS_CFI_FUNCTION_DEFS: { 6517 std::set<std::string> &CfiFunctionDefs = TheIndex.cfiFunctionDefs(); 6518 for (unsigned I = 0; I != Record.size(); I += 2) 6519 CfiFunctionDefs.insert( 6520 {Strtab.data() + Record[I], static_cast<size_t>(Record[I + 1])}); 6521 break; 6522 } 6523 6524 case bitc::FS_CFI_FUNCTION_DECLS: { 6525 std::set<std::string> &CfiFunctionDecls = TheIndex.cfiFunctionDecls(); 6526 for (unsigned I = 0; I != Record.size(); I += 2) 6527 CfiFunctionDecls.insert( 6528 {Strtab.data() + Record[I], static_cast<size_t>(Record[I + 1])}); 6529 break; 6530 } 6531 6532 case bitc::FS_TYPE_ID: 6533 parseTypeIdSummaryRecord(Record, Strtab, TheIndex); 6534 break; 6535 6536 case bitc::FS_TYPE_ID_METADATA: 6537 parseTypeIdCompatibleVtableSummaryRecord(Record); 6538 break; 6539 6540 case bitc::FS_BLOCK_COUNT: 6541 TheIndex.addBlockCount(Record[0]); 6542 break; 6543 6544 case bitc::FS_PARAM_ACCESS: { 6545 PendingParamAccesses = parseParamAccesses(Record); 6546 break; 6547 } 6548 } 6549 } 6550 llvm_unreachable("Exit infinite loop"); 6551 } 6552 6553 // Parse the module string table block into the Index. 6554 // This populates the ModulePathStringTable map in the index. 6555 Error ModuleSummaryIndexBitcodeReader::parseModuleStringTable() { 6556 if (Error Err = Stream.EnterSubBlock(bitc::MODULE_STRTAB_BLOCK_ID)) 6557 return Err; 6558 6559 SmallVector<uint64_t, 64> Record; 6560 6561 SmallString<128> ModulePath; 6562 ModuleSummaryIndex::ModuleInfo *LastSeenModule = nullptr; 6563 6564 while (true) { 6565 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); 6566 if (!MaybeEntry) 6567 return MaybeEntry.takeError(); 6568 BitstreamEntry Entry = MaybeEntry.get(); 6569 6570 switch (Entry.Kind) { 6571 case BitstreamEntry::SubBlock: // Handled for us already. 6572 case BitstreamEntry::Error: 6573 return error("Malformed block"); 6574 case BitstreamEntry::EndBlock: 6575 return Error::success(); 6576 case BitstreamEntry::Record: 6577 // The interesting case. 6578 break; 6579 } 6580 6581 Record.clear(); 6582 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record); 6583 if (!MaybeRecord) 6584 return MaybeRecord.takeError(); 6585 switch (MaybeRecord.get()) { 6586 default: // Default behavior: ignore. 6587 break; 6588 case bitc::MST_CODE_ENTRY: { 6589 // MST_ENTRY: [modid, namechar x N] 6590 uint64_t ModuleId = Record[0]; 6591 6592 if (convertToString(Record, 1, ModulePath)) 6593 return error("Invalid record"); 6594 6595 LastSeenModule = TheIndex.addModule(ModulePath, ModuleId); 6596 ModuleIdMap[ModuleId] = LastSeenModule->first(); 6597 6598 ModulePath.clear(); 6599 break; 6600 } 6601 /// MST_CODE_HASH: [5*i32] 6602 case bitc::MST_CODE_HASH: { 6603 if (Record.size() != 5) 6604 return error("Invalid hash length " + Twine(Record.size()).str()); 6605 if (!LastSeenModule) 6606 return error("Invalid hash that does not follow a module path"); 6607 int Pos = 0; 6608 for (auto &Val : Record) { 6609 assert(!(Val >> 32) && "Unexpected high bits set"); 6610 LastSeenModule->second.second[Pos++] = Val; 6611 } 6612 // Reset LastSeenModule to avoid overriding the hash unexpectedly. 6613 LastSeenModule = nullptr; 6614 break; 6615 } 6616 } 6617 } 6618 llvm_unreachable("Exit infinite loop"); 6619 } 6620 6621 namespace { 6622 6623 // FIXME: This class is only here to support the transition to llvm::Error. It 6624 // will be removed once this transition is complete. Clients should prefer to 6625 // deal with the Error value directly, rather than converting to error_code. 6626 class BitcodeErrorCategoryType : public std::error_category { 6627 const char *name() const noexcept override { 6628 return "llvm.bitcode"; 6629 } 6630 6631 std::string message(int IE) const override { 6632 BitcodeError E = static_cast<BitcodeError>(IE); 6633 switch (E) { 6634 case BitcodeError::CorruptedBitcode: 6635 return "Corrupted bitcode"; 6636 } 6637 llvm_unreachable("Unknown error type!"); 6638 } 6639 }; 6640 6641 } // end anonymous namespace 6642 6643 static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory; 6644 6645 const std::error_category &llvm::BitcodeErrorCategory() { 6646 return *ErrorCategory; 6647 } 6648 6649 static Expected<StringRef> readBlobInRecord(BitstreamCursor &Stream, 6650 unsigned Block, unsigned RecordID) { 6651 if (Error Err = Stream.EnterSubBlock(Block)) 6652 return std::move(Err); 6653 6654 StringRef Strtab; 6655 while (true) { 6656 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance(); 6657 if (!MaybeEntry) 6658 return MaybeEntry.takeError(); 6659 llvm::BitstreamEntry Entry = MaybeEntry.get(); 6660 6661 switch (Entry.Kind) { 6662 case BitstreamEntry::EndBlock: 6663 return Strtab; 6664 6665 case BitstreamEntry::Error: 6666 return error("Malformed block"); 6667 6668 case BitstreamEntry::SubBlock: 6669 if (Error Err = Stream.SkipBlock()) 6670 return std::move(Err); 6671 break; 6672 6673 case BitstreamEntry::Record: 6674 StringRef Blob; 6675 SmallVector<uint64_t, 1> Record; 6676 Expected<unsigned> MaybeRecord = 6677 Stream.readRecord(Entry.ID, Record, &Blob); 6678 if (!MaybeRecord) 6679 return MaybeRecord.takeError(); 6680 if (MaybeRecord.get() == RecordID) 6681 Strtab = Blob; 6682 break; 6683 } 6684 } 6685 } 6686 6687 //===----------------------------------------------------------------------===// 6688 // External interface 6689 //===----------------------------------------------------------------------===// 6690 6691 Expected<std::vector<BitcodeModule>> 6692 llvm::getBitcodeModuleList(MemoryBufferRef Buffer) { 6693 auto FOrErr = getBitcodeFileContents(Buffer); 6694 if (!FOrErr) 6695 return FOrErr.takeError(); 6696 return std::move(FOrErr->Mods); 6697 } 6698 6699 Expected<BitcodeFileContents> 6700 llvm::getBitcodeFileContents(MemoryBufferRef Buffer) { 6701 Expected<BitstreamCursor> StreamOrErr = initStream(Buffer); 6702 if (!StreamOrErr) 6703 return StreamOrErr.takeError(); 6704 BitstreamCursor &Stream = *StreamOrErr; 6705 6706 BitcodeFileContents F; 6707 while (true) { 6708 uint64_t BCBegin = Stream.getCurrentByteNo(); 6709 6710 // We may be consuming bitcode from a client that leaves garbage at the end 6711 // of the bitcode stream (e.g. Apple's ar tool). If we are close enough to 6712 // the end that there cannot possibly be another module, stop looking. 6713 if (BCBegin + 8 >= Stream.getBitcodeBytes().size()) 6714 return F; 6715 6716 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance(); 6717 if (!MaybeEntry) 6718 return MaybeEntry.takeError(); 6719 llvm::BitstreamEntry Entry = MaybeEntry.get(); 6720 6721 switch (Entry.Kind) { 6722 case BitstreamEntry::EndBlock: 6723 case BitstreamEntry::Error: 6724 return error("Malformed block"); 6725 6726 case BitstreamEntry::SubBlock: { 6727 uint64_t IdentificationBit = -1ull; 6728 if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) { 6729 IdentificationBit = Stream.GetCurrentBitNo() - BCBegin * 8; 6730 if (Error Err = Stream.SkipBlock()) 6731 return std::move(Err); 6732 6733 { 6734 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance(); 6735 if (!MaybeEntry) 6736 return MaybeEntry.takeError(); 6737 Entry = MaybeEntry.get(); 6738 } 6739 6740 if (Entry.Kind != BitstreamEntry::SubBlock || 6741 Entry.ID != bitc::MODULE_BLOCK_ID) 6742 return error("Malformed block"); 6743 } 6744 6745 if (Entry.ID == bitc::MODULE_BLOCK_ID) { 6746 uint64_t ModuleBit = Stream.GetCurrentBitNo() - BCBegin * 8; 6747 if (Error Err = Stream.SkipBlock()) 6748 return std::move(Err); 6749 6750 F.Mods.push_back({Stream.getBitcodeBytes().slice( 6751 BCBegin, Stream.getCurrentByteNo() - BCBegin), 6752 Buffer.getBufferIdentifier(), IdentificationBit, 6753 ModuleBit}); 6754 continue; 6755 } 6756 6757 if (Entry.ID == bitc::STRTAB_BLOCK_ID) { 6758 Expected<StringRef> Strtab = 6759 readBlobInRecord(Stream, bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB); 6760 if (!Strtab) 6761 return Strtab.takeError(); 6762 // This string table is used by every preceding bitcode module that does 6763 // not have its own string table. A bitcode file may have multiple 6764 // string tables if it was created by binary concatenation, for example 6765 // with "llvm-cat -b". 6766 for (auto I = F.Mods.rbegin(), E = F.Mods.rend(); I != E; ++I) { 6767 if (!I->Strtab.empty()) 6768 break; 6769 I->Strtab = *Strtab; 6770 } 6771 // Similarly, the string table is used by every preceding symbol table; 6772 // normally there will be just one unless the bitcode file was created 6773 // by binary concatenation. 6774 if (!F.Symtab.empty() && F.StrtabForSymtab.empty()) 6775 F.StrtabForSymtab = *Strtab; 6776 continue; 6777 } 6778 6779 if (Entry.ID == bitc::SYMTAB_BLOCK_ID) { 6780 Expected<StringRef> SymtabOrErr = 6781 readBlobInRecord(Stream, bitc::SYMTAB_BLOCK_ID, bitc::SYMTAB_BLOB); 6782 if (!SymtabOrErr) 6783 return SymtabOrErr.takeError(); 6784 6785 // We can expect the bitcode file to have multiple symbol tables if it 6786 // was created by binary concatenation. In that case we silently 6787 // ignore any subsequent symbol tables, which is fine because this is a 6788 // low level function. The client is expected to notice that the number 6789 // of modules in the symbol table does not match the number of modules 6790 // in the input file and regenerate the symbol table. 6791 if (F.Symtab.empty()) 6792 F.Symtab = *SymtabOrErr; 6793 continue; 6794 } 6795 6796 if (Error Err = Stream.SkipBlock()) 6797 return std::move(Err); 6798 continue; 6799 } 6800 case BitstreamEntry::Record: 6801 if (Expected<unsigned> StreamFailed = Stream.skipRecord(Entry.ID)) 6802 continue; 6803 else 6804 return StreamFailed.takeError(); 6805 } 6806 } 6807 } 6808 6809 /// Get a lazy one-at-time loading module from bitcode. 6810 /// 6811 /// This isn't always used in a lazy context. In particular, it's also used by 6812 /// \a parseModule(). If this is truly lazy, then we need to eagerly pull 6813 /// in forward-referenced functions from block address references. 6814 /// 6815 /// \param[in] MaterializeAll Set to \c true if we should materialize 6816 /// everything. 6817 Expected<std::unique_ptr<Module>> 6818 BitcodeModule::getModuleImpl(LLVMContext &Context, bool MaterializeAll, 6819 bool ShouldLazyLoadMetadata, bool IsImporting, 6820 DataLayoutCallbackTy DataLayoutCallback) { 6821 BitstreamCursor Stream(Buffer); 6822 6823 std::string ProducerIdentification; 6824 if (IdentificationBit != -1ull) { 6825 if (Error JumpFailed = Stream.JumpToBit(IdentificationBit)) 6826 return std::move(JumpFailed); 6827 Expected<std::string> ProducerIdentificationOrErr = 6828 readIdentificationBlock(Stream); 6829 if (!ProducerIdentificationOrErr) 6830 return ProducerIdentificationOrErr.takeError(); 6831 6832 ProducerIdentification = *ProducerIdentificationOrErr; 6833 } 6834 6835 if (Error JumpFailed = Stream.JumpToBit(ModuleBit)) 6836 return std::move(JumpFailed); 6837 auto *R = new BitcodeReader(std::move(Stream), Strtab, ProducerIdentification, 6838 Context); 6839 6840 std::unique_ptr<Module> M = 6841 std::make_unique<Module>(ModuleIdentifier, Context); 6842 M->setMaterializer(R); 6843 6844 // Delay parsing Metadata if ShouldLazyLoadMetadata is true. 6845 if (Error Err = R->parseBitcodeInto(M.get(), ShouldLazyLoadMetadata, 6846 IsImporting, DataLayoutCallback)) 6847 return std::move(Err); 6848 6849 if (MaterializeAll) { 6850 // Read in the entire module, and destroy the BitcodeReader. 6851 if (Error Err = M->materializeAll()) 6852 return std::move(Err); 6853 } else { 6854 // Resolve forward references from blockaddresses. 6855 if (Error Err = R->materializeForwardReferencedFunctions()) 6856 return std::move(Err); 6857 } 6858 return std::move(M); 6859 } 6860 6861 Expected<std::unique_ptr<Module>> 6862 BitcodeModule::getLazyModule(LLVMContext &Context, bool ShouldLazyLoadMetadata, 6863 bool IsImporting) { 6864 return getModuleImpl(Context, false, ShouldLazyLoadMetadata, IsImporting, 6865 [](StringRef) { return None; }); 6866 } 6867 6868 // Parse the specified bitcode buffer and merge the index into CombinedIndex. 6869 // We don't use ModuleIdentifier here because the client may need to control the 6870 // module path used in the combined summary (e.g. when reading summaries for 6871 // regular LTO modules). 6872 Error BitcodeModule::readSummary(ModuleSummaryIndex &CombinedIndex, 6873 StringRef ModulePath, uint64_t ModuleId) { 6874 BitstreamCursor Stream(Buffer); 6875 if (Error JumpFailed = Stream.JumpToBit(ModuleBit)) 6876 return JumpFailed; 6877 6878 ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, CombinedIndex, 6879 ModulePath, ModuleId); 6880 return R.parseModule(); 6881 } 6882 6883 // Parse the specified bitcode buffer, returning the function info index. 6884 Expected<std::unique_ptr<ModuleSummaryIndex>> BitcodeModule::getSummary() { 6885 BitstreamCursor Stream(Buffer); 6886 if (Error JumpFailed = Stream.JumpToBit(ModuleBit)) 6887 return std::move(JumpFailed); 6888 6889 auto Index = std::make_unique<ModuleSummaryIndex>(/*HaveGVs=*/false); 6890 ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, *Index, 6891 ModuleIdentifier, 0); 6892 6893 if (Error Err = R.parseModule()) 6894 return std::move(Err); 6895 6896 return std::move(Index); 6897 } 6898 6899 static Expected<bool> getEnableSplitLTOUnitFlag(BitstreamCursor &Stream, 6900 unsigned ID) { 6901 if (Error Err = Stream.EnterSubBlock(ID)) 6902 return std::move(Err); 6903 SmallVector<uint64_t, 64> Record; 6904 6905 while (true) { 6906 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); 6907 if (!MaybeEntry) 6908 return MaybeEntry.takeError(); 6909 BitstreamEntry Entry = MaybeEntry.get(); 6910 6911 switch (Entry.Kind) { 6912 case BitstreamEntry::SubBlock: // Handled for us already. 6913 case BitstreamEntry::Error: 6914 return error("Malformed block"); 6915 case BitstreamEntry::EndBlock: 6916 // If no flags record found, conservatively return true to mimic 6917 // behavior before this flag was added. 6918 return true; 6919 case BitstreamEntry::Record: 6920 // The interesting case. 6921 break; 6922 } 6923 6924 // Look for the FS_FLAGS record. 6925 Record.clear(); 6926 Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record); 6927 if (!MaybeBitCode) 6928 return MaybeBitCode.takeError(); 6929 switch (MaybeBitCode.get()) { 6930 default: // Default behavior: ignore. 6931 break; 6932 case bitc::FS_FLAGS: { // [flags] 6933 uint64_t Flags = Record[0]; 6934 // Scan flags. 6935 assert(Flags <= 0x7f && "Unexpected bits in flag"); 6936 6937 return Flags & 0x8; 6938 } 6939 } 6940 } 6941 llvm_unreachable("Exit infinite loop"); 6942 } 6943 6944 // Check if the given bitcode buffer contains a global value summary block. 6945 Expected<BitcodeLTOInfo> BitcodeModule::getLTOInfo() { 6946 BitstreamCursor Stream(Buffer); 6947 if (Error JumpFailed = Stream.JumpToBit(ModuleBit)) 6948 return std::move(JumpFailed); 6949 6950 if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID)) 6951 return std::move(Err); 6952 6953 while (true) { 6954 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance(); 6955 if (!MaybeEntry) 6956 return MaybeEntry.takeError(); 6957 llvm::BitstreamEntry Entry = MaybeEntry.get(); 6958 6959 switch (Entry.Kind) { 6960 case BitstreamEntry::Error: 6961 return error("Malformed block"); 6962 case BitstreamEntry::EndBlock: 6963 return BitcodeLTOInfo{/*IsThinLTO=*/false, /*HasSummary=*/false, 6964 /*EnableSplitLTOUnit=*/false}; 6965 6966 case BitstreamEntry::SubBlock: 6967 if (Entry.ID == bitc::GLOBALVAL_SUMMARY_BLOCK_ID) { 6968 Expected<bool> EnableSplitLTOUnit = 6969 getEnableSplitLTOUnitFlag(Stream, Entry.ID); 6970 if (!EnableSplitLTOUnit) 6971 return EnableSplitLTOUnit.takeError(); 6972 return BitcodeLTOInfo{/*IsThinLTO=*/true, /*HasSummary=*/true, 6973 *EnableSplitLTOUnit}; 6974 } 6975 6976 if (Entry.ID == bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID) { 6977 Expected<bool> EnableSplitLTOUnit = 6978 getEnableSplitLTOUnitFlag(Stream, Entry.ID); 6979 if (!EnableSplitLTOUnit) 6980 return EnableSplitLTOUnit.takeError(); 6981 return BitcodeLTOInfo{/*IsThinLTO=*/false, /*HasSummary=*/true, 6982 *EnableSplitLTOUnit}; 6983 } 6984 6985 // Ignore other sub-blocks. 6986 if (Error Err = Stream.SkipBlock()) 6987 return std::move(Err); 6988 continue; 6989 6990 case BitstreamEntry::Record: 6991 if (Expected<unsigned> StreamFailed = Stream.skipRecord(Entry.ID)) 6992 continue; 6993 else 6994 return StreamFailed.takeError(); 6995 } 6996 } 6997 } 6998 6999 static Expected<BitcodeModule> getSingleModule(MemoryBufferRef Buffer) { 7000 Expected<std::vector<BitcodeModule>> MsOrErr = getBitcodeModuleList(Buffer); 7001 if (!MsOrErr) 7002 return MsOrErr.takeError(); 7003 7004 if (MsOrErr->size() != 1) 7005 return error("Expected a single module"); 7006 7007 return (*MsOrErr)[0]; 7008 } 7009 7010 Expected<std::unique_ptr<Module>> 7011 llvm::getLazyBitcodeModule(MemoryBufferRef Buffer, LLVMContext &Context, 7012 bool ShouldLazyLoadMetadata, bool IsImporting) { 7013 Expected<BitcodeModule> BM = getSingleModule(Buffer); 7014 if (!BM) 7015 return BM.takeError(); 7016 7017 return BM->getLazyModule(Context, ShouldLazyLoadMetadata, IsImporting); 7018 } 7019 7020 Expected<std::unique_ptr<Module>> llvm::getOwningLazyBitcodeModule( 7021 std::unique_ptr<MemoryBuffer> &&Buffer, LLVMContext &Context, 7022 bool ShouldLazyLoadMetadata, bool IsImporting) { 7023 auto MOrErr = getLazyBitcodeModule(*Buffer, Context, ShouldLazyLoadMetadata, 7024 IsImporting); 7025 if (MOrErr) 7026 (*MOrErr)->setOwnedMemoryBuffer(std::move(Buffer)); 7027 return MOrErr; 7028 } 7029 7030 Expected<std::unique_ptr<Module>> 7031 BitcodeModule::parseModule(LLVMContext &Context, 7032 DataLayoutCallbackTy DataLayoutCallback) { 7033 return getModuleImpl(Context, true, false, false, DataLayoutCallback); 7034 // TODO: Restore the use-lists to the in-memory state when the bitcode was 7035 // written. We must defer until the Module has been fully materialized. 7036 } 7037 7038 Expected<std::unique_ptr<Module>> 7039 llvm::parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context, 7040 DataLayoutCallbackTy DataLayoutCallback) { 7041 Expected<BitcodeModule> BM = getSingleModule(Buffer); 7042 if (!BM) 7043 return BM.takeError(); 7044 7045 return BM->parseModule(Context, DataLayoutCallback); 7046 } 7047 7048 Expected<std::string> llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer) { 7049 Expected<BitstreamCursor> StreamOrErr = initStream(Buffer); 7050 if (!StreamOrErr) 7051 return StreamOrErr.takeError(); 7052 7053 return readTriple(*StreamOrErr); 7054 } 7055 7056 Expected<bool> llvm::isBitcodeContainingObjCCategory(MemoryBufferRef Buffer) { 7057 Expected<BitstreamCursor> StreamOrErr = initStream(Buffer); 7058 if (!StreamOrErr) 7059 return StreamOrErr.takeError(); 7060 7061 return hasObjCCategory(*StreamOrErr); 7062 } 7063 7064 Expected<std::string> llvm::getBitcodeProducerString(MemoryBufferRef Buffer) { 7065 Expected<BitstreamCursor> StreamOrErr = initStream(Buffer); 7066 if (!StreamOrErr) 7067 return StreamOrErr.takeError(); 7068 7069 return readIdentificationCode(*StreamOrErr); 7070 } 7071 7072 Error llvm::readModuleSummaryIndex(MemoryBufferRef Buffer, 7073 ModuleSummaryIndex &CombinedIndex, 7074 uint64_t ModuleId) { 7075 Expected<BitcodeModule> BM = getSingleModule(Buffer); 7076 if (!BM) 7077 return BM.takeError(); 7078 7079 return BM->readSummary(CombinedIndex, BM->getModuleIdentifier(), ModuleId); 7080 } 7081 7082 Expected<std::unique_ptr<ModuleSummaryIndex>> 7083 llvm::getModuleSummaryIndex(MemoryBufferRef Buffer) { 7084 Expected<BitcodeModule> BM = getSingleModule(Buffer); 7085 if (!BM) 7086 return BM.takeError(); 7087 7088 return BM->getSummary(); 7089 } 7090 7091 Expected<BitcodeLTOInfo> llvm::getBitcodeLTOInfo(MemoryBufferRef Buffer) { 7092 Expected<BitcodeModule> BM = getSingleModule(Buffer); 7093 if (!BM) 7094 return BM.takeError(); 7095 7096 return BM->getLTOInfo(); 7097 } 7098 7099 Expected<std::unique_ptr<ModuleSummaryIndex>> 7100 llvm::getModuleSummaryIndexForFile(StringRef Path, 7101 bool IgnoreEmptyThinLTOIndexFile) { 7102 ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr = 7103 MemoryBuffer::getFileOrSTDIN(Path); 7104 if (!FileOrErr) 7105 return errorCodeToError(FileOrErr.getError()); 7106 if (IgnoreEmptyThinLTOIndexFile && !(*FileOrErr)->getBufferSize()) 7107 return nullptr; 7108 return getModuleSummaryIndex(**FileOrErr); 7109 } 7110