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