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