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