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