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