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