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