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