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