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 bool isImplicitCode = Record.size() == 5 && Record[4]; 3520 3521 MDNode *Scope = nullptr, *IA = nullptr; 3522 if (ScopeID) { 3523 Scope = dyn_cast_or_null<MDNode>( 3524 MDLoader->getMetadataFwdRefOrLoad(ScopeID - 1)); 3525 if (!Scope) 3526 return error("Invalid record"); 3527 } 3528 if (IAID) { 3529 IA = dyn_cast_or_null<MDNode>( 3530 MDLoader->getMetadataFwdRefOrLoad(IAID - 1)); 3531 if (!IA) 3532 return error("Invalid record"); 3533 } 3534 LastLoc = DebugLoc::get(Line, Col, Scope, IA, isImplicitCode); 3535 I->setDebugLoc(LastLoc); 3536 I = nullptr; 3537 continue; 3538 } 3539 3540 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode] 3541 unsigned OpNum = 0; 3542 Value *LHS, *RHS; 3543 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) || 3544 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) || 3545 OpNum+1 > Record.size()) 3546 return error("Invalid record"); 3547 3548 int Opc = getDecodedBinaryOpcode(Record[OpNum++], LHS->getType()); 3549 if (Opc == -1) 3550 return error("Invalid record"); 3551 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS); 3552 InstructionList.push_back(I); 3553 if (OpNum < Record.size()) { 3554 if (Opc == Instruction::Add || 3555 Opc == Instruction::Sub || 3556 Opc == Instruction::Mul || 3557 Opc == Instruction::Shl) { 3558 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP)) 3559 cast<BinaryOperator>(I)->setHasNoSignedWrap(true); 3560 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP)) 3561 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true); 3562 } else if (Opc == Instruction::SDiv || 3563 Opc == Instruction::UDiv || 3564 Opc == Instruction::LShr || 3565 Opc == Instruction::AShr) { 3566 if (Record[OpNum] & (1 << bitc::PEO_EXACT)) 3567 cast<BinaryOperator>(I)->setIsExact(true); 3568 } else if (isa<FPMathOperator>(I)) { 3569 FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]); 3570 if (FMF.any()) 3571 I->setFastMathFlags(FMF); 3572 } 3573 3574 } 3575 break; 3576 } 3577 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc] 3578 unsigned OpNum = 0; 3579 Value *Op; 3580 if (getValueTypePair(Record, OpNum, NextValueNo, Op) || 3581 OpNum+2 != Record.size()) 3582 return error("Invalid record"); 3583 3584 Type *ResTy = getTypeByID(Record[OpNum]); 3585 int Opc = getDecodedCastOpcode(Record[OpNum + 1]); 3586 if (Opc == -1 || !ResTy) 3587 return error("Invalid record"); 3588 Instruction *Temp = nullptr; 3589 if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) { 3590 if (Temp) { 3591 InstructionList.push_back(Temp); 3592 CurBB->getInstList().push_back(Temp); 3593 } 3594 } else { 3595 auto CastOp = (Instruction::CastOps)Opc; 3596 if (!CastInst::castIsValid(CastOp, Op, ResTy)) 3597 return error("Invalid cast"); 3598 I = CastInst::Create(CastOp, Op, ResTy); 3599 } 3600 InstructionList.push_back(I); 3601 break; 3602 } 3603 case bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD: 3604 case bitc::FUNC_CODE_INST_GEP_OLD: 3605 case bitc::FUNC_CODE_INST_GEP: { // GEP: type, [n x operands] 3606 unsigned OpNum = 0; 3607 3608 Type *Ty; 3609 bool InBounds; 3610 3611 if (BitCode == bitc::FUNC_CODE_INST_GEP) { 3612 InBounds = Record[OpNum++]; 3613 Ty = getTypeByID(Record[OpNum++]); 3614 } else { 3615 InBounds = BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD; 3616 Ty = nullptr; 3617 } 3618 3619 Value *BasePtr; 3620 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr)) 3621 return error("Invalid record"); 3622 3623 if (!Ty) 3624 Ty = cast<PointerType>(BasePtr->getType()->getScalarType()) 3625 ->getElementType(); 3626 else if (Ty != 3627 cast<PointerType>(BasePtr->getType()->getScalarType()) 3628 ->getElementType()) 3629 return error( 3630 "Explicit gep type does not match pointee type of pointer operand"); 3631 3632 SmallVector<Value*, 16> GEPIdx; 3633 while (OpNum != Record.size()) { 3634 Value *Op; 3635 if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 3636 return error("Invalid record"); 3637 GEPIdx.push_back(Op); 3638 } 3639 3640 I = GetElementPtrInst::Create(Ty, BasePtr, GEPIdx); 3641 3642 InstructionList.push_back(I); 3643 if (InBounds) 3644 cast<GetElementPtrInst>(I)->setIsInBounds(true); 3645 break; 3646 } 3647 3648 case bitc::FUNC_CODE_INST_EXTRACTVAL: { 3649 // EXTRACTVAL: [opty, opval, n x indices] 3650 unsigned OpNum = 0; 3651 Value *Agg; 3652 if (getValueTypePair(Record, OpNum, NextValueNo, Agg)) 3653 return error("Invalid record"); 3654 3655 unsigned RecSize = Record.size(); 3656 if (OpNum == RecSize) 3657 return error("EXTRACTVAL: Invalid instruction with 0 indices"); 3658 3659 SmallVector<unsigned, 4> EXTRACTVALIdx; 3660 Type *CurTy = Agg->getType(); 3661 for (; OpNum != RecSize; ++OpNum) { 3662 bool IsArray = CurTy->isArrayTy(); 3663 bool IsStruct = CurTy->isStructTy(); 3664 uint64_t Index = Record[OpNum]; 3665 3666 if (!IsStruct && !IsArray) 3667 return error("EXTRACTVAL: Invalid type"); 3668 if ((unsigned)Index != Index) 3669 return error("Invalid value"); 3670 if (IsStruct && Index >= CurTy->subtypes().size()) 3671 return error("EXTRACTVAL: Invalid struct index"); 3672 if (IsArray && Index >= CurTy->getArrayNumElements()) 3673 return error("EXTRACTVAL: Invalid array index"); 3674 EXTRACTVALIdx.push_back((unsigned)Index); 3675 3676 if (IsStruct) 3677 CurTy = CurTy->subtypes()[Index]; 3678 else 3679 CurTy = CurTy->subtypes()[0]; 3680 } 3681 3682 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx); 3683 InstructionList.push_back(I); 3684 break; 3685 } 3686 3687 case bitc::FUNC_CODE_INST_INSERTVAL: { 3688 // INSERTVAL: [opty, opval, opty, opval, n x indices] 3689 unsigned OpNum = 0; 3690 Value *Agg; 3691 if (getValueTypePair(Record, OpNum, NextValueNo, Agg)) 3692 return error("Invalid record"); 3693 Value *Val; 3694 if (getValueTypePair(Record, OpNum, NextValueNo, Val)) 3695 return error("Invalid record"); 3696 3697 unsigned RecSize = Record.size(); 3698 if (OpNum == RecSize) 3699 return error("INSERTVAL: Invalid instruction with 0 indices"); 3700 3701 SmallVector<unsigned, 4> INSERTVALIdx; 3702 Type *CurTy = Agg->getType(); 3703 for (; OpNum != RecSize; ++OpNum) { 3704 bool IsArray = CurTy->isArrayTy(); 3705 bool IsStruct = CurTy->isStructTy(); 3706 uint64_t Index = Record[OpNum]; 3707 3708 if (!IsStruct && !IsArray) 3709 return error("INSERTVAL: Invalid type"); 3710 if ((unsigned)Index != Index) 3711 return error("Invalid value"); 3712 if (IsStruct && Index >= CurTy->subtypes().size()) 3713 return error("INSERTVAL: Invalid struct index"); 3714 if (IsArray && Index >= CurTy->getArrayNumElements()) 3715 return error("INSERTVAL: Invalid array index"); 3716 3717 INSERTVALIdx.push_back((unsigned)Index); 3718 if (IsStruct) 3719 CurTy = CurTy->subtypes()[Index]; 3720 else 3721 CurTy = CurTy->subtypes()[0]; 3722 } 3723 3724 if (CurTy != Val->getType()) 3725 return error("Inserted value type doesn't match aggregate type"); 3726 3727 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx); 3728 InstructionList.push_back(I); 3729 break; 3730 } 3731 3732 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval] 3733 // obsolete form of select 3734 // handles select i1 ... in old bitcode 3735 unsigned OpNum = 0; 3736 Value *TrueVal, *FalseVal, *Cond; 3737 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) || 3738 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) || 3739 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond)) 3740 return error("Invalid record"); 3741 3742 I = SelectInst::Create(Cond, TrueVal, FalseVal); 3743 InstructionList.push_back(I); 3744 break; 3745 } 3746 3747 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred] 3748 // new form of select 3749 // handles select i1 or select [N x i1] 3750 unsigned OpNum = 0; 3751 Value *TrueVal, *FalseVal, *Cond; 3752 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) || 3753 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) || 3754 getValueTypePair(Record, OpNum, NextValueNo, Cond)) 3755 return error("Invalid record"); 3756 3757 // select condition can be either i1 or [N x i1] 3758 if (VectorType* vector_type = 3759 dyn_cast<VectorType>(Cond->getType())) { 3760 // expect <n x i1> 3761 if (vector_type->getElementType() != Type::getInt1Ty(Context)) 3762 return error("Invalid type for value"); 3763 } else { 3764 // expect i1 3765 if (Cond->getType() != Type::getInt1Ty(Context)) 3766 return error("Invalid type for value"); 3767 } 3768 3769 I = SelectInst::Create(Cond, TrueVal, FalseVal); 3770 InstructionList.push_back(I); 3771 break; 3772 } 3773 3774 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval] 3775 unsigned OpNum = 0; 3776 Value *Vec, *Idx; 3777 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) || 3778 getValueTypePair(Record, OpNum, NextValueNo, Idx)) 3779 return error("Invalid record"); 3780 if (!Vec->getType()->isVectorTy()) 3781 return error("Invalid type for value"); 3782 I = ExtractElementInst::Create(Vec, Idx); 3783 InstructionList.push_back(I); 3784 break; 3785 } 3786 3787 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval] 3788 unsigned OpNum = 0; 3789 Value *Vec, *Elt, *Idx; 3790 if (getValueTypePair(Record, OpNum, NextValueNo, Vec)) 3791 return error("Invalid record"); 3792 if (!Vec->getType()->isVectorTy()) 3793 return error("Invalid type for value"); 3794 if (popValue(Record, OpNum, NextValueNo, 3795 cast<VectorType>(Vec->getType())->getElementType(), Elt) || 3796 getValueTypePair(Record, OpNum, NextValueNo, Idx)) 3797 return error("Invalid record"); 3798 I = InsertElementInst::Create(Vec, Elt, Idx); 3799 InstructionList.push_back(I); 3800 break; 3801 } 3802 3803 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval] 3804 unsigned OpNum = 0; 3805 Value *Vec1, *Vec2, *Mask; 3806 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) || 3807 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2)) 3808 return error("Invalid record"); 3809 3810 if (getValueTypePair(Record, OpNum, NextValueNo, Mask)) 3811 return error("Invalid record"); 3812 if (!Vec1->getType()->isVectorTy() || !Vec2->getType()->isVectorTy()) 3813 return error("Invalid type for value"); 3814 I = new ShuffleVectorInst(Vec1, Vec2, Mask); 3815 InstructionList.push_back(I); 3816 break; 3817 } 3818 3819 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred] 3820 // Old form of ICmp/FCmp returning bool 3821 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were 3822 // both legal on vectors but had different behaviour. 3823 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred] 3824 // FCmp/ICmp returning bool or vector of bool 3825 3826 unsigned OpNum = 0; 3827 Value *LHS, *RHS; 3828 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) || 3829 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS)) 3830 return error("Invalid record"); 3831 3832 unsigned PredVal = Record[OpNum]; 3833 bool IsFP = LHS->getType()->isFPOrFPVectorTy(); 3834 FastMathFlags FMF; 3835 if (IsFP && Record.size() > OpNum+1) 3836 FMF = getDecodedFastMathFlags(Record[++OpNum]); 3837 3838 if (OpNum+1 != Record.size()) 3839 return error("Invalid record"); 3840 3841 if (LHS->getType()->isFPOrFPVectorTy()) 3842 I = new FCmpInst((FCmpInst::Predicate)PredVal, LHS, RHS); 3843 else 3844 I = new ICmpInst((ICmpInst::Predicate)PredVal, LHS, RHS); 3845 3846 if (FMF.any()) 3847 I->setFastMathFlags(FMF); 3848 InstructionList.push_back(I); 3849 break; 3850 } 3851 3852 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>] 3853 { 3854 unsigned Size = Record.size(); 3855 if (Size == 0) { 3856 I = ReturnInst::Create(Context); 3857 InstructionList.push_back(I); 3858 break; 3859 } 3860 3861 unsigned OpNum = 0; 3862 Value *Op = nullptr; 3863 if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 3864 return error("Invalid record"); 3865 if (OpNum != Record.size()) 3866 return error("Invalid record"); 3867 3868 I = ReturnInst::Create(Context, Op); 3869 InstructionList.push_back(I); 3870 break; 3871 } 3872 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#] 3873 if (Record.size() != 1 && Record.size() != 3) 3874 return error("Invalid record"); 3875 BasicBlock *TrueDest = getBasicBlock(Record[0]); 3876 if (!TrueDest) 3877 return error("Invalid record"); 3878 3879 if (Record.size() == 1) { 3880 I = BranchInst::Create(TrueDest); 3881 InstructionList.push_back(I); 3882 } 3883 else { 3884 BasicBlock *FalseDest = getBasicBlock(Record[1]); 3885 Value *Cond = getValue(Record, 2, NextValueNo, 3886 Type::getInt1Ty(Context)); 3887 if (!FalseDest || !Cond) 3888 return error("Invalid record"); 3889 I = BranchInst::Create(TrueDest, FalseDest, Cond); 3890 InstructionList.push_back(I); 3891 } 3892 break; 3893 } 3894 case bitc::FUNC_CODE_INST_CLEANUPRET: { // CLEANUPRET: [val] or [val,bb#] 3895 if (Record.size() != 1 && Record.size() != 2) 3896 return error("Invalid record"); 3897 unsigned Idx = 0; 3898 Value *CleanupPad = 3899 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context)); 3900 if (!CleanupPad) 3901 return error("Invalid record"); 3902 BasicBlock *UnwindDest = nullptr; 3903 if (Record.size() == 2) { 3904 UnwindDest = getBasicBlock(Record[Idx++]); 3905 if (!UnwindDest) 3906 return error("Invalid record"); 3907 } 3908 3909 I = CleanupReturnInst::Create(CleanupPad, UnwindDest); 3910 InstructionList.push_back(I); 3911 break; 3912 } 3913 case bitc::FUNC_CODE_INST_CATCHRET: { // CATCHRET: [val,bb#] 3914 if (Record.size() != 2) 3915 return error("Invalid record"); 3916 unsigned Idx = 0; 3917 Value *CatchPad = 3918 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context)); 3919 if (!CatchPad) 3920 return error("Invalid record"); 3921 BasicBlock *BB = getBasicBlock(Record[Idx++]); 3922 if (!BB) 3923 return error("Invalid record"); 3924 3925 I = CatchReturnInst::Create(CatchPad, BB); 3926 InstructionList.push_back(I); 3927 break; 3928 } 3929 case bitc::FUNC_CODE_INST_CATCHSWITCH: { // CATCHSWITCH: [tok,num,(bb)*,bb?] 3930 // We must have, at minimum, the outer scope and the number of arguments. 3931 if (Record.size() < 2) 3932 return error("Invalid record"); 3933 3934 unsigned Idx = 0; 3935 3936 Value *ParentPad = 3937 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context)); 3938 3939 unsigned NumHandlers = Record[Idx++]; 3940 3941 SmallVector<BasicBlock *, 2> Handlers; 3942 for (unsigned Op = 0; Op != NumHandlers; ++Op) { 3943 BasicBlock *BB = getBasicBlock(Record[Idx++]); 3944 if (!BB) 3945 return error("Invalid record"); 3946 Handlers.push_back(BB); 3947 } 3948 3949 BasicBlock *UnwindDest = nullptr; 3950 if (Idx + 1 == Record.size()) { 3951 UnwindDest = getBasicBlock(Record[Idx++]); 3952 if (!UnwindDest) 3953 return error("Invalid record"); 3954 } 3955 3956 if (Record.size() != Idx) 3957 return error("Invalid record"); 3958 3959 auto *CatchSwitch = 3960 CatchSwitchInst::Create(ParentPad, UnwindDest, NumHandlers); 3961 for (BasicBlock *Handler : Handlers) 3962 CatchSwitch->addHandler(Handler); 3963 I = CatchSwitch; 3964 InstructionList.push_back(I); 3965 break; 3966 } 3967 case bitc::FUNC_CODE_INST_CATCHPAD: 3968 case bitc::FUNC_CODE_INST_CLEANUPPAD: { // [tok,num,(ty,val)*] 3969 // We must have, at minimum, the outer scope and the number of arguments. 3970 if (Record.size() < 2) 3971 return error("Invalid record"); 3972 3973 unsigned Idx = 0; 3974 3975 Value *ParentPad = 3976 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context)); 3977 3978 unsigned NumArgOperands = Record[Idx++]; 3979 3980 SmallVector<Value *, 2> Args; 3981 for (unsigned Op = 0; Op != NumArgOperands; ++Op) { 3982 Value *Val; 3983 if (getValueTypePair(Record, Idx, NextValueNo, Val)) 3984 return error("Invalid record"); 3985 Args.push_back(Val); 3986 } 3987 3988 if (Record.size() != Idx) 3989 return error("Invalid record"); 3990 3991 if (BitCode == bitc::FUNC_CODE_INST_CLEANUPPAD) 3992 I = CleanupPadInst::Create(ParentPad, Args); 3993 else 3994 I = CatchPadInst::Create(ParentPad, Args); 3995 InstructionList.push_back(I); 3996 break; 3997 } 3998 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...] 3999 // Check magic 4000 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) { 4001 // "New" SwitchInst format with case ranges. The changes to write this 4002 // format were reverted but we still recognize bitcode that uses it. 4003 // Hopefully someday we will have support for case ranges and can use 4004 // this format again. 4005 4006 Type *OpTy = getTypeByID(Record[1]); 4007 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth(); 4008 4009 Value *Cond = getValue(Record, 2, NextValueNo, OpTy); 4010 BasicBlock *Default = getBasicBlock(Record[3]); 4011 if (!OpTy || !Cond || !Default) 4012 return error("Invalid record"); 4013 4014 unsigned NumCases = Record[4]; 4015 4016 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases); 4017 InstructionList.push_back(SI); 4018 4019 unsigned CurIdx = 5; 4020 for (unsigned i = 0; i != NumCases; ++i) { 4021 SmallVector<ConstantInt*, 1> CaseVals; 4022 unsigned NumItems = Record[CurIdx++]; 4023 for (unsigned ci = 0; ci != NumItems; ++ci) { 4024 bool isSingleNumber = Record[CurIdx++]; 4025 4026 APInt Low; 4027 unsigned ActiveWords = 1; 4028 if (ValueBitWidth > 64) 4029 ActiveWords = Record[CurIdx++]; 4030 Low = readWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords), 4031 ValueBitWidth); 4032 CurIdx += ActiveWords; 4033 4034 if (!isSingleNumber) { 4035 ActiveWords = 1; 4036 if (ValueBitWidth > 64) 4037 ActiveWords = Record[CurIdx++]; 4038 APInt High = readWideAPInt( 4039 makeArrayRef(&Record[CurIdx], ActiveWords), ValueBitWidth); 4040 CurIdx += ActiveWords; 4041 4042 // FIXME: It is not clear whether values in the range should be 4043 // compared as signed or unsigned values. The partially 4044 // implemented changes that used this format in the past used 4045 // unsigned comparisons. 4046 for ( ; Low.ule(High); ++Low) 4047 CaseVals.push_back(ConstantInt::get(Context, Low)); 4048 } else 4049 CaseVals.push_back(ConstantInt::get(Context, Low)); 4050 } 4051 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]); 4052 for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(), 4053 cve = CaseVals.end(); cvi != cve; ++cvi) 4054 SI->addCase(*cvi, DestBB); 4055 } 4056 I = SI; 4057 break; 4058 } 4059 4060 // Old SwitchInst format without case ranges. 4061 4062 if (Record.size() < 3 || (Record.size() & 1) == 0) 4063 return error("Invalid record"); 4064 Type *OpTy = getTypeByID(Record[0]); 4065 Value *Cond = getValue(Record, 1, NextValueNo, OpTy); 4066 BasicBlock *Default = getBasicBlock(Record[2]); 4067 if (!OpTy || !Cond || !Default) 4068 return error("Invalid record"); 4069 unsigned NumCases = (Record.size()-3)/2; 4070 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases); 4071 InstructionList.push_back(SI); 4072 for (unsigned i = 0, e = NumCases; i != e; ++i) { 4073 ConstantInt *CaseVal = 4074 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy)); 4075 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]); 4076 if (!CaseVal || !DestBB) { 4077 delete SI; 4078 return error("Invalid record"); 4079 } 4080 SI->addCase(CaseVal, DestBB); 4081 } 4082 I = SI; 4083 break; 4084 } 4085 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...] 4086 if (Record.size() < 2) 4087 return error("Invalid record"); 4088 Type *OpTy = getTypeByID(Record[0]); 4089 Value *Address = getValue(Record, 1, NextValueNo, OpTy); 4090 if (!OpTy || !Address) 4091 return error("Invalid record"); 4092 unsigned NumDests = Record.size()-2; 4093 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests); 4094 InstructionList.push_back(IBI); 4095 for (unsigned i = 0, e = NumDests; i != e; ++i) { 4096 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) { 4097 IBI->addDestination(DestBB); 4098 } else { 4099 delete IBI; 4100 return error("Invalid record"); 4101 } 4102 } 4103 I = IBI; 4104 break; 4105 } 4106 4107 case bitc::FUNC_CODE_INST_INVOKE: { 4108 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...] 4109 if (Record.size() < 4) 4110 return error("Invalid record"); 4111 unsigned OpNum = 0; 4112 AttributeList PAL = getAttributes(Record[OpNum++]); 4113 unsigned CCInfo = Record[OpNum++]; 4114 BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]); 4115 BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]); 4116 4117 FunctionType *FTy = nullptr; 4118 if (CCInfo >> 13 & 1 && 4119 !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++])))) 4120 return error("Explicit invoke type is not a function type"); 4121 4122 Value *Callee; 4123 if (getValueTypePair(Record, OpNum, NextValueNo, Callee)) 4124 return error("Invalid record"); 4125 4126 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType()); 4127 if (!CalleeTy) 4128 return error("Callee is not a pointer"); 4129 if (!FTy) { 4130 FTy = dyn_cast<FunctionType>(CalleeTy->getElementType()); 4131 if (!FTy) 4132 return error("Callee is not of pointer to function type"); 4133 } else if (CalleeTy->getElementType() != FTy) 4134 return error("Explicit invoke type does not match pointee type of " 4135 "callee operand"); 4136 if (Record.size() < FTy->getNumParams() + OpNum) 4137 return error("Insufficient operands to call"); 4138 4139 SmallVector<Value*, 16> Ops; 4140 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) { 4141 Ops.push_back(getValue(Record, OpNum, NextValueNo, 4142 FTy->getParamType(i))); 4143 if (!Ops.back()) 4144 return error("Invalid record"); 4145 } 4146 4147 if (!FTy->isVarArg()) { 4148 if (Record.size() != OpNum) 4149 return error("Invalid record"); 4150 } else { 4151 // Read type/value pairs for varargs params. 4152 while (OpNum != Record.size()) { 4153 Value *Op; 4154 if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 4155 return error("Invalid record"); 4156 Ops.push_back(Op); 4157 } 4158 } 4159 4160 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops, OperandBundles); 4161 OperandBundles.clear(); 4162 InstructionList.push_back(I); 4163 cast<InvokeInst>(I)->setCallingConv( 4164 static_cast<CallingConv::ID>(CallingConv::MaxID & CCInfo)); 4165 cast<InvokeInst>(I)->setAttributes(PAL); 4166 break; 4167 } 4168 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval] 4169 unsigned Idx = 0; 4170 Value *Val = nullptr; 4171 if (getValueTypePair(Record, Idx, NextValueNo, Val)) 4172 return error("Invalid record"); 4173 I = ResumeInst::Create(Val); 4174 InstructionList.push_back(I); 4175 break; 4176 } 4177 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE 4178 I = new UnreachableInst(Context); 4179 InstructionList.push_back(I); 4180 break; 4181 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...] 4182 if (Record.size() < 1 || ((Record.size()-1)&1)) 4183 return error("Invalid record"); 4184 Type *Ty = getTypeByID(Record[0]); 4185 if (!Ty) 4186 return error("Invalid record"); 4187 4188 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2); 4189 InstructionList.push_back(PN); 4190 4191 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) { 4192 Value *V; 4193 // With the new function encoding, it is possible that operands have 4194 // negative IDs (for forward references). Use a signed VBR 4195 // representation to keep the encoding small. 4196 if (UseRelativeIDs) 4197 V = getValueSigned(Record, 1+i, NextValueNo, Ty); 4198 else 4199 V = getValue(Record, 1+i, NextValueNo, Ty); 4200 BasicBlock *BB = getBasicBlock(Record[2+i]); 4201 if (!V || !BB) 4202 return error("Invalid record"); 4203 PN->addIncoming(V, BB); 4204 } 4205 I = PN; 4206 break; 4207 } 4208 4209 case bitc::FUNC_CODE_INST_LANDINGPAD: 4210 case bitc::FUNC_CODE_INST_LANDINGPAD_OLD: { 4211 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?] 4212 unsigned Idx = 0; 4213 if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD) { 4214 if (Record.size() < 3) 4215 return error("Invalid record"); 4216 } else { 4217 assert(BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD); 4218 if (Record.size() < 4) 4219 return error("Invalid record"); 4220 } 4221 Type *Ty = getTypeByID(Record[Idx++]); 4222 if (!Ty) 4223 return error("Invalid record"); 4224 if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD) { 4225 Value *PersFn = nullptr; 4226 if (getValueTypePair(Record, Idx, NextValueNo, PersFn)) 4227 return error("Invalid record"); 4228 4229 if (!F->hasPersonalityFn()) 4230 F->setPersonalityFn(cast<Constant>(PersFn)); 4231 else if (F->getPersonalityFn() != cast<Constant>(PersFn)) 4232 return error("Personality function mismatch"); 4233 } 4234 4235 bool IsCleanup = !!Record[Idx++]; 4236 unsigned NumClauses = Record[Idx++]; 4237 LandingPadInst *LP = LandingPadInst::Create(Ty, NumClauses); 4238 LP->setCleanup(IsCleanup); 4239 for (unsigned J = 0; J != NumClauses; ++J) { 4240 LandingPadInst::ClauseType CT = 4241 LandingPadInst::ClauseType(Record[Idx++]); (void)CT; 4242 Value *Val; 4243 4244 if (getValueTypePair(Record, Idx, NextValueNo, Val)) { 4245 delete LP; 4246 return error("Invalid record"); 4247 } 4248 4249 assert((CT != LandingPadInst::Catch || 4250 !isa<ArrayType>(Val->getType())) && 4251 "Catch clause has a invalid type!"); 4252 assert((CT != LandingPadInst::Filter || 4253 isa<ArrayType>(Val->getType())) && 4254 "Filter clause has invalid type!"); 4255 LP->addClause(cast<Constant>(Val)); 4256 } 4257 4258 I = LP; 4259 InstructionList.push_back(I); 4260 break; 4261 } 4262 4263 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align] 4264 if (Record.size() != 4) 4265 return error("Invalid record"); 4266 uint64_t AlignRecord = Record[3]; 4267 const uint64_t InAllocaMask = uint64_t(1) << 5; 4268 const uint64_t ExplicitTypeMask = uint64_t(1) << 6; 4269 const uint64_t SwiftErrorMask = uint64_t(1) << 7; 4270 const uint64_t FlagMask = InAllocaMask | ExplicitTypeMask | 4271 SwiftErrorMask; 4272 bool InAlloca = AlignRecord & InAllocaMask; 4273 bool SwiftError = AlignRecord & SwiftErrorMask; 4274 Type *Ty = getTypeByID(Record[0]); 4275 if ((AlignRecord & ExplicitTypeMask) == 0) { 4276 auto *PTy = dyn_cast_or_null<PointerType>(Ty); 4277 if (!PTy) 4278 return error("Old-style alloca with a non-pointer type"); 4279 Ty = PTy->getElementType(); 4280 } 4281 Type *OpTy = getTypeByID(Record[1]); 4282 Value *Size = getFnValueByID(Record[2], OpTy); 4283 unsigned Align; 4284 if (Error Err = parseAlignmentValue(AlignRecord & ~FlagMask, Align)) { 4285 return Err; 4286 } 4287 if (!Ty || !Size) 4288 return error("Invalid record"); 4289 4290 // FIXME: Make this an optional field. 4291 const DataLayout &DL = TheModule->getDataLayout(); 4292 unsigned AS = DL.getAllocaAddrSpace(); 4293 4294 AllocaInst *AI = new AllocaInst(Ty, AS, Size, Align); 4295 AI->setUsedWithInAlloca(InAlloca); 4296 AI->setSwiftError(SwiftError); 4297 I = AI; 4298 InstructionList.push_back(I); 4299 break; 4300 } 4301 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol] 4302 unsigned OpNum = 0; 4303 Value *Op; 4304 if (getValueTypePair(Record, OpNum, NextValueNo, Op) || 4305 (OpNum + 2 != Record.size() && OpNum + 3 != Record.size())) 4306 return error("Invalid record"); 4307 4308 Type *Ty = nullptr; 4309 if (OpNum + 3 == Record.size()) 4310 Ty = getTypeByID(Record[OpNum++]); 4311 if (Error Err = typeCheckLoadStoreInst(Ty, Op->getType())) 4312 return Err; 4313 if (!Ty) 4314 Ty = cast<PointerType>(Op->getType())->getElementType(); 4315 4316 unsigned Align; 4317 if (Error Err = parseAlignmentValue(Record[OpNum], Align)) 4318 return Err; 4319 I = new LoadInst(Ty, Op, "", Record[OpNum + 1], Align); 4320 4321 InstructionList.push_back(I); 4322 break; 4323 } 4324 case bitc::FUNC_CODE_INST_LOADATOMIC: { 4325 // LOADATOMIC: [opty, op, align, vol, ordering, ssid] 4326 unsigned OpNum = 0; 4327 Value *Op; 4328 if (getValueTypePair(Record, OpNum, NextValueNo, Op) || 4329 (OpNum + 4 != Record.size() && OpNum + 5 != Record.size())) 4330 return error("Invalid record"); 4331 4332 Type *Ty = nullptr; 4333 if (OpNum + 5 == Record.size()) 4334 Ty = getTypeByID(Record[OpNum++]); 4335 if (Error Err = typeCheckLoadStoreInst(Ty, Op->getType())) 4336 return Err; 4337 if (!Ty) 4338 Ty = cast<PointerType>(Op->getType())->getElementType(); 4339 4340 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]); 4341 if (Ordering == AtomicOrdering::NotAtomic || 4342 Ordering == AtomicOrdering::Release || 4343 Ordering == AtomicOrdering::AcquireRelease) 4344 return error("Invalid record"); 4345 if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0) 4346 return error("Invalid record"); 4347 SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]); 4348 4349 unsigned Align; 4350 if (Error Err = parseAlignmentValue(Record[OpNum], Align)) 4351 return Err; 4352 I = new LoadInst(Op, "", Record[OpNum+1], Align, Ordering, SSID); 4353 4354 InstructionList.push_back(I); 4355 break; 4356 } 4357 case bitc::FUNC_CODE_INST_STORE: 4358 case bitc::FUNC_CODE_INST_STORE_OLD: { // STORE2:[ptrty, ptr, val, align, vol] 4359 unsigned OpNum = 0; 4360 Value *Val, *Ptr; 4361 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) || 4362 (BitCode == bitc::FUNC_CODE_INST_STORE 4363 ? getValueTypePair(Record, OpNum, NextValueNo, Val) 4364 : popValue(Record, OpNum, NextValueNo, 4365 cast<PointerType>(Ptr->getType())->getElementType(), 4366 Val)) || 4367 OpNum + 2 != Record.size()) 4368 return error("Invalid record"); 4369 4370 if (Error Err = typeCheckLoadStoreInst(Val->getType(), Ptr->getType())) 4371 return Err; 4372 unsigned Align; 4373 if (Error Err = parseAlignmentValue(Record[OpNum], Align)) 4374 return Err; 4375 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align); 4376 InstructionList.push_back(I); 4377 break; 4378 } 4379 case bitc::FUNC_CODE_INST_STOREATOMIC: 4380 case bitc::FUNC_CODE_INST_STOREATOMIC_OLD: { 4381 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, ssid] 4382 unsigned OpNum = 0; 4383 Value *Val, *Ptr; 4384 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) || 4385 !isa<PointerType>(Ptr->getType()) || 4386 (BitCode == bitc::FUNC_CODE_INST_STOREATOMIC 4387 ? getValueTypePair(Record, OpNum, NextValueNo, Val) 4388 : popValue(Record, OpNum, NextValueNo, 4389 cast<PointerType>(Ptr->getType())->getElementType(), 4390 Val)) || 4391 OpNum + 4 != Record.size()) 4392 return error("Invalid record"); 4393 4394 if (Error Err = typeCheckLoadStoreInst(Val->getType(), Ptr->getType())) 4395 return Err; 4396 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]); 4397 if (Ordering == AtomicOrdering::NotAtomic || 4398 Ordering == AtomicOrdering::Acquire || 4399 Ordering == AtomicOrdering::AcquireRelease) 4400 return error("Invalid record"); 4401 SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]); 4402 if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0) 4403 return error("Invalid record"); 4404 4405 unsigned Align; 4406 if (Error Err = parseAlignmentValue(Record[OpNum], Align)) 4407 return Err; 4408 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align, Ordering, SSID); 4409 InstructionList.push_back(I); 4410 break; 4411 } 4412 case bitc::FUNC_CODE_INST_CMPXCHG_OLD: 4413 case bitc::FUNC_CODE_INST_CMPXCHG: { 4414 // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, ssid, 4415 // failureordering?, isweak?] 4416 unsigned OpNum = 0; 4417 Value *Ptr, *Cmp, *New; 4418 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) || 4419 (BitCode == bitc::FUNC_CODE_INST_CMPXCHG 4420 ? getValueTypePair(Record, OpNum, NextValueNo, Cmp) 4421 : popValue(Record, OpNum, NextValueNo, 4422 cast<PointerType>(Ptr->getType())->getElementType(), 4423 Cmp)) || 4424 popValue(Record, OpNum, NextValueNo, Cmp->getType(), New) || 4425 Record.size() < OpNum + 3 || Record.size() > OpNum + 5) 4426 return error("Invalid record"); 4427 AtomicOrdering SuccessOrdering = getDecodedOrdering(Record[OpNum + 1]); 4428 if (SuccessOrdering == AtomicOrdering::NotAtomic || 4429 SuccessOrdering == AtomicOrdering::Unordered) 4430 return error("Invalid record"); 4431 SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 2]); 4432 4433 if (Error Err = typeCheckLoadStoreInst(Cmp->getType(), Ptr->getType())) 4434 return Err; 4435 AtomicOrdering FailureOrdering; 4436 if (Record.size() < 7) 4437 FailureOrdering = 4438 AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering); 4439 else 4440 FailureOrdering = getDecodedOrdering(Record[OpNum + 3]); 4441 4442 I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering, 4443 SSID); 4444 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]); 4445 4446 if (Record.size() < 8) { 4447 // Before weak cmpxchgs existed, the instruction simply returned the 4448 // value loaded from memory, so bitcode files from that era will be 4449 // expecting the first component of a modern cmpxchg. 4450 CurBB->getInstList().push_back(I); 4451 I = ExtractValueInst::Create(I, 0); 4452 } else { 4453 cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]); 4454 } 4455 4456 InstructionList.push_back(I); 4457 break; 4458 } 4459 case bitc::FUNC_CODE_INST_ATOMICRMW: { 4460 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, ssid] 4461 unsigned OpNum = 0; 4462 Value *Ptr, *Val; 4463 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) || 4464 !isa<PointerType>(Ptr->getType()) || 4465 popValue(Record, OpNum, NextValueNo, 4466 cast<PointerType>(Ptr->getType())->getElementType(), Val) || 4467 OpNum+4 != Record.size()) 4468 return error("Invalid record"); 4469 AtomicRMWInst::BinOp Operation = getDecodedRMWOperation(Record[OpNum]); 4470 if (Operation < AtomicRMWInst::FIRST_BINOP || 4471 Operation > AtomicRMWInst::LAST_BINOP) 4472 return error("Invalid record"); 4473 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]); 4474 if (Ordering == AtomicOrdering::NotAtomic || 4475 Ordering == AtomicOrdering::Unordered) 4476 return error("Invalid record"); 4477 SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]); 4478 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SSID); 4479 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]); 4480 InstructionList.push_back(I); 4481 break; 4482 } 4483 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, ssid] 4484 if (2 != Record.size()) 4485 return error("Invalid record"); 4486 AtomicOrdering Ordering = getDecodedOrdering(Record[0]); 4487 if (Ordering == AtomicOrdering::NotAtomic || 4488 Ordering == AtomicOrdering::Unordered || 4489 Ordering == AtomicOrdering::Monotonic) 4490 return error("Invalid record"); 4491 SyncScope::ID SSID = getDecodedSyncScopeID(Record[1]); 4492 I = new FenceInst(Context, Ordering, SSID); 4493 InstructionList.push_back(I); 4494 break; 4495 } 4496 case bitc::FUNC_CODE_INST_CALL: { 4497 // CALL: [paramattrs, cc, fmf, fnty, fnid, arg0, arg1...] 4498 if (Record.size() < 3) 4499 return error("Invalid record"); 4500 4501 unsigned OpNum = 0; 4502 AttributeList PAL = getAttributes(Record[OpNum++]); 4503 unsigned CCInfo = Record[OpNum++]; 4504 4505 FastMathFlags FMF; 4506 if ((CCInfo >> bitc::CALL_FMF) & 1) { 4507 FMF = getDecodedFastMathFlags(Record[OpNum++]); 4508 if (!FMF.any()) 4509 return error("Fast math flags indicator set for call with no FMF"); 4510 } 4511 4512 FunctionType *FTy = nullptr; 4513 if (CCInfo >> bitc::CALL_EXPLICIT_TYPE & 1 && 4514 !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++])))) 4515 return error("Explicit call type is not a function type"); 4516 4517 Value *Callee; 4518 if (getValueTypePair(Record, OpNum, NextValueNo, Callee)) 4519 return error("Invalid record"); 4520 4521 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType()); 4522 if (!OpTy) 4523 return error("Callee is not a pointer type"); 4524 if (!FTy) { 4525 FTy = dyn_cast<FunctionType>(OpTy->getElementType()); 4526 if (!FTy) 4527 return error("Callee is not of pointer to function type"); 4528 } else if (OpTy->getElementType() != FTy) 4529 return error("Explicit call type does not match pointee type of " 4530 "callee operand"); 4531 if (Record.size() < FTy->getNumParams() + OpNum) 4532 return error("Insufficient operands to call"); 4533 4534 SmallVector<Value*, 16> Args; 4535 // Read the fixed params. 4536 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) { 4537 if (FTy->getParamType(i)->isLabelTy()) 4538 Args.push_back(getBasicBlock(Record[OpNum])); 4539 else 4540 Args.push_back(getValue(Record, OpNum, NextValueNo, 4541 FTy->getParamType(i))); 4542 if (!Args.back()) 4543 return error("Invalid record"); 4544 } 4545 4546 // Read type/value pairs for varargs params. 4547 if (!FTy->isVarArg()) { 4548 if (OpNum != Record.size()) 4549 return error("Invalid record"); 4550 } else { 4551 while (OpNum != Record.size()) { 4552 Value *Op; 4553 if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 4554 return error("Invalid record"); 4555 Args.push_back(Op); 4556 } 4557 } 4558 4559 I = CallInst::Create(FTy, Callee, Args, OperandBundles); 4560 OperandBundles.clear(); 4561 InstructionList.push_back(I); 4562 cast<CallInst>(I)->setCallingConv( 4563 static_cast<CallingConv::ID>((0x7ff & CCInfo) >> bitc::CALL_CCONV)); 4564 CallInst::TailCallKind TCK = CallInst::TCK_None; 4565 if (CCInfo & 1 << bitc::CALL_TAIL) 4566 TCK = CallInst::TCK_Tail; 4567 if (CCInfo & (1 << bitc::CALL_MUSTTAIL)) 4568 TCK = CallInst::TCK_MustTail; 4569 if (CCInfo & (1 << bitc::CALL_NOTAIL)) 4570 TCK = CallInst::TCK_NoTail; 4571 cast<CallInst>(I)->setTailCallKind(TCK); 4572 cast<CallInst>(I)->setAttributes(PAL); 4573 if (FMF.any()) { 4574 if (!isa<FPMathOperator>(I)) 4575 return error("Fast-math-flags specified for call without " 4576 "floating-point scalar or vector return type"); 4577 I->setFastMathFlags(FMF); 4578 } 4579 break; 4580 } 4581 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty] 4582 if (Record.size() < 3) 4583 return error("Invalid record"); 4584 Type *OpTy = getTypeByID(Record[0]); 4585 Value *Op = getValue(Record, 1, NextValueNo, OpTy); 4586 Type *ResTy = getTypeByID(Record[2]); 4587 if (!OpTy || !Op || !ResTy) 4588 return error("Invalid record"); 4589 I = new VAArgInst(Op, ResTy); 4590 InstructionList.push_back(I); 4591 break; 4592 } 4593 4594 case bitc::FUNC_CODE_OPERAND_BUNDLE: { 4595 // A call or an invoke can be optionally prefixed with some variable 4596 // number of operand bundle blocks. These blocks are read into 4597 // OperandBundles and consumed at the next call or invoke instruction. 4598 4599 if (Record.size() < 1 || Record[0] >= BundleTags.size()) 4600 return error("Invalid record"); 4601 4602 std::vector<Value *> Inputs; 4603 4604 unsigned OpNum = 1; 4605 while (OpNum != Record.size()) { 4606 Value *Op; 4607 if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 4608 return error("Invalid record"); 4609 Inputs.push_back(Op); 4610 } 4611 4612 OperandBundles.emplace_back(BundleTags[Record[0]], std::move(Inputs)); 4613 continue; 4614 } 4615 } 4616 4617 // Add instruction to end of current BB. If there is no current BB, reject 4618 // this file. 4619 if (!CurBB) { 4620 I->deleteValue(); 4621 return error("Invalid instruction with no BB"); 4622 } 4623 if (!OperandBundles.empty()) { 4624 I->deleteValue(); 4625 return error("Operand bundles found with no consumer"); 4626 } 4627 CurBB->getInstList().push_back(I); 4628 4629 // If this was a terminator instruction, move to the next block. 4630 if (I->isTerminator()) { 4631 ++CurBBNo; 4632 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr; 4633 } 4634 4635 // Non-void values get registered in the value table for future use. 4636 if (I && !I->getType()->isVoidTy()) 4637 ValueList.assignValue(I, NextValueNo++); 4638 } 4639 4640 OutOfRecordLoop: 4641 4642 if (!OperandBundles.empty()) 4643 return error("Operand bundles found with no consumer"); 4644 4645 // Check the function list for unresolved values. 4646 if (Argument *A = dyn_cast<Argument>(ValueList.back())) { 4647 if (!A->getParent()) { 4648 // We found at least one unresolved value. Nuke them all to avoid leaks. 4649 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){ 4650 if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) { 4651 A->replaceAllUsesWith(UndefValue::get(A->getType())); 4652 delete A; 4653 } 4654 } 4655 return error("Never resolved value found in function"); 4656 } 4657 } 4658 4659 // Unexpected unresolved metadata about to be dropped. 4660 if (MDLoader->hasFwdRefs()) 4661 return error("Invalid function metadata: outgoing forward refs"); 4662 4663 // Trim the value list down to the size it was before we parsed this function. 4664 ValueList.shrinkTo(ModuleValueListSize); 4665 MDLoader->shrinkTo(ModuleMDLoaderSize); 4666 std::vector<BasicBlock*>().swap(FunctionBBs); 4667 return Error::success(); 4668 } 4669 4670 /// Find the function body in the bitcode stream 4671 Error BitcodeReader::findFunctionInStream( 4672 Function *F, 4673 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) { 4674 while (DeferredFunctionInfoIterator->second == 0) { 4675 // This is the fallback handling for the old format bitcode that 4676 // didn't contain the function index in the VST, or when we have 4677 // an anonymous function which would not have a VST entry. 4678 // Assert that we have one of those two cases. 4679 assert(VSTOffset == 0 || !F->hasName()); 4680 // Parse the next body in the stream and set its position in the 4681 // DeferredFunctionInfo map. 4682 if (Error Err = rememberAndSkipFunctionBodies()) 4683 return Err; 4684 } 4685 return Error::success(); 4686 } 4687 4688 SyncScope::ID BitcodeReader::getDecodedSyncScopeID(unsigned Val) { 4689 if (Val == SyncScope::SingleThread || Val == SyncScope::System) 4690 return SyncScope::ID(Val); 4691 if (Val >= SSIDs.size()) 4692 return SyncScope::System; // Map unknown synchronization scopes to system. 4693 return SSIDs[Val]; 4694 } 4695 4696 //===----------------------------------------------------------------------===// 4697 // GVMaterializer implementation 4698 //===----------------------------------------------------------------------===// 4699 4700 Error BitcodeReader::materialize(GlobalValue *GV) { 4701 Function *F = dyn_cast<Function>(GV); 4702 // If it's not a function or is already material, ignore the request. 4703 if (!F || !F->isMaterializable()) 4704 return Error::success(); 4705 4706 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F); 4707 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!"); 4708 // If its position is recorded as 0, its body is somewhere in the stream 4709 // but we haven't seen it yet. 4710 if (DFII->second == 0) 4711 if (Error Err = findFunctionInStream(F, DFII)) 4712 return Err; 4713 4714 // Materialize metadata before parsing any function bodies. 4715 if (Error Err = materializeMetadata()) 4716 return Err; 4717 4718 // Move the bit stream to the saved position of the deferred function body. 4719 Stream.JumpToBit(DFII->second); 4720 4721 if (Error Err = parseFunctionBody(F)) 4722 return Err; 4723 F->setIsMaterializable(false); 4724 4725 if (StripDebugInfo) 4726 stripDebugInfo(*F); 4727 4728 // Upgrade any old intrinsic calls in the function. 4729 for (auto &I : UpgradedIntrinsics) { 4730 for (auto UI = I.first->materialized_user_begin(), UE = I.first->user_end(); 4731 UI != UE;) { 4732 User *U = *UI; 4733 ++UI; 4734 if (CallInst *CI = dyn_cast<CallInst>(U)) 4735 UpgradeIntrinsicCall(CI, I.second); 4736 } 4737 } 4738 4739 // Update calls to the remangled intrinsics 4740 for (auto &I : RemangledIntrinsics) 4741 for (auto UI = I.first->materialized_user_begin(), UE = I.first->user_end(); 4742 UI != UE;) 4743 // Don't expect any other users than call sites 4744 CallSite(*UI++).setCalledFunction(I.second); 4745 4746 // Finish fn->subprogram upgrade for materialized functions. 4747 if (DISubprogram *SP = MDLoader->lookupSubprogramForFunction(F)) 4748 F->setSubprogram(SP); 4749 4750 // Check if the TBAA Metadata are valid, otherwise we will need to strip them. 4751 if (!MDLoader->isStrippingTBAA()) { 4752 for (auto &I : instructions(F)) { 4753 MDNode *TBAA = I.getMetadata(LLVMContext::MD_tbaa); 4754 if (!TBAA || TBAAVerifyHelper.visitTBAAMetadata(I, TBAA)) 4755 continue; 4756 MDLoader->setStripTBAA(true); 4757 stripTBAA(F->getParent()); 4758 } 4759 } 4760 4761 // Bring in any functions that this function forward-referenced via 4762 // blockaddresses. 4763 return materializeForwardReferencedFunctions(); 4764 } 4765 4766 Error BitcodeReader::materializeModule() { 4767 if (Error Err = materializeMetadata()) 4768 return Err; 4769 4770 // Promise to materialize all forward references. 4771 WillMaterializeAllForwardRefs = true; 4772 4773 // Iterate over the module, deserializing any functions that are still on 4774 // disk. 4775 for (Function &F : *TheModule) { 4776 if (Error Err = materialize(&F)) 4777 return Err; 4778 } 4779 // At this point, if there are any function bodies, parse the rest of 4780 // the bits in the module past the last function block we have recorded 4781 // through either lazy scanning or the VST. 4782 if (LastFunctionBlockBit || NextUnreadBit) 4783 if (Error Err = parseModule(LastFunctionBlockBit > NextUnreadBit 4784 ? LastFunctionBlockBit 4785 : NextUnreadBit)) 4786 return Err; 4787 4788 // Check that all block address forward references got resolved (as we 4789 // promised above). 4790 if (!BasicBlockFwdRefs.empty()) 4791 return error("Never resolved function from blockaddress"); 4792 4793 // Upgrade any intrinsic calls that slipped through (should not happen!) and 4794 // delete the old functions to clean up. We can't do this unless the entire 4795 // module is materialized because there could always be another function body 4796 // with calls to the old function. 4797 for (auto &I : UpgradedIntrinsics) { 4798 for (auto *U : I.first->users()) { 4799 if (CallInst *CI = dyn_cast<CallInst>(U)) 4800 UpgradeIntrinsicCall(CI, I.second); 4801 } 4802 if (!I.first->use_empty()) 4803 I.first->replaceAllUsesWith(I.second); 4804 I.first->eraseFromParent(); 4805 } 4806 UpgradedIntrinsics.clear(); 4807 // Do the same for remangled intrinsics 4808 for (auto &I : RemangledIntrinsics) { 4809 I.first->replaceAllUsesWith(I.second); 4810 I.first->eraseFromParent(); 4811 } 4812 RemangledIntrinsics.clear(); 4813 4814 UpgradeDebugInfo(*TheModule); 4815 4816 UpgradeModuleFlags(*TheModule); 4817 4818 UpgradeRetainReleaseMarker(*TheModule); 4819 4820 return Error::success(); 4821 } 4822 4823 std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const { 4824 return IdentifiedStructTypes; 4825 } 4826 4827 ModuleSummaryIndexBitcodeReader::ModuleSummaryIndexBitcodeReader( 4828 BitstreamCursor Cursor, StringRef Strtab, ModuleSummaryIndex &TheIndex, 4829 StringRef ModulePath, unsigned ModuleId) 4830 : BitcodeReaderBase(std::move(Cursor), Strtab), TheIndex(TheIndex), 4831 ModulePath(ModulePath), ModuleId(ModuleId) {} 4832 4833 void ModuleSummaryIndexBitcodeReader::addThisModule() { 4834 TheIndex.addModule(ModulePath, ModuleId); 4835 } 4836 4837 ModuleSummaryIndex::ModuleInfo * 4838 ModuleSummaryIndexBitcodeReader::getThisModule() { 4839 return TheIndex.getModule(ModulePath); 4840 } 4841 4842 std::pair<ValueInfo, GlobalValue::GUID> 4843 ModuleSummaryIndexBitcodeReader::getValueInfoFromValueId(unsigned ValueId) { 4844 auto VGI = ValueIdToValueInfoMap[ValueId]; 4845 assert(VGI.first); 4846 return VGI; 4847 } 4848 4849 void ModuleSummaryIndexBitcodeReader::setValueGUID( 4850 uint64_t ValueID, StringRef ValueName, GlobalValue::LinkageTypes Linkage, 4851 StringRef SourceFileName) { 4852 std::string GlobalId = 4853 GlobalValue::getGlobalIdentifier(ValueName, Linkage, SourceFileName); 4854 auto ValueGUID = GlobalValue::getGUID(GlobalId); 4855 auto OriginalNameID = ValueGUID; 4856 if (GlobalValue::isLocalLinkage(Linkage)) 4857 OriginalNameID = GlobalValue::getGUID(ValueName); 4858 if (PrintSummaryGUIDs) 4859 dbgs() << "GUID " << ValueGUID << "(" << OriginalNameID << ") is " 4860 << ValueName << "\n"; 4861 4862 // UseStrtab is false for legacy summary formats and value names are 4863 // created on stack. In that case we save the name in a string saver in 4864 // the index so that the value name can be recorded. 4865 ValueIdToValueInfoMap[ValueID] = std::make_pair( 4866 TheIndex.getOrInsertValueInfo( 4867 ValueGUID, 4868 UseStrtab ? ValueName : TheIndex.saveString(ValueName.str())), 4869 OriginalNameID); 4870 } 4871 4872 // Specialized value symbol table parser used when reading module index 4873 // blocks where we don't actually create global values. The parsed information 4874 // is saved in the bitcode reader for use when later parsing summaries. 4875 Error ModuleSummaryIndexBitcodeReader::parseValueSymbolTable( 4876 uint64_t Offset, 4877 DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap) { 4878 // With a strtab the VST is not required to parse the summary. 4879 if (UseStrtab) 4880 return Error::success(); 4881 4882 assert(Offset > 0 && "Expected non-zero VST offset"); 4883 uint64_t CurrentBit = jumpToValueSymbolTable(Offset, Stream); 4884 4885 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID)) 4886 return error("Invalid record"); 4887 4888 SmallVector<uint64_t, 64> Record; 4889 4890 // Read all the records for this value table. 4891 SmallString<128> ValueName; 4892 4893 while (true) { 4894 BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 4895 4896 switch (Entry.Kind) { 4897 case BitstreamEntry::SubBlock: // Handled for us already. 4898 case BitstreamEntry::Error: 4899 return error("Malformed block"); 4900 case BitstreamEntry::EndBlock: 4901 // Done parsing VST, jump back to wherever we came from. 4902 Stream.JumpToBit(CurrentBit); 4903 return Error::success(); 4904 case BitstreamEntry::Record: 4905 // The interesting case. 4906 break; 4907 } 4908 4909 // Read a record. 4910 Record.clear(); 4911 switch (Stream.readRecord(Entry.ID, Record)) { 4912 default: // Default behavior: ignore (e.g. VST_CODE_BBENTRY records). 4913 break; 4914 case bitc::VST_CODE_ENTRY: { // VST_CODE_ENTRY: [valueid, namechar x N] 4915 if (convertToString(Record, 1, ValueName)) 4916 return error("Invalid record"); 4917 unsigned ValueID = Record[0]; 4918 assert(!SourceFileName.empty()); 4919 auto VLI = ValueIdToLinkageMap.find(ValueID); 4920 assert(VLI != ValueIdToLinkageMap.end() && 4921 "No linkage found for VST entry?"); 4922 auto Linkage = VLI->second; 4923 setValueGUID(ValueID, ValueName, Linkage, SourceFileName); 4924 ValueName.clear(); 4925 break; 4926 } 4927 case bitc::VST_CODE_FNENTRY: { 4928 // VST_CODE_FNENTRY: [valueid, offset, namechar x N] 4929 if (convertToString(Record, 2, ValueName)) 4930 return error("Invalid record"); 4931 unsigned ValueID = Record[0]; 4932 assert(!SourceFileName.empty()); 4933 auto VLI = ValueIdToLinkageMap.find(ValueID); 4934 assert(VLI != ValueIdToLinkageMap.end() && 4935 "No linkage found for VST entry?"); 4936 auto Linkage = VLI->second; 4937 setValueGUID(ValueID, ValueName, Linkage, SourceFileName); 4938 ValueName.clear(); 4939 break; 4940 } 4941 case bitc::VST_CODE_COMBINED_ENTRY: { 4942 // VST_CODE_COMBINED_ENTRY: [valueid, refguid] 4943 unsigned ValueID = Record[0]; 4944 GlobalValue::GUID RefGUID = Record[1]; 4945 // The "original name", which is the second value of the pair will be 4946 // overriden later by a FS_COMBINED_ORIGINAL_NAME in the combined index. 4947 ValueIdToValueInfoMap[ValueID] = 4948 std::make_pair(TheIndex.getOrInsertValueInfo(RefGUID), RefGUID); 4949 break; 4950 } 4951 } 4952 } 4953 } 4954 4955 // Parse just the blocks needed for building the index out of the module. 4956 // At the end of this routine the module Index is populated with a map 4957 // from global value id to GlobalValueSummary objects. 4958 Error ModuleSummaryIndexBitcodeReader::parseModule() { 4959 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID)) 4960 return error("Invalid record"); 4961 4962 SmallVector<uint64_t, 64> Record; 4963 DenseMap<unsigned, GlobalValue::LinkageTypes> ValueIdToLinkageMap; 4964 unsigned ValueId = 0; 4965 4966 // Read the index for this module. 4967 while (true) { 4968 BitstreamEntry Entry = Stream.advance(); 4969 4970 switch (Entry.Kind) { 4971 case BitstreamEntry::Error: 4972 return error("Malformed block"); 4973 case BitstreamEntry::EndBlock: 4974 return Error::success(); 4975 4976 case BitstreamEntry::SubBlock: 4977 switch (Entry.ID) { 4978 default: // Skip unknown content. 4979 if (Stream.SkipBlock()) 4980 return error("Invalid record"); 4981 break; 4982 case bitc::BLOCKINFO_BLOCK_ID: 4983 // Need to parse these to get abbrev ids (e.g. for VST) 4984 if (readBlockInfo()) 4985 return error("Malformed block"); 4986 break; 4987 case bitc::VALUE_SYMTAB_BLOCK_ID: 4988 // Should have been parsed earlier via VSTOffset, unless there 4989 // is no summary section. 4990 assert(((SeenValueSymbolTable && VSTOffset > 0) || 4991 !SeenGlobalValSummary) && 4992 "Expected early VST parse via VSTOffset record"); 4993 if (Stream.SkipBlock()) 4994 return error("Invalid record"); 4995 break; 4996 case bitc::GLOBALVAL_SUMMARY_BLOCK_ID: 4997 case bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID: 4998 // Add the module if it is a per-module index (has a source file name). 4999 if (!SourceFileName.empty()) 5000 addThisModule(); 5001 assert(!SeenValueSymbolTable && 5002 "Already read VST when parsing summary block?"); 5003 // We might not have a VST if there were no values in the 5004 // summary. An empty summary block generated when we are 5005 // performing ThinLTO compiles so we don't later invoke 5006 // the regular LTO process on them. 5007 if (VSTOffset > 0) { 5008 if (Error Err = parseValueSymbolTable(VSTOffset, ValueIdToLinkageMap)) 5009 return Err; 5010 SeenValueSymbolTable = true; 5011 } 5012 SeenGlobalValSummary = true; 5013 if (Error Err = parseEntireSummary(Entry.ID)) 5014 return Err; 5015 break; 5016 case bitc::MODULE_STRTAB_BLOCK_ID: 5017 if (Error Err = parseModuleStringTable()) 5018 return Err; 5019 break; 5020 } 5021 continue; 5022 5023 case BitstreamEntry::Record: { 5024 Record.clear(); 5025 auto BitCode = Stream.readRecord(Entry.ID, Record); 5026 switch (BitCode) { 5027 default: 5028 break; // Default behavior, ignore unknown content. 5029 case bitc::MODULE_CODE_VERSION: { 5030 if (Error Err = parseVersionRecord(Record).takeError()) 5031 return Err; 5032 break; 5033 } 5034 /// MODULE_CODE_SOURCE_FILENAME: [namechar x N] 5035 case bitc::MODULE_CODE_SOURCE_FILENAME: { 5036 SmallString<128> ValueName; 5037 if (convertToString(Record, 0, ValueName)) 5038 return error("Invalid record"); 5039 SourceFileName = ValueName.c_str(); 5040 break; 5041 } 5042 /// MODULE_CODE_HASH: [5*i32] 5043 case bitc::MODULE_CODE_HASH: { 5044 if (Record.size() != 5) 5045 return error("Invalid hash length " + Twine(Record.size()).str()); 5046 auto &Hash = getThisModule()->second.second; 5047 int Pos = 0; 5048 for (auto &Val : Record) { 5049 assert(!(Val >> 32) && "Unexpected high bits set"); 5050 Hash[Pos++] = Val; 5051 } 5052 break; 5053 } 5054 /// MODULE_CODE_VSTOFFSET: [offset] 5055 case bitc::MODULE_CODE_VSTOFFSET: 5056 if (Record.size() < 1) 5057 return error("Invalid record"); 5058 // Note that we subtract 1 here because the offset is relative to one 5059 // word before the start of the identification or module block, which 5060 // was historically always the start of the regular bitcode header. 5061 VSTOffset = Record[0] - 1; 5062 break; 5063 // v1 GLOBALVAR: [pointer type, isconst, initid, linkage, ...] 5064 // v1 FUNCTION: [type, callingconv, isproto, linkage, ...] 5065 // v1 ALIAS: [alias type, addrspace, aliasee val#, linkage, ...] 5066 // v2: [strtab offset, strtab size, v1] 5067 case bitc::MODULE_CODE_GLOBALVAR: 5068 case bitc::MODULE_CODE_FUNCTION: 5069 case bitc::MODULE_CODE_ALIAS: { 5070 StringRef Name; 5071 ArrayRef<uint64_t> GVRecord; 5072 std::tie(Name, GVRecord) = readNameFromStrtab(Record); 5073 if (GVRecord.size() <= 3) 5074 return error("Invalid record"); 5075 uint64_t RawLinkage = GVRecord[3]; 5076 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage); 5077 if (!UseStrtab) { 5078 ValueIdToLinkageMap[ValueId++] = Linkage; 5079 break; 5080 } 5081 5082 setValueGUID(ValueId++, Name, Linkage, SourceFileName); 5083 break; 5084 } 5085 } 5086 } 5087 continue; 5088 } 5089 } 5090 } 5091 5092 std::vector<ValueInfo> 5093 ModuleSummaryIndexBitcodeReader::makeRefList(ArrayRef<uint64_t> Record) { 5094 std::vector<ValueInfo> Ret; 5095 Ret.reserve(Record.size()); 5096 for (uint64_t RefValueId : Record) 5097 Ret.push_back(getValueInfoFromValueId(RefValueId).first); 5098 return Ret; 5099 } 5100 5101 std::vector<FunctionSummary::EdgeTy> 5102 ModuleSummaryIndexBitcodeReader::makeCallList(ArrayRef<uint64_t> Record, 5103 bool IsOldProfileFormat, 5104 bool HasProfile, bool HasRelBF) { 5105 std::vector<FunctionSummary::EdgeTy> Ret; 5106 Ret.reserve(Record.size()); 5107 for (unsigned I = 0, E = Record.size(); I != E; ++I) { 5108 CalleeInfo::HotnessType Hotness = CalleeInfo::HotnessType::Unknown; 5109 uint64_t RelBF = 0; 5110 ValueInfo Callee = getValueInfoFromValueId(Record[I]).first; 5111 if (IsOldProfileFormat) { 5112 I += 1; // Skip old callsitecount field 5113 if (HasProfile) 5114 I += 1; // Skip old profilecount field 5115 } else if (HasProfile) 5116 Hotness = static_cast<CalleeInfo::HotnessType>(Record[++I]); 5117 else if (HasRelBF) 5118 RelBF = Record[++I]; 5119 Ret.push_back(FunctionSummary::EdgeTy{Callee, CalleeInfo(Hotness, RelBF)}); 5120 } 5121 return Ret; 5122 } 5123 5124 static void 5125 parseWholeProgramDevirtResolutionByArg(ArrayRef<uint64_t> Record, size_t &Slot, 5126 WholeProgramDevirtResolution &Wpd) { 5127 uint64_t ArgNum = Record[Slot++]; 5128 WholeProgramDevirtResolution::ByArg &B = 5129 Wpd.ResByArg[{Record.begin() + Slot, Record.begin() + Slot + ArgNum}]; 5130 Slot += ArgNum; 5131 5132 B.TheKind = 5133 static_cast<WholeProgramDevirtResolution::ByArg::Kind>(Record[Slot++]); 5134 B.Info = Record[Slot++]; 5135 B.Byte = Record[Slot++]; 5136 B.Bit = Record[Slot++]; 5137 } 5138 5139 static void parseWholeProgramDevirtResolution(ArrayRef<uint64_t> Record, 5140 StringRef Strtab, size_t &Slot, 5141 TypeIdSummary &TypeId) { 5142 uint64_t Id = Record[Slot++]; 5143 WholeProgramDevirtResolution &Wpd = TypeId.WPDRes[Id]; 5144 5145 Wpd.TheKind = static_cast<WholeProgramDevirtResolution::Kind>(Record[Slot++]); 5146 Wpd.SingleImplName = {Strtab.data() + Record[Slot], 5147 static_cast<size_t>(Record[Slot + 1])}; 5148 Slot += 2; 5149 5150 uint64_t ResByArgNum = Record[Slot++]; 5151 for (uint64_t I = 0; I != ResByArgNum; ++I) 5152 parseWholeProgramDevirtResolutionByArg(Record, Slot, Wpd); 5153 } 5154 5155 static void parseTypeIdSummaryRecord(ArrayRef<uint64_t> Record, 5156 StringRef Strtab, 5157 ModuleSummaryIndex &TheIndex) { 5158 size_t Slot = 0; 5159 TypeIdSummary &TypeId = TheIndex.getOrInsertTypeIdSummary( 5160 {Strtab.data() + Record[Slot], static_cast<size_t>(Record[Slot + 1])}); 5161 Slot += 2; 5162 5163 TypeId.TTRes.TheKind = static_cast<TypeTestResolution::Kind>(Record[Slot++]); 5164 TypeId.TTRes.SizeM1BitWidth = Record[Slot++]; 5165 TypeId.TTRes.AlignLog2 = Record[Slot++]; 5166 TypeId.TTRes.SizeM1 = Record[Slot++]; 5167 TypeId.TTRes.BitMask = Record[Slot++]; 5168 TypeId.TTRes.InlineBits = Record[Slot++]; 5169 5170 while (Slot < Record.size()) 5171 parseWholeProgramDevirtResolution(Record, Strtab, Slot, TypeId); 5172 } 5173 5174 // Eagerly parse the entire summary block. This populates the GlobalValueSummary 5175 // objects in the index. 5176 Error ModuleSummaryIndexBitcodeReader::parseEntireSummary(unsigned ID) { 5177 if (Stream.EnterSubBlock(ID)) 5178 return error("Invalid record"); 5179 SmallVector<uint64_t, 64> Record; 5180 5181 // Parse version 5182 { 5183 BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 5184 if (Entry.Kind != BitstreamEntry::Record) 5185 return error("Invalid Summary Block: record for version expected"); 5186 if (Stream.readRecord(Entry.ID, Record) != bitc::FS_VERSION) 5187 return error("Invalid Summary Block: version expected"); 5188 } 5189 const uint64_t Version = Record[0]; 5190 const bool IsOldProfileFormat = Version == 1; 5191 if (Version < 1 || Version > 4) 5192 return error("Invalid summary version " + Twine(Version) + 5193 ", 1, 2, 3 or 4 expected"); 5194 Record.clear(); 5195 5196 // Keep around the last seen summary to be used when we see an optional 5197 // "OriginalName" attachement. 5198 GlobalValueSummary *LastSeenSummary = nullptr; 5199 GlobalValue::GUID LastSeenGUID = 0; 5200 5201 // We can expect to see any number of type ID information records before 5202 // each function summary records; these variables store the information 5203 // collected so far so that it can be used to create the summary object. 5204 std::vector<GlobalValue::GUID> PendingTypeTests; 5205 std::vector<FunctionSummary::VFuncId> PendingTypeTestAssumeVCalls, 5206 PendingTypeCheckedLoadVCalls; 5207 std::vector<FunctionSummary::ConstVCall> PendingTypeTestAssumeConstVCalls, 5208 PendingTypeCheckedLoadConstVCalls; 5209 5210 while (true) { 5211 BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 5212 5213 switch (Entry.Kind) { 5214 case BitstreamEntry::SubBlock: // Handled for us already. 5215 case BitstreamEntry::Error: 5216 return error("Malformed block"); 5217 case BitstreamEntry::EndBlock: 5218 return Error::success(); 5219 case BitstreamEntry::Record: 5220 // The interesting case. 5221 break; 5222 } 5223 5224 // Read a record. The record format depends on whether this 5225 // is a per-module index or a combined index file. In the per-module 5226 // case the records contain the associated value's ID for correlation 5227 // with VST entries. In the combined index the correlation is done 5228 // via the bitcode offset of the summary records (which were saved 5229 // in the combined index VST entries). The records also contain 5230 // information used for ThinLTO renaming and importing. 5231 Record.clear(); 5232 auto BitCode = Stream.readRecord(Entry.ID, Record); 5233 switch (BitCode) { 5234 default: // Default behavior: ignore. 5235 break; 5236 case bitc::FS_FLAGS: { // [flags] 5237 uint64_t Flags = Record[0]; 5238 // Scan flags (set only on the combined index). 5239 assert(Flags <= 0x3 && "Unexpected bits in flag"); 5240 5241 // 1 bit: WithGlobalValueDeadStripping flag. 5242 if (Flags & 0x1) 5243 TheIndex.setWithGlobalValueDeadStripping(); 5244 // 1 bit: SkipModuleByDistributedBackend flag. 5245 if (Flags & 0x2) 5246 TheIndex.setSkipModuleByDistributedBackend(); 5247 break; 5248 } 5249 case bitc::FS_VALUE_GUID: { // [valueid, refguid] 5250 uint64_t ValueID = Record[0]; 5251 GlobalValue::GUID RefGUID = Record[1]; 5252 ValueIdToValueInfoMap[ValueID] = 5253 std::make_pair(TheIndex.getOrInsertValueInfo(RefGUID), RefGUID); 5254 break; 5255 } 5256 // FS_PERMODULE: [valueid, flags, instcount, fflags, numrefs, 5257 // numrefs x valueid, n x (valueid)] 5258 // FS_PERMODULE_PROFILE: [valueid, flags, instcount, fflags, numrefs, 5259 // numrefs x valueid, 5260 // n x (valueid, hotness)] 5261 // FS_PERMODULE_RELBF: [valueid, flags, instcount, fflags, numrefs, 5262 // numrefs x valueid, 5263 // n x (valueid, relblockfreq)] 5264 case bitc::FS_PERMODULE: 5265 case bitc::FS_PERMODULE_RELBF: 5266 case bitc::FS_PERMODULE_PROFILE: { 5267 unsigned ValueID = Record[0]; 5268 uint64_t RawFlags = Record[1]; 5269 unsigned InstCount = Record[2]; 5270 uint64_t RawFunFlags = 0; 5271 unsigned NumRefs = Record[3]; 5272 int RefListStartIndex = 4; 5273 if (Version >= 4) { 5274 RawFunFlags = Record[3]; 5275 NumRefs = Record[4]; 5276 RefListStartIndex = 5; 5277 } 5278 5279 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version); 5280 // The module path string ref set in the summary must be owned by the 5281 // index's module string table. Since we don't have a module path 5282 // string table section in the per-module index, we create a single 5283 // module path string table entry with an empty (0) ID to take 5284 // ownership. 5285 int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs; 5286 assert(Record.size() >= RefListStartIndex + NumRefs && 5287 "Record size inconsistent with number of references"); 5288 std::vector<ValueInfo> Refs = makeRefList( 5289 ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs)); 5290 bool HasProfile = (BitCode == bitc::FS_PERMODULE_PROFILE); 5291 bool HasRelBF = (BitCode == bitc::FS_PERMODULE_RELBF); 5292 std::vector<FunctionSummary::EdgeTy> Calls = makeCallList( 5293 ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex), 5294 IsOldProfileFormat, HasProfile, HasRelBF); 5295 auto FS = llvm::make_unique<FunctionSummary>( 5296 Flags, InstCount, getDecodedFFlags(RawFunFlags), std::move(Refs), 5297 std::move(Calls), std::move(PendingTypeTests), 5298 std::move(PendingTypeTestAssumeVCalls), 5299 std::move(PendingTypeCheckedLoadVCalls), 5300 std::move(PendingTypeTestAssumeConstVCalls), 5301 std::move(PendingTypeCheckedLoadConstVCalls)); 5302 PendingTypeTests.clear(); 5303 PendingTypeTestAssumeVCalls.clear(); 5304 PendingTypeCheckedLoadVCalls.clear(); 5305 PendingTypeTestAssumeConstVCalls.clear(); 5306 PendingTypeCheckedLoadConstVCalls.clear(); 5307 auto VIAndOriginalGUID = getValueInfoFromValueId(ValueID); 5308 FS->setModulePath(getThisModule()->first()); 5309 FS->setOriginalName(VIAndOriginalGUID.second); 5310 TheIndex.addGlobalValueSummary(VIAndOriginalGUID.first, std::move(FS)); 5311 break; 5312 } 5313 // FS_ALIAS: [valueid, flags, valueid] 5314 // Aliases must be emitted (and parsed) after all FS_PERMODULE entries, as 5315 // they expect all aliasee summaries to be available. 5316 case bitc::FS_ALIAS: { 5317 unsigned ValueID = Record[0]; 5318 uint64_t RawFlags = Record[1]; 5319 unsigned AliaseeID = Record[2]; 5320 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version); 5321 auto AS = llvm::make_unique<AliasSummary>(Flags); 5322 // The module path string ref set in the summary must be owned by the 5323 // index's module string table. Since we don't have a module path 5324 // string table section in the per-module index, we create a single 5325 // module path string table entry with an empty (0) ID to take 5326 // ownership. 5327 AS->setModulePath(getThisModule()->first()); 5328 5329 GlobalValue::GUID AliaseeGUID = 5330 getValueInfoFromValueId(AliaseeID).first.getGUID(); 5331 auto AliaseeInModule = 5332 TheIndex.findSummaryInModule(AliaseeGUID, ModulePath); 5333 if (!AliaseeInModule) 5334 return error("Alias expects aliasee summary to be parsed"); 5335 AS->setAliasee(AliaseeInModule); 5336 AS->setAliaseeGUID(AliaseeGUID); 5337 5338 auto GUID = getValueInfoFromValueId(ValueID); 5339 AS->setOriginalName(GUID.second); 5340 TheIndex.addGlobalValueSummary(GUID.first, std::move(AS)); 5341 break; 5342 } 5343 // FS_PERMODULE_GLOBALVAR_INIT_REFS: [valueid, flags, n x valueid] 5344 case bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS: { 5345 unsigned ValueID = Record[0]; 5346 uint64_t RawFlags = Record[1]; 5347 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version); 5348 std::vector<ValueInfo> Refs = 5349 makeRefList(ArrayRef<uint64_t>(Record).slice(2)); 5350 auto FS = llvm::make_unique<GlobalVarSummary>(Flags, std::move(Refs)); 5351 FS->setModulePath(getThisModule()->first()); 5352 auto GUID = getValueInfoFromValueId(ValueID); 5353 FS->setOriginalName(GUID.second); 5354 TheIndex.addGlobalValueSummary(GUID.first, std::move(FS)); 5355 break; 5356 } 5357 // FS_COMBINED: [valueid, modid, flags, instcount, fflags, numrefs, 5358 // numrefs x valueid, n x (valueid)] 5359 // FS_COMBINED_PROFILE: [valueid, modid, flags, instcount, fflags, numrefs, 5360 // numrefs x valueid, n x (valueid, hotness)] 5361 case bitc::FS_COMBINED: 5362 case bitc::FS_COMBINED_PROFILE: { 5363 unsigned ValueID = Record[0]; 5364 uint64_t ModuleId = Record[1]; 5365 uint64_t RawFlags = Record[2]; 5366 unsigned InstCount = Record[3]; 5367 uint64_t RawFunFlags = 0; 5368 unsigned NumRefs = Record[4]; 5369 int RefListStartIndex = 5; 5370 5371 if (Version >= 4) { 5372 RawFunFlags = Record[4]; 5373 NumRefs = Record[5]; 5374 RefListStartIndex = 6; 5375 } 5376 5377 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version); 5378 int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs; 5379 assert(Record.size() >= RefListStartIndex + NumRefs && 5380 "Record size inconsistent with number of references"); 5381 std::vector<ValueInfo> Refs = makeRefList( 5382 ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs)); 5383 bool HasProfile = (BitCode == bitc::FS_COMBINED_PROFILE); 5384 std::vector<FunctionSummary::EdgeTy> Edges = makeCallList( 5385 ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex), 5386 IsOldProfileFormat, HasProfile, false); 5387 ValueInfo VI = getValueInfoFromValueId(ValueID).first; 5388 auto FS = llvm::make_unique<FunctionSummary>( 5389 Flags, InstCount, getDecodedFFlags(RawFunFlags), std::move(Refs), 5390 std::move(Edges), std::move(PendingTypeTests), 5391 std::move(PendingTypeTestAssumeVCalls), 5392 std::move(PendingTypeCheckedLoadVCalls), 5393 std::move(PendingTypeTestAssumeConstVCalls), 5394 std::move(PendingTypeCheckedLoadConstVCalls)); 5395 PendingTypeTests.clear(); 5396 PendingTypeTestAssumeVCalls.clear(); 5397 PendingTypeCheckedLoadVCalls.clear(); 5398 PendingTypeTestAssumeConstVCalls.clear(); 5399 PendingTypeCheckedLoadConstVCalls.clear(); 5400 LastSeenSummary = FS.get(); 5401 LastSeenGUID = VI.getGUID(); 5402 FS->setModulePath(ModuleIdMap[ModuleId]); 5403 TheIndex.addGlobalValueSummary(VI, std::move(FS)); 5404 break; 5405 } 5406 // FS_COMBINED_ALIAS: [valueid, modid, flags, valueid] 5407 // Aliases must be emitted (and parsed) after all FS_COMBINED entries, as 5408 // they expect all aliasee summaries to be available. 5409 case bitc::FS_COMBINED_ALIAS: { 5410 unsigned ValueID = Record[0]; 5411 uint64_t ModuleId = Record[1]; 5412 uint64_t RawFlags = Record[2]; 5413 unsigned AliaseeValueId = Record[3]; 5414 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version); 5415 auto AS = llvm::make_unique<AliasSummary>(Flags); 5416 LastSeenSummary = AS.get(); 5417 AS->setModulePath(ModuleIdMap[ModuleId]); 5418 5419 auto AliaseeGUID = 5420 getValueInfoFromValueId(AliaseeValueId).first.getGUID(); 5421 auto AliaseeInModule = 5422 TheIndex.findSummaryInModule(AliaseeGUID, AS->modulePath()); 5423 AS->setAliasee(AliaseeInModule); 5424 AS->setAliaseeGUID(AliaseeGUID); 5425 5426 ValueInfo VI = getValueInfoFromValueId(ValueID).first; 5427 LastSeenGUID = VI.getGUID(); 5428 TheIndex.addGlobalValueSummary(VI, std::move(AS)); 5429 break; 5430 } 5431 // FS_COMBINED_GLOBALVAR_INIT_REFS: [valueid, modid, flags, n x valueid] 5432 case bitc::FS_COMBINED_GLOBALVAR_INIT_REFS: { 5433 unsigned ValueID = Record[0]; 5434 uint64_t ModuleId = Record[1]; 5435 uint64_t RawFlags = Record[2]; 5436 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version); 5437 std::vector<ValueInfo> Refs = 5438 makeRefList(ArrayRef<uint64_t>(Record).slice(3)); 5439 auto FS = llvm::make_unique<GlobalVarSummary>(Flags, std::move(Refs)); 5440 LastSeenSummary = FS.get(); 5441 FS->setModulePath(ModuleIdMap[ModuleId]); 5442 ValueInfo VI = getValueInfoFromValueId(ValueID).first; 5443 LastSeenGUID = VI.getGUID(); 5444 TheIndex.addGlobalValueSummary(VI, std::move(FS)); 5445 break; 5446 } 5447 // FS_COMBINED_ORIGINAL_NAME: [original_name] 5448 case bitc::FS_COMBINED_ORIGINAL_NAME: { 5449 uint64_t OriginalName = Record[0]; 5450 if (!LastSeenSummary) 5451 return error("Name attachment that does not follow a combined record"); 5452 LastSeenSummary->setOriginalName(OriginalName); 5453 TheIndex.addOriginalName(LastSeenGUID, OriginalName); 5454 // Reset the LastSeenSummary 5455 LastSeenSummary = nullptr; 5456 LastSeenGUID = 0; 5457 break; 5458 } 5459 case bitc::FS_TYPE_TESTS: 5460 assert(PendingTypeTests.empty()); 5461 PendingTypeTests.insert(PendingTypeTests.end(), Record.begin(), 5462 Record.end()); 5463 break; 5464 5465 case bitc::FS_TYPE_TEST_ASSUME_VCALLS: 5466 assert(PendingTypeTestAssumeVCalls.empty()); 5467 for (unsigned I = 0; I != Record.size(); I += 2) 5468 PendingTypeTestAssumeVCalls.push_back({Record[I], Record[I+1]}); 5469 break; 5470 5471 case bitc::FS_TYPE_CHECKED_LOAD_VCALLS: 5472 assert(PendingTypeCheckedLoadVCalls.empty()); 5473 for (unsigned I = 0; I != Record.size(); I += 2) 5474 PendingTypeCheckedLoadVCalls.push_back({Record[I], Record[I+1]}); 5475 break; 5476 5477 case bitc::FS_TYPE_TEST_ASSUME_CONST_VCALL: 5478 PendingTypeTestAssumeConstVCalls.push_back( 5479 {{Record[0], Record[1]}, {Record.begin() + 2, Record.end()}}); 5480 break; 5481 5482 case bitc::FS_TYPE_CHECKED_LOAD_CONST_VCALL: 5483 PendingTypeCheckedLoadConstVCalls.push_back( 5484 {{Record[0], Record[1]}, {Record.begin() + 2, Record.end()}}); 5485 break; 5486 5487 case bitc::FS_CFI_FUNCTION_DEFS: { 5488 std::set<std::string> &CfiFunctionDefs = TheIndex.cfiFunctionDefs(); 5489 for (unsigned I = 0; I != Record.size(); I += 2) 5490 CfiFunctionDefs.insert( 5491 {Strtab.data() + Record[I], static_cast<size_t>(Record[I + 1])}); 5492 break; 5493 } 5494 5495 case bitc::FS_CFI_FUNCTION_DECLS: { 5496 std::set<std::string> &CfiFunctionDecls = TheIndex.cfiFunctionDecls(); 5497 for (unsigned I = 0; I != Record.size(); I += 2) 5498 CfiFunctionDecls.insert( 5499 {Strtab.data() + Record[I], static_cast<size_t>(Record[I + 1])}); 5500 break; 5501 } 5502 5503 case bitc::FS_TYPE_ID: 5504 parseTypeIdSummaryRecord(Record, Strtab, TheIndex); 5505 break; 5506 } 5507 } 5508 llvm_unreachable("Exit infinite loop"); 5509 } 5510 5511 // Parse the module string table block into the Index. 5512 // This populates the ModulePathStringTable map in the index. 5513 Error ModuleSummaryIndexBitcodeReader::parseModuleStringTable() { 5514 if (Stream.EnterSubBlock(bitc::MODULE_STRTAB_BLOCK_ID)) 5515 return error("Invalid record"); 5516 5517 SmallVector<uint64_t, 64> Record; 5518 5519 SmallString<128> ModulePath; 5520 ModuleSummaryIndex::ModuleInfo *LastSeenModule = nullptr; 5521 5522 while (true) { 5523 BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 5524 5525 switch (Entry.Kind) { 5526 case BitstreamEntry::SubBlock: // Handled for us already. 5527 case BitstreamEntry::Error: 5528 return error("Malformed block"); 5529 case BitstreamEntry::EndBlock: 5530 return Error::success(); 5531 case BitstreamEntry::Record: 5532 // The interesting case. 5533 break; 5534 } 5535 5536 Record.clear(); 5537 switch (Stream.readRecord(Entry.ID, Record)) { 5538 default: // Default behavior: ignore. 5539 break; 5540 case bitc::MST_CODE_ENTRY: { 5541 // MST_ENTRY: [modid, namechar x N] 5542 uint64_t ModuleId = Record[0]; 5543 5544 if (convertToString(Record, 1, ModulePath)) 5545 return error("Invalid record"); 5546 5547 LastSeenModule = TheIndex.addModule(ModulePath, ModuleId); 5548 ModuleIdMap[ModuleId] = LastSeenModule->first(); 5549 5550 ModulePath.clear(); 5551 break; 5552 } 5553 /// MST_CODE_HASH: [5*i32] 5554 case bitc::MST_CODE_HASH: { 5555 if (Record.size() != 5) 5556 return error("Invalid hash length " + Twine(Record.size()).str()); 5557 if (!LastSeenModule) 5558 return error("Invalid hash that does not follow a module path"); 5559 int Pos = 0; 5560 for (auto &Val : Record) { 5561 assert(!(Val >> 32) && "Unexpected high bits set"); 5562 LastSeenModule->second.second[Pos++] = Val; 5563 } 5564 // Reset LastSeenModule to avoid overriding the hash unexpectedly. 5565 LastSeenModule = nullptr; 5566 break; 5567 } 5568 } 5569 } 5570 llvm_unreachable("Exit infinite loop"); 5571 } 5572 5573 namespace { 5574 5575 // FIXME: This class is only here to support the transition to llvm::Error. It 5576 // will be removed once this transition is complete. Clients should prefer to 5577 // deal with the Error value directly, rather than converting to error_code. 5578 class BitcodeErrorCategoryType : public std::error_category { 5579 const char *name() const noexcept override { 5580 return "llvm.bitcode"; 5581 } 5582 5583 std::string message(int IE) const override { 5584 BitcodeError E = static_cast<BitcodeError>(IE); 5585 switch (E) { 5586 case BitcodeError::CorruptedBitcode: 5587 return "Corrupted bitcode"; 5588 } 5589 llvm_unreachable("Unknown error type!"); 5590 } 5591 }; 5592 5593 } // end anonymous namespace 5594 5595 static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory; 5596 5597 const std::error_category &llvm::BitcodeErrorCategory() { 5598 return *ErrorCategory; 5599 } 5600 5601 static Expected<StringRef> readBlobInRecord(BitstreamCursor &Stream, 5602 unsigned Block, unsigned RecordID) { 5603 if (Stream.EnterSubBlock(Block)) 5604 return error("Invalid record"); 5605 5606 StringRef Strtab; 5607 while (true) { 5608 BitstreamEntry Entry = Stream.advance(); 5609 switch (Entry.Kind) { 5610 case BitstreamEntry::EndBlock: 5611 return Strtab; 5612 5613 case BitstreamEntry::Error: 5614 return error("Malformed block"); 5615 5616 case BitstreamEntry::SubBlock: 5617 if (Stream.SkipBlock()) 5618 return error("Malformed block"); 5619 break; 5620 5621 case BitstreamEntry::Record: 5622 StringRef Blob; 5623 SmallVector<uint64_t, 1> Record; 5624 if (Stream.readRecord(Entry.ID, Record, &Blob) == RecordID) 5625 Strtab = Blob; 5626 break; 5627 } 5628 } 5629 } 5630 5631 //===----------------------------------------------------------------------===// 5632 // External interface 5633 //===----------------------------------------------------------------------===// 5634 5635 Expected<std::vector<BitcodeModule>> 5636 llvm::getBitcodeModuleList(MemoryBufferRef Buffer) { 5637 auto FOrErr = getBitcodeFileContents(Buffer); 5638 if (!FOrErr) 5639 return FOrErr.takeError(); 5640 return std::move(FOrErr->Mods); 5641 } 5642 5643 Expected<BitcodeFileContents> 5644 llvm::getBitcodeFileContents(MemoryBufferRef Buffer) { 5645 Expected<BitstreamCursor> StreamOrErr = initStream(Buffer); 5646 if (!StreamOrErr) 5647 return StreamOrErr.takeError(); 5648 BitstreamCursor &Stream = *StreamOrErr; 5649 5650 BitcodeFileContents F; 5651 while (true) { 5652 uint64_t BCBegin = Stream.getCurrentByteNo(); 5653 5654 // We may be consuming bitcode from a client that leaves garbage at the end 5655 // of the bitcode stream (e.g. Apple's ar tool). If we are close enough to 5656 // the end that there cannot possibly be another module, stop looking. 5657 if (BCBegin + 8 >= Stream.getBitcodeBytes().size()) 5658 return F; 5659 5660 BitstreamEntry Entry = Stream.advance(); 5661 switch (Entry.Kind) { 5662 case BitstreamEntry::EndBlock: 5663 case BitstreamEntry::Error: 5664 return error("Malformed block"); 5665 5666 case BitstreamEntry::SubBlock: { 5667 uint64_t IdentificationBit = -1ull; 5668 if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) { 5669 IdentificationBit = Stream.GetCurrentBitNo() - BCBegin * 8; 5670 if (Stream.SkipBlock()) 5671 return error("Malformed block"); 5672 5673 Entry = Stream.advance(); 5674 if (Entry.Kind != BitstreamEntry::SubBlock || 5675 Entry.ID != bitc::MODULE_BLOCK_ID) 5676 return error("Malformed block"); 5677 } 5678 5679 if (Entry.ID == bitc::MODULE_BLOCK_ID) { 5680 uint64_t ModuleBit = Stream.GetCurrentBitNo() - BCBegin * 8; 5681 if (Stream.SkipBlock()) 5682 return error("Malformed block"); 5683 5684 F.Mods.push_back({Stream.getBitcodeBytes().slice( 5685 BCBegin, Stream.getCurrentByteNo() - BCBegin), 5686 Buffer.getBufferIdentifier(), IdentificationBit, 5687 ModuleBit}); 5688 continue; 5689 } 5690 5691 if (Entry.ID == bitc::STRTAB_BLOCK_ID) { 5692 Expected<StringRef> Strtab = 5693 readBlobInRecord(Stream, bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB); 5694 if (!Strtab) 5695 return Strtab.takeError(); 5696 // This string table is used by every preceding bitcode module that does 5697 // not have its own string table. A bitcode file may have multiple 5698 // string tables if it was created by binary concatenation, for example 5699 // with "llvm-cat -b". 5700 for (auto I = F.Mods.rbegin(), E = F.Mods.rend(); I != E; ++I) { 5701 if (!I->Strtab.empty()) 5702 break; 5703 I->Strtab = *Strtab; 5704 } 5705 // Similarly, the string table is used by every preceding symbol table; 5706 // normally there will be just one unless the bitcode file was created 5707 // by binary concatenation. 5708 if (!F.Symtab.empty() && F.StrtabForSymtab.empty()) 5709 F.StrtabForSymtab = *Strtab; 5710 continue; 5711 } 5712 5713 if (Entry.ID == bitc::SYMTAB_BLOCK_ID) { 5714 Expected<StringRef> SymtabOrErr = 5715 readBlobInRecord(Stream, bitc::SYMTAB_BLOCK_ID, bitc::SYMTAB_BLOB); 5716 if (!SymtabOrErr) 5717 return SymtabOrErr.takeError(); 5718 5719 // We can expect the bitcode file to have multiple symbol tables if it 5720 // was created by binary concatenation. In that case we silently 5721 // ignore any subsequent symbol tables, which is fine because this is a 5722 // low level function. The client is expected to notice that the number 5723 // of modules in the symbol table does not match the number of modules 5724 // in the input file and regenerate the symbol table. 5725 if (F.Symtab.empty()) 5726 F.Symtab = *SymtabOrErr; 5727 continue; 5728 } 5729 5730 if (Stream.SkipBlock()) 5731 return error("Malformed block"); 5732 continue; 5733 } 5734 case BitstreamEntry::Record: 5735 Stream.skipRecord(Entry.ID); 5736 continue; 5737 } 5738 } 5739 } 5740 5741 /// Get a lazy one-at-time loading module from bitcode. 5742 /// 5743 /// This isn't always used in a lazy context. In particular, it's also used by 5744 /// \a parseModule(). If this is truly lazy, then we need to eagerly pull 5745 /// in forward-referenced functions from block address references. 5746 /// 5747 /// \param[in] MaterializeAll Set to \c true if we should materialize 5748 /// everything. 5749 Expected<std::unique_ptr<Module>> 5750 BitcodeModule::getModuleImpl(LLVMContext &Context, bool MaterializeAll, 5751 bool ShouldLazyLoadMetadata, bool IsImporting) { 5752 BitstreamCursor Stream(Buffer); 5753 5754 std::string ProducerIdentification; 5755 if (IdentificationBit != -1ull) { 5756 Stream.JumpToBit(IdentificationBit); 5757 Expected<std::string> ProducerIdentificationOrErr = 5758 readIdentificationBlock(Stream); 5759 if (!ProducerIdentificationOrErr) 5760 return ProducerIdentificationOrErr.takeError(); 5761 5762 ProducerIdentification = *ProducerIdentificationOrErr; 5763 } 5764 5765 Stream.JumpToBit(ModuleBit); 5766 auto *R = new BitcodeReader(std::move(Stream), Strtab, ProducerIdentification, 5767 Context); 5768 5769 std::unique_ptr<Module> M = 5770 llvm::make_unique<Module>(ModuleIdentifier, Context); 5771 M->setMaterializer(R); 5772 5773 // Delay parsing Metadata if ShouldLazyLoadMetadata is true. 5774 if (Error Err = 5775 R->parseBitcodeInto(M.get(), ShouldLazyLoadMetadata, IsImporting)) 5776 return std::move(Err); 5777 5778 if (MaterializeAll) { 5779 // Read in the entire module, and destroy the BitcodeReader. 5780 if (Error Err = M->materializeAll()) 5781 return std::move(Err); 5782 } else { 5783 // Resolve forward references from blockaddresses. 5784 if (Error Err = R->materializeForwardReferencedFunctions()) 5785 return std::move(Err); 5786 } 5787 return std::move(M); 5788 } 5789 5790 Expected<std::unique_ptr<Module>> 5791 BitcodeModule::getLazyModule(LLVMContext &Context, bool ShouldLazyLoadMetadata, 5792 bool IsImporting) { 5793 return getModuleImpl(Context, false, ShouldLazyLoadMetadata, IsImporting); 5794 } 5795 5796 // Parse the specified bitcode buffer and merge the index into CombinedIndex. 5797 // We don't use ModuleIdentifier here because the client may need to control the 5798 // module path used in the combined summary (e.g. when reading summaries for 5799 // regular LTO modules). 5800 Error BitcodeModule::readSummary(ModuleSummaryIndex &CombinedIndex, 5801 StringRef ModulePath, uint64_t ModuleId) { 5802 BitstreamCursor Stream(Buffer); 5803 Stream.JumpToBit(ModuleBit); 5804 5805 ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, CombinedIndex, 5806 ModulePath, ModuleId); 5807 return R.parseModule(); 5808 } 5809 5810 // Parse the specified bitcode buffer, returning the function info index. 5811 Expected<std::unique_ptr<ModuleSummaryIndex>> BitcodeModule::getSummary() { 5812 BitstreamCursor Stream(Buffer); 5813 Stream.JumpToBit(ModuleBit); 5814 5815 auto Index = llvm::make_unique<ModuleSummaryIndex>(/*HaveGVs=*/false); 5816 ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, *Index, 5817 ModuleIdentifier, 0); 5818 5819 if (Error Err = R.parseModule()) 5820 return std::move(Err); 5821 5822 return std::move(Index); 5823 } 5824 5825 // Check if the given bitcode buffer contains a global value summary block. 5826 Expected<BitcodeLTOInfo> BitcodeModule::getLTOInfo() { 5827 BitstreamCursor Stream(Buffer); 5828 Stream.JumpToBit(ModuleBit); 5829 5830 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID)) 5831 return error("Invalid record"); 5832 5833 while (true) { 5834 BitstreamEntry Entry = Stream.advance(); 5835 5836 switch (Entry.Kind) { 5837 case BitstreamEntry::Error: 5838 return error("Malformed block"); 5839 case BitstreamEntry::EndBlock: 5840 return BitcodeLTOInfo{/*IsThinLTO=*/false, /*HasSummary=*/false}; 5841 5842 case BitstreamEntry::SubBlock: 5843 if (Entry.ID == bitc::GLOBALVAL_SUMMARY_BLOCK_ID) 5844 return BitcodeLTOInfo{/*IsThinLTO=*/true, /*HasSummary=*/true}; 5845 5846 if (Entry.ID == bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID) 5847 return BitcodeLTOInfo{/*IsThinLTO=*/false, /*HasSummary=*/true}; 5848 5849 // Ignore other sub-blocks. 5850 if (Stream.SkipBlock()) 5851 return error("Malformed block"); 5852 continue; 5853 5854 case BitstreamEntry::Record: 5855 Stream.skipRecord(Entry.ID); 5856 continue; 5857 } 5858 } 5859 } 5860 5861 static Expected<BitcodeModule> getSingleModule(MemoryBufferRef Buffer) { 5862 Expected<std::vector<BitcodeModule>> MsOrErr = getBitcodeModuleList(Buffer); 5863 if (!MsOrErr) 5864 return MsOrErr.takeError(); 5865 5866 if (MsOrErr->size() != 1) 5867 return error("Expected a single module"); 5868 5869 return (*MsOrErr)[0]; 5870 } 5871 5872 Expected<std::unique_ptr<Module>> 5873 llvm::getLazyBitcodeModule(MemoryBufferRef Buffer, LLVMContext &Context, 5874 bool ShouldLazyLoadMetadata, bool IsImporting) { 5875 Expected<BitcodeModule> BM = getSingleModule(Buffer); 5876 if (!BM) 5877 return BM.takeError(); 5878 5879 return BM->getLazyModule(Context, ShouldLazyLoadMetadata, IsImporting); 5880 } 5881 5882 Expected<std::unique_ptr<Module>> llvm::getOwningLazyBitcodeModule( 5883 std::unique_ptr<MemoryBuffer> &&Buffer, LLVMContext &Context, 5884 bool ShouldLazyLoadMetadata, bool IsImporting) { 5885 auto MOrErr = getLazyBitcodeModule(*Buffer, Context, ShouldLazyLoadMetadata, 5886 IsImporting); 5887 if (MOrErr) 5888 (*MOrErr)->setOwnedMemoryBuffer(std::move(Buffer)); 5889 return MOrErr; 5890 } 5891 5892 Expected<std::unique_ptr<Module>> 5893 BitcodeModule::parseModule(LLVMContext &Context) { 5894 return getModuleImpl(Context, true, false, false); 5895 // TODO: Restore the use-lists to the in-memory state when the bitcode was 5896 // written. We must defer until the Module has been fully materialized. 5897 } 5898 5899 Expected<std::unique_ptr<Module>> llvm::parseBitcodeFile(MemoryBufferRef Buffer, 5900 LLVMContext &Context) { 5901 Expected<BitcodeModule> BM = getSingleModule(Buffer); 5902 if (!BM) 5903 return BM.takeError(); 5904 5905 return BM->parseModule(Context); 5906 } 5907 5908 Expected<std::string> llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer) { 5909 Expected<BitstreamCursor> StreamOrErr = initStream(Buffer); 5910 if (!StreamOrErr) 5911 return StreamOrErr.takeError(); 5912 5913 return readTriple(*StreamOrErr); 5914 } 5915 5916 Expected<bool> llvm::isBitcodeContainingObjCCategory(MemoryBufferRef Buffer) { 5917 Expected<BitstreamCursor> StreamOrErr = initStream(Buffer); 5918 if (!StreamOrErr) 5919 return StreamOrErr.takeError(); 5920 5921 return hasObjCCategory(*StreamOrErr); 5922 } 5923 5924 Expected<std::string> llvm::getBitcodeProducerString(MemoryBufferRef Buffer) { 5925 Expected<BitstreamCursor> StreamOrErr = initStream(Buffer); 5926 if (!StreamOrErr) 5927 return StreamOrErr.takeError(); 5928 5929 return readIdentificationCode(*StreamOrErr); 5930 } 5931 5932 Error llvm::readModuleSummaryIndex(MemoryBufferRef Buffer, 5933 ModuleSummaryIndex &CombinedIndex, 5934 uint64_t ModuleId) { 5935 Expected<BitcodeModule> BM = getSingleModule(Buffer); 5936 if (!BM) 5937 return BM.takeError(); 5938 5939 return BM->readSummary(CombinedIndex, BM->getModuleIdentifier(), ModuleId); 5940 } 5941 5942 Expected<std::unique_ptr<ModuleSummaryIndex>> 5943 llvm::getModuleSummaryIndex(MemoryBufferRef Buffer) { 5944 Expected<BitcodeModule> BM = getSingleModule(Buffer); 5945 if (!BM) 5946 return BM.takeError(); 5947 5948 return BM->getSummary(); 5949 } 5950 5951 Expected<BitcodeLTOInfo> llvm::getBitcodeLTOInfo(MemoryBufferRef Buffer) { 5952 Expected<BitcodeModule> BM = getSingleModule(Buffer); 5953 if (!BM) 5954 return BM.takeError(); 5955 5956 return BM->getLTOInfo(); 5957 } 5958 5959 Expected<std::unique_ptr<ModuleSummaryIndex>> 5960 llvm::getModuleSummaryIndexForFile(StringRef Path, 5961 bool IgnoreEmptyThinLTOIndexFile) { 5962 ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr = 5963 MemoryBuffer::getFileOrSTDIN(Path); 5964 if (!FileOrErr) 5965 return errorCodeToError(FileOrErr.getError()); 5966 if (IgnoreEmptyThinLTOIndexFile && !(*FileOrErr)->getBufferSize()) 5967 return nullptr; 5968 return getModuleSummaryIndex(**FileOrErr); 5969 } 5970