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