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