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