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