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