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