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