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