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