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