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