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