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