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