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