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 uint64_t AlignInBits = Record[8]; 2501 uint64_t OffsetInBits = Record[9]; 2502 DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[10]); 2503 Metadata *Elements = getMDOrNull(Record[11]); 2504 unsigned RuntimeLang = Record[12]; 2505 Metadata *VTableHolder = getDITypeRefOrNull(Record[13]); 2506 Metadata *TemplateParams = getMDOrNull(Record[14]); 2507 auto *Identifier = getMDString(Record[15]); 2508 DICompositeType *CT = nullptr; 2509 if (Identifier) 2510 CT = DICompositeType::buildODRType( 2511 Context, *Identifier, Tag, Name, File, Line, Scope, BaseType, 2512 SizeInBits, AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang, 2513 VTableHolder, TemplateParams); 2514 2515 // Create a node if we didn't get a lazy ODR type. 2516 if (!CT) 2517 CT = GET_OR_DISTINCT(DICompositeType, 2518 (Context, Tag, Name, File, Line, Scope, BaseType, 2519 SizeInBits, AlignInBits, OffsetInBits, Flags, 2520 Elements, RuntimeLang, VTableHolder, 2521 TemplateParams, Identifier)); 2522 if (!IsNotUsedInTypeRef && Identifier) 2523 MetadataList.addTypeRef(*Identifier, *cast<DICompositeType>(CT)); 2524 2525 MetadataList.assignValue(CT, NextMetadataNo++); 2526 break; 2527 } 2528 case bitc::METADATA_SUBROUTINE_TYPE: { 2529 if (Record.size() < 3 || Record.size() > 4) 2530 return error("Invalid record"); 2531 bool IsOldTypeRefArray = Record[0] < 2; 2532 unsigned CC = (Record.size() > 3) ? Record[3] : 0; 2533 2534 IsDistinct = Record[0] & 0x1; 2535 DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[1]); 2536 Metadata *Types = getMDOrNull(Record[2]); 2537 if (LLVM_UNLIKELY(IsOldTypeRefArray)) 2538 Types = MetadataList.upgradeTypeRefArray(Types); 2539 2540 MetadataList.assignValue( 2541 GET_OR_DISTINCT(DISubroutineType, (Context, Flags, CC, Types)), 2542 NextMetadataNo++); 2543 break; 2544 } 2545 2546 case bitc::METADATA_MODULE: { 2547 if (Record.size() != 6) 2548 return error("Invalid record"); 2549 2550 IsDistinct = Record[0]; 2551 MetadataList.assignValue( 2552 GET_OR_DISTINCT(DIModule, 2553 (Context, getMDOrNull(Record[1]), 2554 getMDString(Record[2]), getMDString(Record[3]), 2555 getMDString(Record[4]), getMDString(Record[5]))), 2556 NextMetadataNo++); 2557 break; 2558 } 2559 2560 case bitc::METADATA_FILE: { 2561 if (Record.size() != 3) 2562 return error("Invalid record"); 2563 2564 IsDistinct = Record[0]; 2565 MetadataList.assignValue( 2566 GET_OR_DISTINCT(DIFile, (Context, getMDString(Record[1]), 2567 getMDString(Record[2]))), 2568 NextMetadataNo++); 2569 break; 2570 } 2571 case bitc::METADATA_COMPILE_UNIT: { 2572 if (Record.size() < 14 || Record.size() > 17) 2573 return error("Invalid record"); 2574 2575 // Ignore Record[0], which indicates whether this compile unit is 2576 // distinct. It's always distinct. 2577 IsDistinct = true; 2578 auto *CU = DICompileUnit::getDistinct( 2579 Context, Record[1], getMDOrNull(Record[2]), getMDString(Record[3]), 2580 Record[4], getMDString(Record[5]), Record[6], getMDString(Record[7]), 2581 Record[8], getMDOrNull(Record[9]), getMDOrNull(Record[10]), 2582 getMDOrNull(Record[12]), getMDOrNull(Record[13]), 2583 Record.size() <= 15 ? nullptr : getMDOrNull(Record[15]), 2584 Record.size() <= 14 ? 0 : Record[14], 2585 Record.size() <= 16 ? true : Record[16]); 2586 2587 MetadataList.assignValue(CU, NextMetadataNo++); 2588 2589 // Move the Upgrade the list of subprograms. 2590 if (Metadata *SPs = getMDOrNullWithoutPlaceholders(Record[11])) 2591 CUSubprograms.push_back({CU, SPs}); 2592 break; 2593 } 2594 case bitc::METADATA_SUBPROGRAM: { 2595 if (Record.size() < 18 || Record.size() > 20) 2596 return error("Invalid record"); 2597 2598 IsDistinct = 2599 (Record[0] & 1) || Record[8]; // All definitions should be distinct. 2600 // Version 1 has a Function as Record[15]. 2601 // Version 2 has removed Record[15]. 2602 // Version 3 has the Unit as Record[15]. 2603 // Version 4 added thisAdjustment. 2604 bool HasUnit = Record[0] >= 2; 2605 if (HasUnit && Record.size() < 19) 2606 return error("Invalid record"); 2607 Metadata *CUorFn = getMDOrNull(Record[15]); 2608 unsigned Offset = Record.size() >= 19 ? 1 : 0; 2609 bool HasFn = Offset && !HasUnit; 2610 bool HasThisAdj = Record.size() >= 20; 2611 DISubprogram *SP = GET_OR_DISTINCT( 2612 DISubprogram, (Context, 2613 getDITypeRefOrNull(Record[1]), // scope 2614 getMDString(Record[2]), // name 2615 getMDString(Record[3]), // linkageName 2616 getMDOrNull(Record[4]), // file 2617 Record[5], // line 2618 getMDOrNull(Record[6]), // type 2619 Record[7], // isLocal 2620 Record[8], // isDefinition 2621 Record[9], // scopeLine 2622 getDITypeRefOrNull(Record[10]), // containingType 2623 Record[11], // virtuality 2624 Record[12], // virtualIndex 2625 HasThisAdj ? Record[19] : 0, // thisAdjustment 2626 static_cast<DINode::DIFlags>(Record[13] // flags 2627 ), 2628 Record[14], // isOptimized 2629 HasUnit ? CUorFn : nullptr, // unit 2630 getMDOrNull(Record[15 + Offset]), // templateParams 2631 getMDOrNull(Record[16 + Offset]), // declaration 2632 getMDOrNull(Record[17 + Offset]) // variables 2633 )); 2634 MetadataList.assignValue(SP, NextMetadataNo++); 2635 2636 // Upgrade sp->function mapping to function->sp mapping. 2637 if (HasFn) { 2638 if (auto *CMD = dyn_cast_or_null<ConstantAsMetadata>(CUorFn)) 2639 if (auto *F = dyn_cast<Function>(CMD->getValue())) { 2640 if (F->isMaterializable()) 2641 // Defer until materialized; unmaterialized functions may not have 2642 // metadata. 2643 FunctionsWithSPs[F] = SP; 2644 else if (!F->empty()) 2645 F->setSubprogram(SP); 2646 } 2647 } 2648 break; 2649 } 2650 case bitc::METADATA_LEXICAL_BLOCK: { 2651 if (Record.size() != 5) 2652 return error("Invalid record"); 2653 2654 IsDistinct = Record[0]; 2655 MetadataList.assignValue( 2656 GET_OR_DISTINCT(DILexicalBlock, 2657 (Context, getMDOrNull(Record[1]), 2658 getMDOrNull(Record[2]), Record[3], Record[4])), 2659 NextMetadataNo++); 2660 break; 2661 } 2662 case bitc::METADATA_LEXICAL_BLOCK_FILE: { 2663 if (Record.size() != 4) 2664 return error("Invalid record"); 2665 2666 IsDistinct = Record[0]; 2667 MetadataList.assignValue( 2668 GET_OR_DISTINCT(DILexicalBlockFile, 2669 (Context, getMDOrNull(Record[1]), 2670 getMDOrNull(Record[2]), Record[3])), 2671 NextMetadataNo++); 2672 break; 2673 } 2674 case bitc::METADATA_NAMESPACE: { 2675 if (Record.size() != 5) 2676 return error("Invalid record"); 2677 2678 IsDistinct = Record[0]; 2679 MetadataList.assignValue( 2680 GET_OR_DISTINCT(DINamespace, (Context, getMDOrNull(Record[1]), 2681 getMDOrNull(Record[2]), 2682 getMDString(Record[3]), Record[4])), 2683 NextMetadataNo++); 2684 break; 2685 } 2686 case bitc::METADATA_MACRO: { 2687 if (Record.size() != 5) 2688 return error("Invalid record"); 2689 2690 IsDistinct = Record[0]; 2691 MetadataList.assignValue( 2692 GET_OR_DISTINCT(DIMacro, 2693 (Context, Record[1], Record[2], 2694 getMDString(Record[3]), getMDString(Record[4]))), 2695 NextMetadataNo++); 2696 break; 2697 } 2698 case bitc::METADATA_MACRO_FILE: { 2699 if (Record.size() != 5) 2700 return error("Invalid record"); 2701 2702 IsDistinct = Record[0]; 2703 MetadataList.assignValue( 2704 GET_OR_DISTINCT(DIMacroFile, 2705 (Context, Record[1], Record[2], 2706 getMDOrNull(Record[3]), getMDOrNull(Record[4]))), 2707 NextMetadataNo++); 2708 break; 2709 } 2710 case bitc::METADATA_TEMPLATE_TYPE: { 2711 if (Record.size() != 3) 2712 return error("Invalid record"); 2713 2714 IsDistinct = Record[0]; 2715 MetadataList.assignValue(GET_OR_DISTINCT(DITemplateTypeParameter, 2716 (Context, getMDString(Record[1]), 2717 getDITypeRefOrNull(Record[2]))), 2718 NextMetadataNo++); 2719 break; 2720 } 2721 case bitc::METADATA_TEMPLATE_VALUE: { 2722 if (Record.size() != 5) 2723 return error("Invalid record"); 2724 2725 IsDistinct = Record[0]; 2726 MetadataList.assignValue( 2727 GET_OR_DISTINCT(DITemplateValueParameter, 2728 (Context, Record[1], getMDString(Record[2]), 2729 getDITypeRefOrNull(Record[3]), 2730 getMDOrNull(Record[4]))), 2731 NextMetadataNo++); 2732 break; 2733 } 2734 case bitc::METADATA_GLOBAL_VAR: { 2735 if (Record.size() != 11) 2736 return error("Invalid record"); 2737 2738 IsDistinct = Record[0]; 2739 2740 // Upgrade old metadata, which stored a global variable reference or a 2741 // ConstantInt here. 2742 Metadata *Expr = getMDOrNull(Record[9]); 2743 GlobalVariable *Attach = nullptr; 2744 if (auto *CMD = dyn_cast_or_null<ConstantAsMetadata>(Expr)) { 2745 if (auto *GV = dyn_cast<GlobalVariable>(CMD->getValue())) { 2746 Attach = GV; 2747 Expr = nullptr; 2748 } else if (auto *CI = dyn_cast<ConstantInt>(CMD->getValue())) { 2749 Expr = DIExpression::get(Context, 2750 {dwarf::DW_OP_constu, CI->getZExtValue(), 2751 dwarf::DW_OP_stack_value}); 2752 } else { 2753 Expr = nullptr; 2754 } 2755 } 2756 2757 DIGlobalVariable *DGV = GET_OR_DISTINCT( 2758 DIGlobalVariable, 2759 (Context, getMDOrNull(Record[1]), getMDString(Record[2]), 2760 getMDString(Record[3]), getMDOrNull(Record[4]), Record[5], 2761 getDITypeRefOrNull(Record[6]), Record[7], Record[8], Expr, 2762 getMDOrNull(Record[10]))); 2763 MetadataList.assignValue(DGV, NextMetadataNo++); 2764 2765 if (Attach) 2766 Attach->addDebugInfo(DGV); 2767 2768 break; 2769 } 2770 case bitc::METADATA_LOCAL_VAR: { 2771 // 10th field is for the obseleted 'inlinedAt:' field. 2772 if (Record.size() < 8 || Record.size() > 10) 2773 return error("Invalid record"); 2774 2775 // 2nd field used to be an artificial tag, either DW_TAG_auto_variable or 2776 // DW_TAG_arg_variable. 2777 IsDistinct = Record[0]; 2778 bool HasTag = Record.size() > 8; 2779 DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[7 + HasTag]); 2780 MetadataList.assignValue( 2781 GET_OR_DISTINCT(DILocalVariable, 2782 (Context, getMDOrNull(Record[1 + HasTag]), 2783 getMDString(Record[2 + HasTag]), 2784 getMDOrNull(Record[3 + HasTag]), Record[4 + HasTag], 2785 getDITypeRefOrNull(Record[5 + HasTag]), 2786 Record[6 + HasTag], Flags)), 2787 NextMetadataNo++); 2788 break; 2789 } 2790 case bitc::METADATA_EXPRESSION: { 2791 if (Record.size() < 1) 2792 return error("Invalid record"); 2793 2794 IsDistinct = Record[0]; 2795 MetadataList.assignValue( 2796 GET_OR_DISTINCT(DIExpression, 2797 (Context, makeArrayRef(Record).slice(1))), 2798 NextMetadataNo++); 2799 break; 2800 } 2801 case bitc::METADATA_OBJC_PROPERTY: { 2802 if (Record.size() != 8) 2803 return error("Invalid record"); 2804 2805 IsDistinct = Record[0]; 2806 MetadataList.assignValue( 2807 GET_OR_DISTINCT(DIObjCProperty, 2808 (Context, getMDString(Record[1]), 2809 getMDOrNull(Record[2]), Record[3], 2810 getMDString(Record[4]), getMDString(Record[5]), 2811 Record[6], getDITypeRefOrNull(Record[7]))), 2812 NextMetadataNo++); 2813 break; 2814 } 2815 case bitc::METADATA_IMPORTED_ENTITY: { 2816 if (Record.size() != 6) 2817 return error("Invalid record"); 2818 2819 IsDistinct = Record[0]; 2820 MetadataList.assignValue( 2821 GET_OR_DISTINCT(DIImportedEntity, 2822 (Context, Record[1], getMDOrNull(Record[2]), 2823 getDITypeRefOrNull(Record[3]), Record[4], 2824 getMDString(Record[5]))), 2825 NextMetadataNo++); 2826 break; 2827 } 2828 case bitc::METADATA_STRING_OLD: { 2829 std::string String(Record.begin(), Record.end()); 2830 2831 // Test for upgrading !llvm.loop. 2832 HasSeenOldLoopTags |= mayBeOldLoopAttachmentTag(String); 2833 2834 Metadata *MD = MDString::get(Context, String); 2835 MetadataList.assignValue(MD, NextMetadataNo++); 2836 break; 2837 } 2838 case bitc::METADATA_STRINGS: 2839 if (std::error_code EC = 2840 parseMetadataStrings(Record, Blob, NextMetadataNo)) 2841 return EC; 2842 break; 2843 case bitc::METADATA_GLOBAL_DECL_ATTACHMENT: { 2844 if (Record.size() % 2 == 0) 2845 return error("Invalid record"); 2846 unsigned ValueID = Record[0]; 2847 if (ValueID >= ValueList.size()) 2848 return error("Invalid record"); 2849 if (auto *GO = dyn_cast<GlobalObject>(ValueList[ValueID])) 2850 parseGlobalObjectAttachment(*GO, ArrayRef<uint64_t>(Record).slice(1)); 2851 break; 2852 } 2853 case bitc::METADATA_KIND: { 2854 // Support older bitcode files that had METADATA_KIND records in a 2855 // block with METADATA_BLOCK_ID. 2856 if (std::error_code EC = parseMetadataKindRecord(Record)) 2857 return EC; 2858 break; 2859 } 2860 } 2861 } 2862 2863 #undef GET_OR_DISTINCT 2864 } 2865 2866 /// Parse the metadata kinds out of the METADATA_KIND_BLOCK. 2867 std::error_code BitcodeReader::parseMetadataKinds() { 2868 if (Stream.EnterSubBlock(bitc::METADATA_KIND_BLOCK_ID)) 2869 return error("Invalid record"); 2870 2871 SmallVector<uint64_t, 64> Record; 2872 2873 // Read all the records. 2874 while (true) { 2875 BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 2876 2877 switch (Entry.Kind) { 2878 case BitstreamEntry::SubBlock: // Handled for us already. 2879 case BitstreamEntry::Error: 2880 return error("Malformed block"); 2881 case BitstreamEntry::EndBlock: 2882 return std::error_code(); 2883 case BitstreamEntry::Record: 2884 // The interesting case. 2885 break; 2886 } 2887 2888 // Read a record. 2889 Record.clear(); 2890 unsigned Code = Stream.readRecord(Entry.ID, Record); 2891 switch (Code) { 2892 default: // Default behavior: ignore. 2893 break; 2894 case bitc::METADATA_KIND: { 2895 if (std::error_code EC = parseMetadataKindRecord(Record)) 2896 return EC; 2897 break; 2898 } 2899 } 2900 } 2901 } 2902 2903 /// Decode a signed value stored with the sign bit in the LSB for dense VBR 2904 /// encoding. 2905 uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) { 2906 if ((V & 1) == 0) 2907 return V >> 1; 2908 if (V != 1) 2909 return -(V >> 1); 2910 // There is no such thing as -0 with integers. "-0" really means MININT. 2911 return 1ULL << 63; 2912 } 2913 2914 /// Resolve all of the initializers for global values and aliases that we can. 2915 std::error_code BitcodeReader::resolveGlobalAndIndirectSymbolInits() { 2916 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist; 2917 std::vector<std::pair<GlobalIndirectSymbol*, unsigned> > 2918 IndirectSymbolInitWorklist; 2919 std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist; 2920 std::vector<std::pair<Function*, unsigned> > FunctionPrologueWorklist; 2921 std::vector<std::pair<Function*, unsigned> > FunctionPersonalityFnWorklist; 2922 2923 GlobalInitWorklist.swap(GlobalInits); 2924 IndirectSymbolInitWorklist.swap(IndirectSymbolInits); 2925 FunctionPrefixWorklist.swap(FunctionPrefixes); 2926 FunctionPrologueWorklist.swap(FunctionPrologues); 2927 FunctionPersonalityFnWorklist.swap(FunctionPersonalityFns); 2928 2929 while (!GlobalInitWorklist.empty()) { 2930 unsigned ValID = GlobalInitWorklist.back().second; 2931 if (ValID >= ValueList.size()) { 2932 // Not ready to resolve this yet, it requires something later in the file. 2933 GlobalInits.push_back(GlobalInitWorklist.back()); 2934 } else { 2935 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID])) 2936 GlobalInitWorklist.back().first->setInitializer(C); 2937 else 2938 return error("Expected a constant"); 2939 } 2940 GlobalInitWorklist.pop_back(); 2941 } 2942 2943 while (!IndirectSymbolInitWorklist.empty()) { 2944 unsigned ValID = IndirectSymbolInitWorklist.back().second; 2945 if (ValID >= ValueList.size()) { 2946 IndirectSymbolInits.push_back(IndirectSymbolInitWorklist.back()); 2947 } else { 2948 Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]); 2949 if (!C) 2950 return error("Expected a constant"); 2951 GlobalIndirectSymbol *GIS = IndirectSymbolInitWorklist.back().first; 2952 if (isa<GlobalAlias>(GIS) && C->getType() != GIS->getType()) 2953 return error("Alias and aliasee types don't match"); 2954 GIS->setIndirectSymbol(C); 2955 } 2956 IndirectSymbolInitWorklist.pop_back(); 2957 } 2958 2959 while (!FunctionPrefixWorklist.empty()) { 2960 unsigned ValID = FunctionPrefixWorklist.back().second; 2961 if (ValID >= ValueList.size()) { 2962 FunctionPrefixes.push_back(FunctionPrefixWorklist.back()); 2963 } else { 2964 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID])) 2965 FunctionPrefixWorklist.back().first->setPrefixData(C); 2966 else 2967 return error("Expected a constant"); 2968 } 2969 FunctionPrefixWorklist.pop_back(); 2970 } 2971 2972 while (!FunctionPrologueWorklist.empty()) { 2973 unsigned ValID = FunctionPrologueWorklist.back().second; 2974 if (ValID >= ValueList.size()) { 2975 FunctionPrologues.push_back(FunctionPrologueWorklist.back()); 2976 } else { 2977 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID])) 2978 FunctionPrologueWorklist.back().first->setPrologueData(C); 2979 else 2980 return error("Expected a constant"); 2981 } 2982 FunctionPrologueWorklist.pop_back(); 2983 } 2984 2985 while (!FunctionPersonalityFnWorklist.empty()) { 2986 unsigned ValID = FunctionPersonalityFnWorklist.back().second; 2987 if (ValID >= ValueList.size()) { 2988 FunctionPersonalityFns.push_back(FunctionPersonalityFnWorklist.back()); 2989 } else { 2990 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID])) 2991 FunctionPersonalityFnWorklist.back().first->setPersonalityFn(C); 2992 else 2993 return error("Expected a constant"); 2994 } 2995 FunctionPersonalityFnWorklist.pop_back(); 2996 } 2997 2998 return std::error_code(); 2999 } 3000 3001 static APInt readWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) { 3002 SmallVector<uint64_t, 8> Words(Vals.size()); 3003 transform(Vals, Words.begin(), 3004 BitcodeReader::decodeSignRotatedValue); 3005 3006 return APInt(TypeBits, Words); 3007 } 3008 3009 std::error_code BitcodeReader::parseConstants() { 3010 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID)) 3011 return error("Invalid record"); 3012 3013 SmallVector<uint64_t, 64> Record; 3014 3015 // Read all the records for this value table. 3016 Type *CurTy = Type::getInt32Ty(Context); 3017 unsigned NextCstNo = ValueList.size(); 3018 3019 while (true) { 3020 BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 3021 3022 switch (Entry.Kind) { 3023 case BitstreamEntry::SubBlock: // Handled for us already. 3024 case BitstreamEntry::Error: 3025 return error("Malformed block"); 3026 case BitstreamEntry::EndBlock: 3027 if (NextCstNo != ValueList.size()) 3028 return error("Invalid constant reference"); 3029 3030 // Once all the constants have been read, go through and resolve forward 3031 // references. 3032 ValueList.resolveConstantForwardRefs(); 3033 return std::error_code(); 3034 case BitstreamEntry::Record: 3035 // The interesting case. 3036 break; 3037 } 3038 3039 // Read a record. 3040 Record.clear(); 3041 Type *VoidType = Type::getVoidTy(Context); 3042 Value *V = nullptr; 3043 unsigned BitCode = Stream.readRecord(Entry.ID, Record); 3044 switch (BitCode) { 3045 default: // Default behavior: unknown constant 3046 case bitc::CST_CODE_UNDEF: // UNDEF 3047 V = UndefValue::get(CurTy); 3048 break; 3049 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid] 3050 if (Record.empty()) 3051 return error("Invalid record"); 3052 if (Record[0] >= TypeList.size() || !TypeList[Record[0]]) 3053 return error("Invalid record"); 3054 if (TypeList[Record[0]] == VoidType) 3055 return error("Invalid constant type"); 3056 CurTy = TypeList[Record[0]]; 3057 continue; // Skip the ValueList manipulation. 3058 case bitc::CST_CODE_NULL: // NULL 3059 V = Constant::getNullValue(CurTy); 3060 break; 3061 case bitc::CST_CODE_INTEGER: // INTEGER: [intval] 3062 if (!CurTy->isIntegerTy() || Record.empty()) 3063 return error("Invalid record"); 3064 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0])); 3065 break; 3066 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval] 3067 if (!CurTy->isIntegerTy() || Record.empty()) 3068 return error("Invalid record"); 3069 3070 APInt VInt = 3071 readWideAPInt(Record, cast<IntegerType>(CurTy)->getBitWidth()); 3072 V = ConstantInt::get(Context, VInt); 3073 3074 break; 3075 } 3076 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval] 3077 if (Record.empty()) 3078 return error("Invalid record"); 3079 if (CurTy->isHalfTy()) 3080 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf, 3081 APInt(16, (uint16_t)Record[0]))); 3082 else if (CurTy->isFloatTy()) 3083 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle, 3084 APInt(32, (uint32_t)Record[0]))); 3085 else if (CurTy->isDoubleTy()) 3086 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble, 3087 APInt(64, Record[0]))); 3088 else if (CurTy->isX86_FP80Ty()) { 3089 // Bits are not stored the same way as a normal i80 APInt, compensate. 3090 uint64_t Rearrange[2]; 3091 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16); 3092 Rearrange[1] = Record[0] >> 48; 3093 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended, 3094 APInt(80, Rearrange))); 3095 } else if (CurTy->isFP128Ty()) 3096 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad, 3097 APInt(128, Record))); 3098 else if (CurTy->isPPC_FP128Ty()) 3099 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble, 3100 APInt(128, Record))); 3101 else 3102 V = UndefValue::get(CurTy); 3103 break; 3104 } 3105 3106 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number] 3107 if (Record.empty()) 3108 return error("Invalid record"); 3109 3110 unsigned Size = Record.size(); 3111 SmallVector<Constant*, 16> Elts; 3112 3113 if (StructType *STy = dyn_cast<StructType>(CurTy)) { 3114 for (unsigned i = 0; i != Size; ++i) 3115 Elts.push_back(ValueList.getConstantFwdRef(Record[i], 3116 STy->getElementType(i))); 3117 V = ConstantStruct::get(STy, Elts); 3118 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) { 3119 Type *EltTy = ATy->getElementType(); 3120 for (unsigned i = 0; i != Size; ++i) 3121 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy)); 3122 V = ConstantArray::get(ATy, Elts); 3123 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) { 3124 Type *EltTy = VTy->getElementType(); 3125 for (unsigned i = 0; i != Size; ++i) 3126 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy)); 3127 V = ConstantVector::get(Elts); 3128 } else { 3129 V = UndefValue::get(CurTy); 3130 } 3131 break; 3132 } 3133 case bitc::CST_CODE_STRING: // STRING: [values] 3134 case bitc::CST_CODE_CSTRING: { // CSTRING: [values] 3135 if (Record.empty()) 3136 return error("Invalid record"); 3137 3138 SmallString<16> Elts(Record.begin(), Record.end()); 3139 V = ConstantDataArray::getString(Context, Elts, 3140 BitCode == bitc::CST_CODE_CSTRING); 3141 break; 3142 } 3143 case bitc::CST_CODE_DATA: {// DATA: [n x value] 3144 if (Record.empty()) 3145 return error("Invalid record"); 3146 3147 Type *EltTy = cast<SequentialType>(CurTy)->getElementType(); 3148 if (EltTy->isIntegerTy(8)) { 3149 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end()); 3150 if (isa<VectorType>(CurTy)) 3151 V = ConstantDataVector::get(Context, Elts); 3152 else 3153 V = ConstantDataArray::get(Context, Elts); 3154 } else if (EltTy->isIntegerTy(16)) { 3155 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end()); 3156 if (isa<VectorType>(CurTy)) 3157 V = ConstantDataVector::get(Context, Elts); 3158 else 3159 V = ConstantDataArray::get(Context, Elts); 3160 } else if (EltTy->isIntegerTy(32)) { 3161 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end()); 3162 if (isa<VectorType>(CurTy)) 3163 V = ConstantDataVector::get(Context, Elts); 3164 else 3165 V = ConstantDataArray::get(Context, Elts); 3166 } else if (EltTy->isIntegerTy(64)) { 3167 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end()); 3168 if (isa<VectorType>(CurTy)) 3169 V = ConstantDataVector::get(Context, Elts); 3170 else 3171 V = ConstantDataArray::get(Context, Elts); 3172 } else if (EltTy->isHalfTy()) { 3173 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end()); 3174 if (isa<VectorType>(CurTy)) 3175 V = ConstantDataVector::getFP(Context, Elts); 3176 else 3177 V = ConstantDataArray::getFP(Context, Elts); 3178 } else if (EltTy->isFloatTy()) { 3179 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end()); 3180 if (isa<VectorType>(CurTy)) 3181 V = ConstantDataVector::getFP(Context, Elts); 3182 else 3183 V = ConstantDataArray::getFP(Context, Elts); 3184 } else if (EltTy->isDoubleTy()) { 3185 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end()); 3186 if (isa<VectorType>(CurTy)) 3187 V = ConstantDataVector::getFP(Context, Elts); 3188 else 3189 V = ConstantDataArray::getFP(Context, Elts); 3190 } else { 3191 return error("Invalid type for value"); 3192 } 3193 break; 3194 } 3195 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval] 3196 if (Record.size() < 3) 3197 return error("Invalid record"); 3198 int Opc = getDecodedBinaryOpcode(Record[0], CurTy); 3199 if (Opc < 0) { 3200 V = UndefValue::get(CurTy); // Unknown binop. 3201 } else { 3202 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy); 3203 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy); 3204 unsigned Flags = 0; 3205 if (Record.size() >= 4) { 3206 if (Opc == Instruction::Add || 3207 Opc == Instruction::Sub || 3208 Opc == Instruction::Mul || 3209 Opc == Instruction::Shl) { 3210 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP)) 3211 Flags |= OverflowingBinaryOperator::NoSignedWrap; 3212 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP)) 3213 Flags |= OverflowingBinaryOperator::NoUnsignedWrap; 3214 } else if (Opc == Instruction::SDiv || 3215 Opc == Instruction::UDiv || 3216 Opc == Instruction::LShr || 3217 Opc == Instruction::AShr) { 3218 if (Record[3] & (1 << bitc::PEO_EXACT)) 3219 Flags |= SDivOperator::IsExact; 3220 } 3221 } 3222 V = ConstantExpr::get(Opc, LHS, RHS, Flags); 3223 } 3224 break; 3225 } 3226 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval] 3227 if (Record.size() < 3) 3228 return error("Invalid record"); 3229 int Opc = getDecodedCastOpcode(Record[0]); 3230 if (Opc < 0) { 3231 V = UndefValue::get(CurTy); // Unknown cast. 3232 } else { 3233 Type *OpTy = getTypeByID(Record[1]); 3234 if (!OpTy) 3235 return error("Invalid record"); 3236 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy); 3237 V = UpgradeBitCastExpr(Opc, Op, CurTy); 3238 if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy); 3239 } 3240 break; 3241 } 3242 case bitc::CST_CODE_CE_INBOUNDS_GEP: 3243 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands] 3244 unsigned OpNum = 0; 3245 Type *PointeeType = nullptr; 3246 if (Record.size() % 2) 3247 PointeeType = getTypeByID(Record[OpNum++]); 3248 SmallVector<Constant*, 16> Elts; 3249 while (OpNum != Record.size()) { 3250 Type *ElTy = getTypeByID(Record[OpNum++]); 3251 if (!ElTy) 3252 return error("Invalid record"); 3253 Elts.push_back(ValueList.getConstantFwdRef(Record[OpNum++], ElTy)); 3254 } 3255 3256 if (PointeeType && 3257 PointeeType != 3258 cast<SequentialType>(Elts[0]->getType()->getScalarType()) 3259 ->getElementType()) 3260 return error("Explicit gep operator type does not match pointee type " 3261 "of pointer operand"); 3262 3263 if (Elts.size() < 1) 3264 return error("Invalid gep with no operands"); 3265 3266 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end()); 3267 V = ConstantExpr::getGetElementPtr(PointeeType, Elts[0], Indices, 3268 BitCode == 3269 bitc::CST_CODE_CE_INBOUNDS_GEP); 3270 break; 3271 } 3272 case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#] 3273 if (Record.size() < 3) 3274 return error("Invalid record"); 3275 3276 Type *SelectorTy = Type::getInt1Ty(Context); 3277 3278 // The selector might be an i1 or an <n x i1> 3279 // Get the type from the ValueList before getting a forward ref. 3280 if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) 3281 if (Value *V = ValueList[Record[0]]) 3282 if (SelectorTy != V->getType()) 3283 SelectorTy = VectorType::get(SelectorTy, VTy->getNumElements()); 3284 3285 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0], 3286 SelectorTy), 3287 ValueList.getConstantFwdRef(Record[1],CurTy), 3288 ValueList.getConstantFwdRef(Record[2],CurTy)); 3289 break; 3290 } 3291 case bitc::CST_CODE_CE_EXTRACTELT 3292 : { // CE_EXTRACTELT: [opty, opval, opty, opval] 3293 if (Record.size() < 3) 3294 return error("Invalid record"); 3295 VectorType *OpTy = 3296 dyn_cast_or_null<VectorType>(getTypeByID(Record[0])); 3297 if (!OpTy) 3298 return error("Invalid record"); 3299 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy); 3300 Constant *Op1 = nullptr; 3301 if (Record.size() == 4) { 3302 Type *IdxTy = getTypeByID(Record[2]); 3303 if (!IdxTy) 3304 return error("Invalid record"); 3305 Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy); 3306 } else // TODO: Remove with llvm 4.0 3307 Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context)); 3308 if (!Op1) 3309 return error("Invalid record"); 3310 V = ConstantExpr::getExtractElement(Op0, Op1); 3311 break; 3312 } 3313 case bitc::CST_CODE_CE_INSERTELT 3314 : { // CE_INSERTELT: [opval, opval, opty, opval] 3315 VectorType *OpTy = dyn_cast<VectorType>(CurTy); 3316 if (Record.size() < 3 || !OpTy) 3317 return error("Invalid record"); 3318 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy); 3319 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], 3320 OpTy->getElementType()); 3321 Constant *Op2 = nullptr; 3322 if (Record.size() == 4) { 3323 Type *IdxTy = getTypeByID(Record[2]); 3324 if (!IdxTy) 3325 return error("Invalid record"); 3326 Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy); 3327 } else // TODO: Remove with llvm 4.0 3328 Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context)); 3329 if (!Op2) 3330 return error("Invalid record"); 3331 V = ConstantExpr::getInsertElement(Op0, Op1, Op2); 3332 break; 3333 } 3334 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval] 3335 VectorType *OpTy = dyn_cast<VectorType>(CurTy); 3336 if (Record.size() < 3 || !OpTy) 3337 return error("Invalid record"); 3338 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy); 3339 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy); 3340 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context), 3341 OpTy->getNumElements()); 3342 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy); 3343 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2); 3344 break; 3345 } 3346 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval] 3347 VectorType *RTy = dyn_cast<VectorType>(CurTy); 3348 VectorType *OpTy = 3349 dyn_cast_or_null<VectorType>(getTypeByID(Record[0])); 3350 if (Record.size() < 4 || !RTy || !OpTy) 3351 return error("Invalid record"); 3352 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy); 3353 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy); 3354 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context), 3355 RTy->getNumElements()); 3356 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy); 3357 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2); 3358 break; 3359 } 3360 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred] 3361 if (Record.size() < 4) 3362 return error("Invalid record"); 3363 Type *OpTy = getTypeByID(Record[0]); 3364 if (!OpTy) 3365 return error("Invalid record"); 3366 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy); 3367 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy); 3368 3369 if (OpTy->isFPOrFPVectorTy()) 3370 V = ConstantExpr::getFCmp(Record[3], Op0, Op1); 3371 else 3372 V = ConstantExpr::getICmp(Record[3], Op0, Op1); 3373 break; 3374 } 3375 // This maintains backward compatibility, pre-asm dialect keywords. 3376 // FIXME: Remove with the 4.0 release. 3377 case bitc::CST_CODE_INLINEASM_OLD: { 3378 if (Record.size() < 2) 3379 return error("Invalid record"); 3380 std::string AsmStr, ConstrStr; 3381 bool HasSideEffects = Record[0] & 1; 3382 bool IsAlignStack = Record[0] >> 1; 3383 unsigned AsmStrSize = Record[1]; 3384 if (2+AsmStrSize >= Record.size()) 3385 return error("Invalid record"); 3386 unsigned ConstStrSize = Record[2+AsmStrSize]; 3387 if (3+AsmStrSize+ConstStrSize > Record.size()) 3388 return error("Invalid record"); 3389 3390 for (unsigned i = 0; i != AsmStrSize; ++i) 3391 AsmStr += (char)Record[2+i]; 3392 for (unsigned i = 0; i != ConstStrSize; ++i) 3393 ConstrStr += (char)Record[3+AsmStrSize+i]; 3394 PointerType *PTy = cast<PointerType>(CurTy); 3395 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()), 3396 AsmStr, ConstrStr, HasSideEffects, IsAlignStack); 3397 break; 3398 } 3399 // This version adds support for the asm dialect keywords (e.g., 3400 // inteldialect). 3401 case bitc::CST_CODE_INLINEASM: { 3402 if (Record.size() < 2) 3403 return error("Invalid record"); 3404 std::string AsmStr, ConstrStr; 3405 bool HasSideEffects = Record[0] & 1; 3406 bool IsAlignStack = (Record[0] >> 1) & 1; 3407 unsigned AsmDialect = Record[0] >> 2; 3408 unsigned AsmStrSize = Record[1]; 3409 if (2+AsmStrSize >= Record.size()) 3410 return error("Invalid record"); 3411 unsigned ConstStrSize = Record[2+AsmStrSize]; 3412 if (3+AsmStrSize+ConstStrSize > Record.size()) 3413 return error("Invalid record"); 3414 3415 for (unsigned i = 0; i != AsmStrSize; ++i) 3416 AsmStr += (char)Record[2+i]; 3417 for (unsigned i = 0; i != ConstStrSize; ++i) 3418 ConstrStr += (char)Record[3+AsmStrSize+i]; 3419 PointerType *PTy = cast<PointerType>(CurTy); 3420 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()), 3421 AsmStr, ConstrStr, HasSideEffects, IsAlignStack, 3422 InlineAsm::AsmDialect(AsmDialect)); 3423 break; 3424 } 3425 case bitc::CST_CODE_BLOCKADDRESS:{ 3426 if (Record.size() < 3) 3427 return error("Invalid record"); 3428 Type *FnTy = getTypeByID(Record[0]); 3429 if (!FnTy) 3430 return error("Invalid record"); 3431 Function *Fn = 3432 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy)); 3433 if (!Fn) 3434 return error("Invalid record"); 3435 3436 // If the function is already parsed we can insert the block address right 3437 // away. 3438 BasicBlock *BB; 3439 unsigned BBID = Record[2]; 3440 if (!BBID) 3441 // Invalid reference to entry block. 3442 return error("Invalid ID"); 3443 if (!Fn->empty()) { 3444 Function::iterator BBI = Fn->begin(), BBE = Fn->end(); 3445 for (size_t I = 0, E = BBID; I != E; ++I) { 3446 if (BBI == BBE) 3447 return error("Invalid ID"); 3448 ++BBI; 3449 } 3450 BB = &*BBI; 3451 } else { 3452 // Otherwise insert a placeholder and remember it so it can be inserted 3453 // when the function is parsed. 3454 auto &FwdBBs = BasicBlockFwdRefs[Fn]; 3455 if (FwdBBs.empty()) 3456 BasicBlockFwdRefQueue.push_back(Fn); 3457 if (FwdBBs.size() < BBID + 1) 3458 FwdBBs.resize(BBID + 1); 3459 if (!FwdBBs[BBID]) 3460 FwdBBs[BBID] = BasicBlock::Create(Context); 3461 BB = FwdBBs[BBID]; 3462 } 3463 V = BlockAddress::get(Fn, BB); 3464 break; 3465 } 3466 } 3467 3468 ValueList.assignValue(V, NextCstNo); 3469 ++NextCstNo; 3470 } 3471 } 3472 3473 std::error_code BitcodeReader::parseUseLists() { 3474 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID)) 3475 return error("Invalid record"); 3476 3477 // Read all the records. 3478 SmallVector<uint64_t, 64> Record; 3479 3480 while (true) { 3481 BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 3482 3483 switch (Entry.Kind) { 3484 case BitstreamEntry::SubBlock: // Handled for us already. 3485 case BitstreamEntry::Error: 3486 return error("Malformed block"); 3487 case BitstreamEntry::EndBlock: 3488 return std::error_code(); 3489 case BitstreamEntry::Record: 3490 // The interesting case. 3491 break; 3492 } 3493 3494 // Read a use list record. 3495 Record.clear(); 3496 bool IsBB = false; 3497 switch (Stream.readRecord(Entry.ID, Record)) { 3498 default: // Default behavior: unknown type. 3499 break; 3500 case bitc::USELIST_CODE_BB: 3501 IsBB = true; 3502 LLVM_FALLTHROUGH; 3503 case bitc::USELIST_CODE_DEFAULT: { 3504 unsigned RecordLength = Record.size(); 3505 if (RecordLength < 3) 3506 // Records should have at least an ID and two indexes. 3507 return error("Invalid record"); 3508 unsigned ID = Record.back(); 3509 Record.pop_back(); 3510 3511 Value *V; 3512 if (IsBB) { 3513 assert(ID < FunctionBBs.size() && "Basic block not found"); 3514 V = FunctionBBs[ID]; 3515 } else 3516 V = ValueList[ID]; 3517 unsigned NumUses = 0; 3518 SmallDenseMap<const Use *, unsigned, 16> Order; 3519 for (const Use &U : V->materialized_uses()) { 3520 if (++NumUses > Record.size()) 3521 break; 3522 Order[&U] = Record[NumUses - 1]; 3523 } 3524 if (Order.size() != Record.size() || NumUses > Record.size()) 3525 // Mismatches can happen if the functions are being materialized lazily 3526 // (out-of-order), or a value has been upgraded. 3527 break; 3528 3529 V->sortUseList([&](const Use &L, const Use &R) { 3530 return Order.lookup(&L) < Order.lookup(&R); 3531 }); 3532 break; 3533 } 3534 } 3535 } 3536 } 3537 3538 /// When we see the block for metadata, remember where it is and then skip it. 3539 /// This lets us lazily deserialize the metadata. 3540 std::error_code BitcodeReader::rememberAndSkipMetadata() { 3541 // Save the current stream state. 3542 uint64_t CurBit = Stream.GetCurrentBitNo(); 3543 DeferredMetadataInfo.push_back(CurBit); 3544 3545 // Skip over the block for now. 3546 if (Stream.SkipBlock()) 3547 return error("Invalid record"); 3548 return std::error_code(); 3549 } 3550 3551 std::error_code BitcodeReader::materializeMetadata() { 3552 for (uint64_t BitPos : DeferredMetadataInfo) { 3553 // Move the bit stream to the saved position. 3554 Stream.JumpToBit(BitPos); 3555 if (std::error_code EC = parseMetadata(true)) 3556 return EC; 3557 } 3558 DeferredMetadataInfo.clear(); 3559 return std::error_code(); 3560 } 3561 3562 void BitcodeReader::setStripDebugInfo() { StripDebugInfo = true; } 3563 3564 /// When we see the block for a function body, remember where it is and then 3565 /// skip it. This lets us lazily deserialize the functions. 3566 std::error_code BitcodeReader::rememberAndSkipFunctionBody() { 3567 // Get the function we are talking about. 3568 if (FunctionsWithBodies.empty()) 3569 return error("Insufficient function protos"); 3570 3571 Function *Fn = FunctionsWithBodies.back(); 3572 FunctionsWithBodies.pop_back(); 3573 3574 // Save the current stream state. 3575 uint64_t CurBit = Stream.GetCurrentBitNo(); 3576 assert( 3577 (DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo[Fn] == CurBit) && 3578 "Mismatch between VST and scanned function offsets"); 3579 DeferredFunctionInfo[Fn] = CurBit; 3580 3581 // Skip over the function block for now. 3582 if (Stream.SkipBlock()) 3583 return error("Invalid record"); 3584 return std::error_code(); 3585 } 3586 3587 std::error_code BitcodeReader::globalCleanup() { 3588 // Patch the initializers for globals and aliases up. 3589 resolveGlobalAndIndirectSymbolInits(); 3590 if (!GlobalInits.empty() || !IndirectSymbolInits.empty()) 3591 return error("Malformed global initializer set"); 3592 3593 // Look for intrinsic functions which need to be upgraded at some point 3594 for (Function &F : *TheModule) { 3595 Function *NewFn; 3596 if (UpgradeIntrinsicFunction(&F, NewFn)) 3597 UpgradedIntrinsics[&F] = NewFn; 3598 else if (auto Remangled = Intrinsic::remangleIntrinsicFunction(&F)) 3599 // Some types could be renamed during loading if several modules are 3600 // loaded in the same LLVMContext (LTO scenario). In this case we should 3601 // remangle intrinsics names as well. 3602 RemangledIntrinsics[&F] = Remangled.getValue(); 3603 } 3604 3605 // Look for global variables which need to be renamed. 3606 for (GlobalVariable &GV : TheModule->globals()) 3607 UpgradeGlobalVariable(&GV); 3608 3609 // Force deallocation of memory for these vectors to favor the client that 3610 // want lazy deserialization. 3611 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits); 3612 std::vector<std::pair<GlobalIndirectSymbol*, unsigned> >().swap( 3613 IndirectSymbolInits); 3614 return std::error_code(); 3615 } 3616 3617 /// Support for lazy parsing of function bodies. This is required if we 3618 /// either have an old bitcode file without a VST forward declaration record, 3619 /// or if we have an anonymous function being materialized, since anonymous 3620 /// functions do not have a name and are therefore not in the VST. 3621 std::error_code BitcodeReader::rememberAndSkipFunctionBodies() { 3622 Stream.JumpToBit(NextUnreadBit); 3623 3624 if (Stream.AtEndOfStream()) 3625 return error("Could not find function in stream"); 3626 3627 if (!SeenFirstFunctionBody) 3628 return error("Trying to materialize functions before seeing function blocks"); 3629 3630 // An old bitcode file with the symbol table at the end would have 3631 // finished the parse greedily. 3632 assert(SeenValueSymbolTable); 3633 3634 SmallVector<uint64_t, 64> Record; 3635 3636 while (true) { 3637 BitstreamEntry Entry = Stream.advance(); 3638 switch (Entry.Kind) { 3639 default: 3640 return error("Expect SubBlock"); 3641 case BitstreamEntry::SubBlock: 3642 switch (Entry.ID) { 3643 default: 3644 return error("Expect function block"); 3645 case bitc::FUNCTION_BLOCK_ID: 3646 if (std::error_code EC = rememberAndSkipFunctionBody()) 3647 return EC; 3648 NextUnreadBit = Stream.GetCurrentBitNo(); 3649 return std::error_code(); 3650 } 3651 } 3652 } 3653 } 3654 3655 std::error_code BitcodeReader::parseBitcodeVersion() { 3656 if (Stream.EnterSubBlock(bitc::IDENTIFICATION_BLOCK_ID)) 3657 return error("Invalid record"); 3658 3659 // Read all the records. 3660 SmallVector<uint64_t, 64> Record; 3661 3662 while (true) { 3663 BitstreamEntry Entry = Stream.advance(); 3664 3665 switch (Entry.Kind) { 3666 default: 3667 case BitstreamEntry::Error: 3668 return error("Malformed block"); 3669 case BitstreamEntry::EndBlock: 3670 return std::error_code(); 3671 case BitstreamEntry::Record: 3672 // The interesting case. 3673 break; 3674 } 3675 3676 // Read a record. 3677 Record.clear(); 3678 unsigned BitCode = Stream.readRecord(Entry.ID, Record); 3679 switch (BitCode) { 3680 default: // Default behavior: reject 3681 return error("Invalid value"); 3682 case bitc::IDENTIFICATION_CODE_STRING: { // IDENTIFICATION: [strchr x 3683 // N] 3684 convertToString(Record, 0, ProducerIdentification); 3685 break; 3686 } 3687 case bitc::IDENTIFICATION_CODE_EPOCH: { // EPOCH: [epoch#] 3688 unsigned epoch = (unsigned)Record[0]; 3689 if (epoch != bitc::BITCODE_CURRENT_EPOCH) { 3690 return error( 3691 Twine("Incompatible epoch: Bitcode '") + Twine(epoch) + 3692 "' vs current: '" + Twine(bitc::BITCODE_CURRENT_EPOCH) + "'"); 3693 } 3694 } 3695 } 3696 } 3697 } 3698 3699 std::error_code BitcodeReader::parseModule(uint64_t ResumeBit, 3700 bool ShouldLazyLoadMetadata) { 3701 if (ResumeBit) 3702 Stream.JumpToBit(ResumeBit); 3703 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID)) 3704 return error("Invalid record"); 3705 3706 SmallVector<uint64_t, 64> Record; 3707 std::vector<std::string> SectionTable; 3708 std::vector<std::string> GCTable; 3709 3710 // Read all the records for this module. 3711 while (true) { 3712 BitstreamEntry Entry = Stream.advance(); 3713 3714 switch (Entry.Kind) { 3715 case BitstreamEntry::Error: 3716 return error("Malformed block"); 3717 case BitstreamEntry::EndBlock: 3718 return globalCleanup(); 3719 3720 case BitstreamEntry::SubBlock: 3721 switch (Entry.ID) { 3722 default: // Skip unknown content. 3723 if (Stream.SkipBlock()) 3724 return error("Invalid record"); 3725 break; 3726 case bitc::BLOCKINFO_BLOCK_ID: 3727 if (Stream.ReadBlockInfoBlock()) 3728 return error("Malformed block"); 3729 break; 3730 case bitc::PARAMATTR_BLOCK_ID: 3731 if (std::error_code EC = parseAttributeBlock()) 3732 return EC; 3733 break; 3734 case bitc::PARAMATTR_GROUP_BLOCK_ID: 3735 if (std::error_code EC = parseAttributeGroupBlock()) 3736 return EC; 3737 break; 3738 case bitc::TYPE_BLOCK_ID_NEW: 3739 if (std::error_code EC = parseTypeTable()) 3740 return EC; 3741 break; 3742 case bitc::VALUE_SYMTAB_BLOCK_ID: 3743 if (!SeenValueSymbolTable) { 3744 // Either this is an old form VST without function index and an 3745 // associated VST forward declaration record (which would have caused 3746 // the VST to be jumped to and parsed before it was encountered 3747 // normally in the stream), or there were no function blocks to 3748 // trigger an earlier parsing of the VST. 3749 assert(VSTOffset == 0 || FunctionsWithBodies.empty()); 3750 if (std::error_code EC = parseValueSymbolTable()) 3751 return EC; 3752 SeenValueSymbolTable = true; 3753 } else { 3754 // We must have had a VST forward declaration record, which caused 3755 // the parser to jump to and parse the VST earlier. 3756 assert(VSTOffset > 0); 3757 if (Stream.SkipBlock()) 3758 return error("Invalid record"); 3759 } 3760 break; 3761 case bitc::CONSTANTS_BLOCK_ID: 3762 if (std::error_code EC = parseConstants()) 3763 return EC; 3764 if (std::error_code EC = resolveGlobalAndIndirectSymbolInits()) 3765 return EC; 3766 break; 3767 case bitc::METADATA_BLOCK_ID: 3768 if (ShouldLazyLoadMetadata && !IsMetadataMaterialized) { 3769 if (std::error_code EC = rememberAndSkipMetadata()) 3770 return EC; 3771 break; 3772 } 3773 assert(DeferredMetadataInfo.empty() && "Unexpected deferred metadata"); 3774 if (std::error_code EC = parseMetadata(true)) 3775 return EC; 3776 break; 3777 case bitc::METADATA_KIND_BLOCK_ID: 3778 if (std::error_code EC = parseMetadataKinds()) 3779 return EC; 3780 break; 3781 case bitc::FUNCTION_BLOCK_ID: 3782 // If this is the first function body we've seen, reverse the 3783 // FunctionsWithBodies list. 3784 if (!SeenFirstFunctionBody) { 3785 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end()); 3786 if (std::error_code EC = globalCleanup()) 3787 return EC; 3788 SeenFirstFunctionBody = true; 3789 } 3790 3791 if (VSTOffset > 0) { 3792 // If we have a VST forward declaration record, make sure we 3793 // parse the VST now if we haven't already. It is needed to 3794 // set up the DeferredFunctionInfo vector for lazy reading. 3795 if (!SeenValueSymbolTable) { 3796 if (std::error_code EC = 3797 BitcodeReader::parseValueSymbolTable(VSTOffset)) 3798 return EC; 3799 SeenValueSymbolTable = true; 3800 // Fall through so that we record the NextUnreadBit below. 3801 // This is necessary in case we have an anonymous function that 3802 // is later materialized. Since it will not have a VST entry we 3803 // need to fall back to the lazy parse to find its offset. 3804 } else { 3805 // If we have a VST forward declaration record, but have already 3806 // parsed the VST (just above, when the first function body was 3807 // encountered here), then we are resuming the parse after 3808 // materializing functions. The ResumeBit points to the 3809 // start of the last function block recorded in the 3810 // DeferredFunctionInfo map. Skip it. 3811 if (Stream.SkipBlock()) 3812 return error("Invalid record"); 3813 continue; 3814 } 3815 } 3816 3817 // Support older bitcode files that did not have the function 3818 // index in the VST, nor a VST forward declaration record, as 3819 // well as anonymous functions that do not have VST entries. 3820 // Build the DeferredFunctionInfo vector on the fly. 3821 if (std::error_code EC = rememberAndSkipFunctionBody()) 3822 return EC; 3823 3824 // Suspend parsing when we reach the function bodies. Subsequent 3825 // materialization calls will resume it when necessary. If the bitcode 3826 // file is old, the symbol table will be at the end instead and will not 3827 // have been seen yet. In this case, just finish the parse now. 3828 if (SeenValueSymbolTable) { 3829 NextUnreadBit = Stream.GetCurrentBitNo(); 3830 // After the VST has been parsed, we need to make sure intrinsic name 3831 // are auto-upgraded. 3832 return globalCleanup(); 3833 } 3834 break; 3835 case bitc::USELIST_BLOCK_ID: 3836 if (std::error_code EC = parseUseLists()) 3837 return EC; 3838 break; 3839 case bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID: 3840 if (std::error_code EC = parseOperandBundleTags()) 3841 return EC; 3842 break; 3843 } 3844 continue; 3845 3846 case BitstreamEntry::Record: 3847 // The interesting case. 3848 break; 3849 } 3850 3851 // Read a record. 3852 auto BitCode = Stream.readRecord(Entry.ID, Record); 3853 switch (BitCode) { 3854 default: break; // Default behavior, ignore unknown content. 3855 case bitc::MODULE_CODE_VERSION: { // VERSION: [version#] 3856 if (Record.size() < 1) 3857 return error("Invalid record"); 3858 // Only version #0 and #1 are supported so far. 3859 unsigned module_version = Record[0]; 3860 switch (module_version) { 3861 default: 3862 return error("Invalid value"); 3863 case 0: 3864 UseRelativeIDs = false; 3865 break; 3866 case 1: 3867 UseRelativeIDs = true; 3868 break; 3869 } 3870 break; 3871 } 3872 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N] 3873 std::string S; 3874 if (convertToString(Record, 0, S)) 3875 return error("Invalid record"); 3876 TheModule->setTargetTriple(S); 3877 break; 3878 } 3879 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N] 3880 std::string S; 3881 if (convertToString(Record, 0, S)) 3882 return error("Invalid record"); 3883 TheModule->setDataLayout(S); 3884 break; 3885 } 3886 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N] 3887 std::string S; 3888 if (convertToString(Record, 0, S)) 3889 return error("Invalid record"); 3890 TheModule->setModuleInlineAsm(S); 3891 break; 3892 } 3893 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N] 3894 // FIXME: Remove in 4.0. 3895 std::string S; 3896 if (convertToString(Record, 0, S)) 3897 return error("Invalid record"); 3898 // Ignore value. 3899 break; 3900 } 3901 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N] 3902 std::string S; 3903 if (convertToString(Record, 0, S)) 3904 return error("Invalid record"); 3905 SectionTable.push_back(S); 3906 break; 3907 } 3908 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N] 3909 std::string S; 3910 if (convertToString(Record, 0, S)) 3911 return error("Invalid record"); 3912 GCTable.push_back(S); 3913 break; 3914 } 3915 case bitc::MODULE_CODE_COMDAT: { // COMDAT: [selection_kind, name] 3916 if (Record.size() < 2) 3917 return error("Invalid record"); 3918 Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]); 3919 unsigned ComdatNameSize = Record[1]; 3920 std::string ComdatName; 3921 ComdatName.reserve(ComdatNameSize); 3922 for (unsigned i = 0; i != ComdatNameSize; ++i) 3923 ComdatName += (char)Record[2 + i]; 3924 Comdat *C = TheModule->getOrInsertComdat(ComdatName); 3925 C->setSelectionKind(SK); 3926 ComdatList.push_back(C); 3927 break; 3928 } 3929 // GLOBALVAR: [pointer type, isconst, initid, 3930 // linkage, alignment, section, visibility, threadlocal, 3931 // unnamed_addr, externally_initialized, dllstorageclass, 3932 // comdat] 3933 case bitc::MODULE_CODE_GLOBALVAR: { 3934 if (Record.size() < 6) 3935 return error("Invalid record"); 3936 Type *Ty = getTypeByID(Record[0]); 3937 if (!Ty) 3938 return error("Invalid record"); 3939 bool isConstant = Record[1] & 1; 3940 bool explicitType = Record[1] & 2; 3941 unsigned AddressSpace; 3942 if (explicitType) { 3943 AddressSpace = Record[1] >> 2; 3944 } else { 3945 if (!Ty->isPointerTy()) 3946 return error("Invalid type for value"); 3947 AddressSpace = cast<PointerType>(Ty)->getAddressSpace(); 3948 Ty = cast<PointerType>(Ty)->getElementType(); 3949 } 3950 3951 uint64_t RawLinkage = Record[3]; 3952 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage); 3953 unsigned Alignment; 3954 if (std::error_code EC = parseAlignmentValue(Record[4], Alignment)) 3955 return EC; 3956 std::string Section; 3957 if (Record[5]) { 3958 if (Record[5]-1 >= SectionTable.size()) 3959 return error("Invalid ID"); 3960 Section = SectionTable[Record[5]-1]; 3961 } 3962 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility; 3963 // Local linkage must have default visibility. 3964 if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage)) 3965 // FIXME: Change to an error if non-default in 4.0. 3966 Visibility = getDecodedVisibility(Record[6]); 3967 3968 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal; 3969 if (Record.size() > 7) 3970 TLM = getDecodedThreadLocalMode(Record[7]); 3971 3972 GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None; 3973 if (Record.size() > 8) 3974 UnnamedAddr = getDecodedUnnamedAddrType(Record[8]); 3975 3976 bool ExternallyInitialized = false; 3977 if (Record.size() > 9) 3978 ExternallyInitialized = Record[9]; 3979 3980 GlobalVariable *NewGV = 3981 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, "", nullptr, 3982 TLM, AddressSpace, ExternallyInitialized); 3983 NewGV->setAlignment(Alignment); 3984 if (!Section.empty()) 3985 NewGV->setSection(Section); 3986 NewGV->setVisibility(Visibility); 3987 NewGV->setUnnamedAddr(UnnamedAddr); 3988 3989 if (Record.size() > 10) 3990 NewGV->setDLLStorageClass(getDecodedDLLStorageClass(Record[10])); 3991 else 3992 upgradeDLLImportExportLinkage(NewGV, RawLinkage); 3993 3994 ValueList.push_back(NewGV); 3995 3996 // Remember which value to use for the global initializer. 3997 if (unsigned InitID = Record[2]) 3998 GlobalInits.push_back(std::make_pair(NewGV, InitID-1)); 3999 4000 if (Record.size() > 11) { 4001 if (unsigned ComdatID = Record[11]) { 4002 if (ComdatID > ComdatList.size()) 4003 return error("Invalid global variable comdat ID"); 4004 NewGV->setComdat(ComdatList[ComdatID - 1]); 4005 } 4006 } else if (hasImplicitComdat(RawLinkage)) { 4007 NewGV->setComdat(reinterpret_cast<Comdat *>(1)); 4008 } 4009 4010 break; 4011 } 4012 // FUNCTION: [type, callingconv, isproto, linkage, paramattr, 4013 // alignment, section, visibility, gc, unnamed_addr, 4014 // prologuedata, dllstorageclass, comdat, prefixdata] 4015 case bitc::MODULE_CODE_FUNCTION: { 4016 if (Record.size() < 8) 4017 return error("Invalid record"); 4018 Type *Ty = getTypeByID(Record[0]); 4019 if (!Ty) 4020 return error("Invalid record"); 4021 if (auto *PTy = dyn_cast<PointerType>(Ty)) 4022 Ty = PTy->getElementType(); 4023 auto *FTy = dyn_cast<FunctionType>(Ty); 4024 if (!FTy) 4025 return error("Invalid type for value"); 4026 auto CC = static_cast<CallingConv::ID>(Record[1]); 4027 if (CC & ~CallingConv::MaxID) 4028 return error("Invalid calling convention ID"); 4029 4030 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage, 4031 "", TheModule); 4032 4033 Func->setCallingConv(CC); 4034 bool isProto = Record[2]; 4035 uint64_t RawLinkage = Record[3]; 4036 Func->setLinkage(getDecodedLinkage(RawLinkage)); 4037 Func->setAttributes(getAttributes(Record[4])); 4038 4039 unsigned Alignment; 4040 if (std::error_code EC = parseAlignmentValue(Record[5], Alignment)) 4041 return EC; 4042 Func->setAlignment(Alignment); 4043 if (Record[6]) { 4044 if (Record[6]-1 >= SectionTable.size()) 4045 return error("Invalid ID"); 4046 Func->setSection(SectionTable[Record[6]-1]); 4047 } 4048 // Local linkage must have default visibility. 4049 if (!Func->hasLocalLinkage()) 4050 // FIXME: Change to an error if non-default in 4.0. 4051 Func->setVisibility(getDecodedVisibility(Record[7])); 4052 if (Record.size() > 8 && Record[8]) { 4053 if (Record[8]-1 >= GCTable.size()) 4054 return error("Invalid ID"); 4055 Func->setGC(GCTable[Record[8] - 1]); 4056 } 4057 GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None; 4058 if (Record.size() > 9) 4059 UnnamedAddr = getDecodedUnnamedAddrType(Record[9]); 4060 Func->setUnnamedAddr(UnnamedAddr); 4061 if (Record.size() > 10 && Record[10] != 0) 4062 FunctionPrologues.push_back(std::make_pair(Func, Record[10]-1)); 4063 4064 if (Record.size() > 11) 4065 Func->setDLLStorageClass(getDecodedDLLStorageClass(Record[11])); 4066 else 4067 upgradeDLLImportExportLinkage(Func, RawLinkage); 4068 4069 if (Record.size() > 12) { 4070 if (unsigned ComdatID = Record[12]) { 4071 if (ComdatID > ComdatList.size()) 4072 return error("Invalid function comdat ID"); 4073 Func->setComdat(ComdatList[ComdatID - 1]); 4074 } 4075 } else if (hasImplicitComdat(RawLinkage)) { 4076 Func->setComdat(reinterpret_cast<Comdat *>(1)); 4077 } 4078 4079 if (Record.size() > 13 && Record[13] != 0) 4080 FunctionPrefixes.push_back(std::make_pair(Func, Record[13]-1)); 4081 4082 if (Record.size() > 14 && Record[14] != 0) 4083 FunctionPersonalityFns.push_back(std::make_pair(Func, Record[14] - 1)); 4084 4085 ValueList.push_back(Func); 4086 4087 // If this is a function with a body, remember the prototype we are 4088 // creating now, so that we can match up the body with them later. 4089 if (!isProto) { 4090 Func->setIsMaterializable(true); 4091 FunctionsWithBodies.push_back(Func); 4092 DeferredFunctionInfo[Func] = 0; 4093 } 4094 break; 4095 } 4096 // ALIAS: [alias type, addrspace, aliasee val#, linkage] 4097 // ALIAS: [alias type, addrspace, aliasee val#, linkage, visibility, dllstorageclass] 4098 // IFUNC: [alias type, addrspace, aliasee val#, linkage, visibility, dllstorageclass] 4099 case bitc::MODULE_CODE_IFUNC: 4100 case bitc::MODULE_CODE_ALIAS: 4101 case bitc::MODULE_CODE_ALIAS_OLD: { 4102 bool NewRecord = BitCode != bitc::MODULE_CODE_ALIAS_OLD; 4103 if (Record.size() < (3 + (unsigned)NewRecord)) 4104 return error("Invalid record"); 4105 unsigned OpNum = 0; 4106 Type *Ty = getTypeByID(Record[OpNum++]); 4107 if (!Ty) 4108 return error("Invalid record"); 4109 4110 unsigned AddrSpace; 4111 if (!NewRecord) { 4112 auto *PTy = dyn_cast<PointerType>(Ty); 4113 if (!PTy) 4114 return error("Invalid type for value"); 4115 Ty = PTy->getElementType(); 4116 AddrSpace = PTy->getAddressSpace(); 4117 } else { 4118 AddrSpace = Record[OpNum++]; 4119 } 4120 4121 auto Val = Record[OpNum++]; 4122 auto Linkage = Record[OpNum++]; 4123 GlobalIndirectSymbol *NewGA; 4124 if (BitCode == bitc::MODULE_CODE_ALIAS || 4125 BitCode == bitc::MODULE_CODE_ALIAS_OLD) 4126 NewGA = GlobalAlias::create(Ty, AddrSpace, getDecodedLinkage(Linkage), 4127 "", TheModule); 4128 else 4129 NewGA = GlobalIFunc::create(Ty, AddrSpace, getDecodedLinkage(Linkage), 4130 "", nullptr, TheModule); 4131 // Old bitcode files didn't have visibility field. 4132 // Local linkage must have default visibility. 4133 if (OpNum != Record.size()) { 4134 auto VisInd = OpNum++; 4135 if (!NewGA->hasLocalLinkage()) 4136 // FIXME: Change to an error if non-default in 4.0. 4137 NewGA->setVisibility(getDecodedVisibility(Record[VisInd])); 4138 } 4139 if (OpNum != Record.size()) 4140 NewGA->setDLLStorageClass(getDecodedDLLStorageClass(Record[OpNum++])); 4141 else 4142 upgradeDLLImportExportLinkage(NewGA, Linkage); 4143 if (OpNum != Record.size()) 4144 NewGA->setThreadLocalMode(getDecodedThreadLocalMode(Record[OpNum++])); 4145 if (OpNum != Record.size()) 4146 NewGA->setUnnamedAddr(getDecodedUnnamedAddrType(Record[OpNum++])); 4147 ValueList.push_back(NewGA); 4148 IndirectSymbolInits.push_back(std::make_pair(NewGA, Val)); 4149 break; 4150 } 4151 /// MODULE_CODE_PURGEVALS: [numvals] 4152 case bitc::MODULE_CODE_PURGEVALS: 4153 // Trim down the value list to the specified size. 4154 if (Record.size() < 1 || Record[0] > ValueList.size()) 4155 return error("Invalid record"); 4156 ValueList.shrinkTo(Record[0]); 4157 break; 4158 /// MODULE_CODE_VSTOFFSET: [offset] 4159 case bitc::MODULE_CODE_VSTOFFSET: 4160 if (Record.size() < 1) 4161 return error("Invalid record"); 4162 VSTOffset = Record[0]; 4163 break; 4164 /// MODULE_CODE_SOURCE_FILENAME: [namechar x N] 4165 case bitc::MODULE_CODE_SOURCE_FILENAME: 4166 SmallString<128> ValueName; 4167 if (convertToString(Record, 0, ValueName)) 4168 return error("Invalid record"); 4169 TheModule->setSourceFileName(ValueName); 4170 break; 4171 } 4172 Record.clear(); 4173 } 4174 } 4175 4176 /// Helper to read the header common to all bitcode files. 4177 static bool hasValidBitcodeHeader(BitstreamCursor &Stream) { 4178 // Sniff for the signature. 4179 if (Stream.Read(8) != 'B' || 4180 Stream.Read(8) != 'C' || 4181 Stream.Read(4) != 0x0 || 4182 Stream.Read(4) != 0xC || 4183 Stream.Read(4) != 0xE || 4184 Stream.Read(4) != 0xD) 4185 return false; 4186 return true; 4187 } 4188 4189 std::error_code 4190 BitcodeReader::parseBitcodeInto(std::unique_ptr<DataStreamer> Streamer, 4191 Module *M, bool ShouldLazyLoadMetadata) { 4192 TheModule = M; 4193 4194 if (std::error_code EC = initStream(std::move(Streamer))) 4195 return EC; 4196 4197 // Sniff for the signature. 4198 if (!hasValidBitcodeHeader(Stream)) 4199 return error("Invalid bitcode signature"); 4200 4201 // We expect a number of well-defined blocks, though we don't necessarily 4202 // need to understand them all. 4203 while (true) { 4204 if (Stream.AtEndOfStream()) { 4205 // We didn't really read a proper Module. 4206 return error("Malformed IR file"); 4207 } 4208 4209 BitstreamEntry Entry = 4210 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs); 4211 4212 if (Entry.Kind != BitstreamEntry::SubBlock) 4213 return error("Malformed block"); 4214 4215 if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) { 4216 parseBitcodeVersion(); 4217 continue; 4218 } 4219 4220 if (Entry.ID == bitc::MODULE_BLOCK_ID) 4221 return parseModule(0, ShouldLazyLoadMetadata); 4222 4223 if (Stream.SkipBlock()) 4224 return error("Invalid record"); 4225 } 4226 } 4227 4228 ErrorOr<std::string> BitcodeReader::parseModuleTriple() { 4229 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID)) 4230 return error("Invalid record"); 4231 4232 SmallVector<uint64_t, 64> Record; 4233 4234 std::string Triple; 4235 4236 // Read all the records for this module. 4237 while (true) { 4238 BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 4239 4240 switch (Entry.Kind) { 4241 case BitstreamEntry::SubBlock: // Handled for us already. 4242 case BitstreamEntry::Error: 4243 return error("Malformed block"); 4244 case BitstreamEntry::EndBlock: 4245 return Triple; 4246 case BitstreamEntry::Record: 4247 // The interesting case. 4248 break; 4249 } 4250 4251 // Read a record. 4252 switch (Stream.readRecord(Entry.ID, Record)) { 4253 default: break; // Default behavior, ignore unknown content. 4254 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N] 4255 std::string S; 4256 if (convertToString(Record, 0, S)) 4257 return error("Invalid record"); 4258 Triple = S; 4259 break; 4260 } 4261 } 4262 Record.clear(); 4263 } 4264 llvm_unreachable("Exit infinite loop"); 4265 } 4266 4267 ErrorOr<std::string> BitcodeReader::parseTriple() { 4268 if (std::error_code EC = initStream(nullptr)) 4269 return EC; 4270 4271 // Sniff for the signature. 4272 if (!hasValidBitcodeHeader(Stream)) 4273 return error("Invalid bitcode signature"); 4274 4275 // We expect a number of well-defined blocks, though we don't necessarily 4276 // need to understand them all. 4277 while (true) { 4278 BitstreamEntry Entry = Stream.advance(); 4279 4280 switch (Entry.Kind) { 4281 case BitstreamEntry::Error: 4282 return error("Malformed block"); 4283 case BitstreamEntry::EndBlock: 4284 return std::error_code(); 4285 4286 case BitstreamEntry::SubBlock: 4287 if (Entry.ID == bitc::MODULE_BLOCK_ID) 4288 return parseModuleTriple(); 4289 4290 // Ignore other sub-blocks. 4291 if (Stream.SkipBlock()) 4292 return error("Malformed block"); 4293 continue; 4294 4295 case BitstreamEntry::Record: 4296 Stream.skipRecord(Entry.ID); 4297 continue; 4298 } 4299 } 4300 } 4301 4302 ErrorOr<std::string> BitcodeReader::parseIdentificationBlock() { 4303 if (std::error_code EC = initStream(nullptr)) 4304 return EC; 4305 4306 // Sniff for the signature. 4307 if (!hasValidBitcodeHeader(Stream)) 4308 return error("Invalid bitcode signature"); 4309 4310 // We expect a number of well-defined blocks, though we don't necessarily 4311 // need to understand them all. 4312 while (true) { 4313 BitstreamEntry Entry = Stream.advance(); 4314 switch (Entry.Kind) { 4315 case BitstreamEntry::Error: 4316 return error("Malformed block"); 4317 case BitstreamEntry::EndBlock: 4318 return std::error_code(); 4319 4320 case BitstreamEntry::SubBlock: 4321 if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) { 4322 if (std::error_code EC = parseBitcodeVersion()) 4323 return EC; 4324 return ProducerIdentification; 4325 } 4326 // Ignore other sub-blocks. 4327 if (Stream.SkipBlock()) 4328 return error("Malformed block"); 4329 continue; 4330 case BitstreamEntry::Record: 4331 Stream.skipRecord(Entry.ID); 4332 continue; 4333 } 4334 } 4335 } 4336 4337 std::error_code BitcodeReader::parseGlobalObjectAttachment( 4338 GlobalObject &GO, ArrayRef<uint64_t> Record) { 4339 assert(Record.size() % 2 == 0); 4340 for (unsigned I = 0, E = Record.size(); I != E; I += 2) { 4341 auto K = MDKindMap.find(Record[I]); 4342 if (K == MDKindMap.end()) 4343 return error("Invalid ID"); 4344 MDNode *MD = MetadataList.getMDNodeFwdRefOrNull(Record[I + 1]); 4345 if (!MD) 4346 return error("Invalid metadata attachment"); 4347 GO.addMetadata(K->second, *MD); 4348 } 4349 return std::error_code(); 4350 } 4351 4352 ErrorOr<bool> BitcodeReader::hasObjCCategory() { 4353 if (std::error_code EC = initStream(nullptr)) 4354 return EC; 4355 4356 // Sniff for the signature. 4357 if (!hasValidBitcodeHeader(Stream)) 4358 return error("Invalid bitcode signature"); 4359 4360 // We expect a number of well-defined blocks, though we don't necessarily 4361 // need to understand them all. 4362 while (true) { 4363 BitstreamEntry Entry = Stream.advance(); 4364 4365 switch (Entry.Kind) { 4366 case BitstreamEntry::Error: 4367 return error("Malformed block"); 4368 case BitstreamEntry::EndBlock: 4369 return std::error_code(); 4370 4371 case BitstreamEntry::SubBlock: 4372 if (Entry.ID == bitc::MODULE_BLOCK_ID) 4373 return hasObjCCategoryInModule(); 4374 4375 // Ignore other sub-blocks. 4376 if (Stream.SkipBlock()) 4377 return error("Malformed block"); 4378 continue; 4379 4380 case BitstreamEntry::Record: 4381 Stream.skipRecord(Entry.ID); 4382 continue; 4383 } 4384 } 4385 } 4386 4387 ErrorOr<bool> BitcodeReader::hasObjCCategoryInModule() { 4388 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID)) 4389 return error("Invalid record"); 4390 4391 SmallVector<uint64_t, 64> Record; 4392 // Read all the records for this module. 4393 4394 while (true) { 4395 BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 4396 4397 switch (Entry.Kind) { 4398 case BitstreamEntry::SubBlock: // Handled for us already. 4399 case BitstreamEntry::Error: 4400 return error("Malformed block"); 4401 case BitstreamEntry::EndBlock: 4402 return false; 4403 case BitstreamEntry::Record: 4404 // The interesting case. 4405 break; 4406 } 4407 4408 // Read a record. 4409 switch (Stream.readRecord(Entry.ID, Record)) { 4410 default: 4411 break; // Default behavior, ignore unknown content. 4412 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N] 4413 std::string S; 4414 if (convertToString(Record, 0, S)) 4415 return error("Invalid record"); 4416 // Check for the i386 and other (x86_64, ARM) conventions 4417 if (S.find("__DATA, __objc_catlist") != std::string::npos || 4418 S.find("__OBJC,__category") != std::string::npos) 4419 return true; 4420 break; 4421 } 4422 } 4423 Record.clear(); 4424 } 4425 llvm_unreachable("Exit infinite loop"); 4426 } 4427 4428 /// Parse metadata attachments. 4429 std::error_code BitcodeReader::parseMetadataAttachment(Function &F) { 4430 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID)) 4431 return error("Invalid record"); 4432 4433 SmallVector<uint64_t, 64> Record; 4434 4435 while (true) { 4436 BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 4437 4438 switch (Entry.Kind) { 4439 case BitstreamEntry::SubBlock: // Handled for us already. 4440 case BitstreamEntry::Error: 4441 return error("Malformed block"); 4442 case BitstreamEntry::EndBlock: 4443 return std::error_code(); 4444 case BitstreamEntry::Record: 4445 // The interesting case. 4446 break; 4447 } 4448 4449 // Read a metadata attachment record. 4450 Record.clear(); 4451 switch (Stream.readRecord(Entry.ID, Record)) { 4452 default: // Default behavior: ignore. 4453 break; 4454 case bitc::METADATA_ATTACHMENT: { 4455 unsigned RecordLength = Record.size(); 4456 if (Record.empty()) 4457 return error("Invalid record"); 4458 if (RecordLength % 2 == 0) { 4459 // A function attachment. 4460 if (std::error_code EC = parseGlobalObjectAttachment(F, Record)) 4461 return EC; 4462 continue; 4463 } 4464 4465 // An instruction attachment. 4466 Instruction *Inst = InstructionList[Record[0]]; 4467 for (unsigned i = 1; i != RecordLength; i = i+2) { 4468 unsigned Kind = Record[i]; 4469 DenseMap<unsigned, unsigned>::iterator I = 4470 MDKindMap.find(Kind); 4471 if (I == MDKindMap.end()) 4472 return error("Invalid ID"); 4473 Metadata *Node = MetadataList.getMetadataFwdRef(Record[i + 1]); 4474 if (isa<LocalAsMetadata>(Node)) 4475 // Drop the attachment. This used to be legal, but there's no 4476 // upgrade path. 4477 break; 4478 MDNode *MD = dyn_cast_or_null<MDNode>(Node); 4479 if (!MD) 4480 return error("Invalid metadata attachment"); 4481 4482 if (HasSeenOldLoopTags && I->second == LLVMContext::MD_loop) 4483 MD = upgradeInstructionLoopAttachment(*MD); 4484 4485 if (I->second == LLVMContext::MD_tbaa) { 4486 assert(!MD->isTemporary() && "should load MDs before attachments"); 4487 MD = UpgradeTBAANode(*MD); 4488 } 4489 Inst->setMetadata(I->second, MD); 4490 } 4491 break; 4492 } 4493 } 4494 } 4495 } 4496 4497 static std::error_code typeCheckLoadStoreInst(Type *ValType, Type *PtrType) { 4498 LLVMContext &Context = PtrType->getContext(); 4499 if (!isa<PointerType>(PtrType)) 4500 return error(Context, "Load/Store operand is not a pointer type"); 4501 Type *ElemType = cast<PointerType>(PtrType)->getElementType(); 4502 4503 if (ValType && ValType != ElemType) 4504 return error(Context, "Explicit load/store type does not match pointee " 4505 "type of pointer operand"); 4506 if (!PointerType::isLoadableOrStorableType(ElemType)) 4507 return error(Context, "Cannot load/store from pointer"); 4508 return std::error_code(); 4509 } 4510 4511 /// Lazily parse the specified function body block. 4512 std::error_code BitcodeReader::parseFunctionBody(Function *F) { 4513 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID)) 4514 return error("Invalid record"); 4515 4516 // Unexpected unresolved metadata when parsing function. 4517 if (MetadataList.hasFwdRefs()) 4518 return error("Invalid function metadata: incoming forward references"); 4519 4520 InstructionList.clear(); 4521 unsigned ModuleValueListSize = ValueList.size(); 4522 unsigned ModuleMetadataListSize = MetadataList.size(); 4523 4524 // Add all the function arguments to the value table. 4525 for (Argument &I : F->args()) 4526 ValueList.push_back(&I); 4527 4528 unsigned NextValueNo = ValueList.size(); 4529 BasicBlock *CurBB = nullptr; 4530 unsigned CurBBNo = 0; 4531 4532 DebugLoc LastLoc; 4533 auto getLastInstruction = [&]() -> Instruction * { 4534 if (CurBB && !CurBB->empty()) 4535 return &CurBB->back(); 4536 else if (CurBBNo && FunctionBBs[CurBBNo - 1] && 4537 !FunctionBBs[CurBBNo - 1]->empty()) 4538 return &FunctionBBs[CurBBNo - 1]->back(); 4539 return nullptr; 4540 }; 4541 4542 std::vector<OperandBundleDef> OperandBundles; 4543 4544 // Read all the records. 4545 SmallVector<uint64_t, 64> Record; 4546 4547 while (true) { 4548 BitstreamEntry Entry = Stream.advance(); 4549 4550 switch (Entry.Kind) { 4551 case BitstreamEntry::Error: 4552 return error("Malformed block"); 4553 case BitstreamEntry::EndBlock: 4554 goto OutOfRecordLoop; 4555 4556 case BitstreamEntry::SubBlock: 4557 switch (Entry.ID) { 4558 default: // Skip unknown content. 4559 if (Stream.SkipBlock()) 4560 return error("Invalid record"); 4561 break; 4562 case bitc::CONSTANTS_BLOCK_ID: 4563 if (std::error_code EC = parseConstants()) 4564 return EC; 4565 NextValueNo = ValueList.size(); 4566 break; 4567 case bitc::VALUE_SYMTAB_BLOCK_ID: 4568 if (std::error_code EC = parseValueSymbolTable()) 4569 return EC; 4570 break; 4571 case bitc::METADATA_ATTACHMENT_ID: 4572 if (std::error_code EC = parseMetadataAttachment(*F)) 4573 return EC; 4574 break; 4575 case bitc::METADATA_BLOCK_ID: 4576 if (std::error_code EC = parseMetadata()) 4577 return EC; 4578 break; 4579 case bitc::USELIST_BLOCK_ID: 4580 if (std::error_code EC = parseUseLists()) 4581 return EC; 4582 break; 4583 } 4584 continue; 4585 4586 case BitstreamEntry::Record: 4587 // The interesting case. 4588 break; 4589 } 4590 4591 // Read a record. 4592 Record.clear(); 4593 Instruction *I = nullptr; 4594 unsigned BitCode = Stream.readRecord(Entry.ID, Record); 4595 switch (BitCode) { 4596 default: // Default behavior: reject 4597 return error("Invalid value"); 4598 case bitc::FUNC_CODE_DECLAREBLOCKS: { // DECLAREBLOCKS: [nblocks] 4599 if (Record.size() < 1 || Record[0] == 0) 4600 return error("Invalid record"); 4601 // Create all the basic blocks for the function. 4602 FunctionBBs.resize(Record[0]); 4603 4604 // See if anything took the address of blocks in this function. 4605 auto BBFRI = BasicBlockFwdRefs.find(F); 4606 if (BBFRI == BasicBlockFwdRefs.end()) { 4607 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i) 4608 FunctionBBs[i] = BasicBlock::Create(Context, "", F); 4609 } else { 4610 auto &BBRefs = BBFRI->second; 4611 // Check for invalid basic block references. 4612 if (BBRefs.size() > FunctionBBs.size()) 4613 return error("Invalid ID"); 4614 assert(!BBRefs.empty() && "Unexpected empty array"); 4615 assert(!BBRefs.front() && "Invalid reference to entry block"); 4616 for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E; 4617 ++I) 4618 if (I < RE && BBRefs[I]) { 4619 BBRefs[I]->insertInto(F); 4620 FunctionBBs[I] = BBRefs[I]; 4621 } else { 4622 FunctionBBs[I] = BasicBlock::Create(Context, "", F); 4623 } 4624 4625 // Erase from the table. 4626 BasicBlockFwdRefs.erase(BBFRI); 4627 } 4628 4629 CurBB = FunctionBBs[0]; 4630 continue; 4631 } 4632 4633 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN 4634 // This record indicates that the last instruction is at the same 4635 // location as the previous instruction with a location. 4636 I = getLastInstruction(); 4637 4638 if (!I) 4639 return error("Invalid record"); 4640 I->setDebugLoc(LastLoc); 4641 I = nullptr; 4642 continue; 4643 4644 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia] 4645 I = getLastInstruction(); 4646 if (!I || Record.size() < 4) 4647 return error("Invalid record"); 4648 4649 unsigned Line = Record[0], Col = Record[1]; 4650 unsigned ScopeID = Record[2], IAID = Record[3]; 4651 4652 MDNode *Scope = nullptr, *IA = nullptr; 4653 if (ScopeID) { 4654 Scope = MetadataList.getMDNodeFwdRefOrNull(ScopeID - 1); 4655 if (!Scope) 4656 return error("Invalid record"); 4657 } 4658 if (IAID) { 4659 IA = MetadataList.getMDNodeFwdRefOrNull(IAID - 1); 4660 if (!IA) 4661 return error("Invalid record"); 4662 } 4663 LastLoc = DebugLoc::get(Line, Col, Scope, IA); 4664 I->setDebugLoc(LastLoc); 4665 I = nullptr; 4666 continue; 4667 } 4668 4669 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode] 4670 unsigned OpNum = 0; 4671 Value *LHS, *RHS; 4672 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) || 4673 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) || 4674 OpNum+1 > Record.size()) 4675 return error("Invalid record"); 4676 4677 int Opc = getDecodedBinaryOpcode(Record[OpNum++], LHS->getType()); 4678 if (Opc == -1) 4679 return error("Invalid record"); 4680 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS); 4681 InstructionList.push_back(I); 4682 if (OpNum < Record.size()) { 4683 if (Opc == Instruction::Add || 4684 Opc == Instruction::Sub || 4685 Opc == Instruction::Mul || 4686 Opc == Instruction::Shl) { 4687 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP)) 4688 cast<BinaryOperator>(I)->setHasNoSignedWrap(true); 4689 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP)) 4690 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true); 4691 } else if (Opc == Instruction::SDiv || 4692 Opc == Instruction::UDiv || 4693 Opc == Instruction::LShr || 4694 Opc == Instruction::AShr) { 4695 if (Record[OpNum] & (1 << bitc::PEO_EXACT)) 4696 cast<BinaryOperator>(I)->setIsExact(true); 4697 } else if (isa<FPMathOperator>(I)) { 4698 FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]); 4699 if (FMF.any()) 4700 I->setFastMathFlags(FMF); 4701 } 4702 4703 } 4704 break; 4705 } 4706 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc] 4707 unsigned OpNum = 0; 4708 Value *Op; 4709 if (getValueTypePair(Record, OpNum, NextValueNo, Op) || 4710 OpNum+2 != Record.size()) 4711 return error("Invalid record"); 4712 4713 Type *ResTy = getTypeByID(Record[OpNum]); 4714 int Opc = getDecodedCastOpcode(Record[OpNum + 1]); 4715 if (Opc == -1 || !ResTy) 4716 return error("Invalid record"); 4717 Instruction *Temp = nullptr; 4718 if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) { 4719 if (Temp) { 4720 InstructionList.push_back(Temp); 4721 CurBB->getInstList().push_back(Temp); 4722 } 4723 } else { 4724 auto CastOp = (Instruction::CastOps)Opc; 4725 if (!CastInst::castIsValid(CastOp, Op, ResTy)) 4726 return error("Invalid cast"); 4727 I = CastInst::Create(CastOp, Op, ResTy); 4728 } 4729 InstructionList.push_back(I); 4730 break; 4731 } 4732 case bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD: 4733 case bitc::FUNC_CODE_INST_GEP_OLD: 4734 case bitc::FUNC_CODE_INST_GEP: { // GEP: type, [n x operands] 4735 unsigned OpNum = 0; 4736 4737 Type *Ty; 4738 bool InBounds; 4739 4740 if (BitCode == bitc::FUNC_CODE_INST_GEP) { 4741 InBounds = Record[OpNum++]; 4742 Ty = getTypeByID(Record[OpNum++]); 4743 } else { 4744 InBounds = BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD; 4745 Ty = nullptr; 4746 } 4747 4748 Value *BasePtr; 4749 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr)) 4750 return error("Invalid record"); 4751 4752 if (!Ty) 4753 Ty = cast<SequentialType>(BasePtr->getType()->getScalarType()) 4754 ->getElementType(); 4755 else if (Ty != 4756 cast<SequentialType>(BasePtr->getType()->getScalarType()) 4757 ->getElementType()) 4758 return error( 4759 "Explicit gep type does not match pointee type of pointer operand"); 4760 4761 SmallVector<Value*, 16> GEPIdx; 4762 while (OpNum != Record.size()) { 4763 Value *Op; 4764 if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 4765 return error("Invalid record"); 4766 GEPIdx.push_back(Op); 4767 } 4768 4769 I = GetElementPtrInst::Create(Ty, BasePtr, GEPIdx); 4770 4771 InstructionList.push_back(I); 4772 if (InBounds) 4773 cast<GetElementPtrInst>(I)->setIsInBounds(true); 4774 break; 4775 } 4776 4777 case bitc::FUNC_CODE_INST_EXTRACTVAL: { 4778 // EXTRACTVAL: [opty, opval, n x indices] 4779 unsigned OpNum = 0; 4780 Value *Agg; 4781 if (getValueTypePair(Record, OpNum, NextValueNo, Agg)) 4782 return error("Invalid record"); 4783 4784 unsigned RecSize = Record.size(); 4785 if (OpNum == RecSize) 4786 return error("EXTRACTVAL: Invalid instruction with 0 indices"); 4787 4788 SmallVector<unsigned, 4> EXTRACTVALIdx; 4789 Type *CurTy = Agg->getType(); 4790 for (; OpNum != RecSize; ++OpNum) { 4791 bool IsArray = CurTy->isArrayTy(); 4792 bool IsStruct = CurTy->isStructTy(); 4793 uint64_t Index = Record[OpNum]; 4794 4795 if (!IsStruct && !IsArray) 4796 return error("EXTRACTVAL: Invalid type"); 4797 if ((unsigned)Index != Index) 4798 return error("Invalid value"); 4799 if (IsStruct && Index >= CurTy->subtypes().size()) 4800 return error("EXTRACTVAL: Invalid struct index"); 4801 if (IsArray && Index >= CurTy->getArrayNumElements()) 4802 return error("EXTRACTVAL: Invalid array index"); 4803 EXTRACTVALIdx.push_back((unsigned)Index); 4804 4805 if (IsStruct) 4806 CurTy = CurTy->subtypes()[Index]; 4807 else 4808 CurTy = CurTy->subtypes()[0]; 4809 } 4810 4811 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx); 4812 InstructionList.push_back(I); 4813 break; 4814 } 4815 4816 case bitc::FUNC_CODE_INST_INSERTVAL: { 4817 // INSERTVAL: [opty, opval, opty, opval, n x indices] 4818 unsigned OpNum = 0; 4819 Value *Agg; 4820 if (getValueTypePair(Record, OpNum, NextValueNo, Agg)) 4821 return error("Invalid record"); 4822 Value *Val; 4823 if (getValueTypePair(Record, OpNum, NextValueNo, Val)) 4824 return error("Invalid record"); 4825 4826 unsigned RecSize = Record.size(); 4827 if (OpNum == RecSize) 4828 return error("INSERTVAL: Invalid instruction with 0 indices"); 4829 4830 SmallVector<unsigned, 4> INSERTVALIdx; 4831 Type *CurTy = Agg->getType(); 4832 for (; OpNum != RecSize; ++OpNum) { 4833 bool IsArray = CurTy->isArrayTy(); 4834 bool IsStruct = CurTy->isStructTy(); 4835 uint64_t Index = Record[OpNum]; 4836 4837 if (!IsStruct && !IsArray) 4838 return error("INSERTVAL: Invalid type"); 4839 if ((unsigned)Index != Index) 4840 return error("Invalid value"); 4841 if (IsStruct && Index >= CurTy->subtypes().size()) 4842 return error("INSERTVAL: Invalid struct index"); 4843 if (IsArray && Index >= CurTy->getArrayNumElements()) 4844 return error("INSERTVAL: Invalid array index"); 4845 4846 INSERTVALIdx.push_back((unsigned)Index); 4847 if (IsStruct) 4848 CurTy = CurTy->subtypes()[Index]; 4849 else 4850 CurTy = CurTy->subtypes()[0]; 4851 } 4852 4853 if (CurTy != Val->getType()) 4854 return error("Inserted value type doesn't match aggregate type"); 4855 4856 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx); 4857 InstructionList.push_back(I); 4858 break; 4859 } 4860 4861 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval] 4862 // obsolete form of select 4863 // handles select i1 ... in old bitcode 4864 unsigned OpNum = 0; 4865 Value *TrueVal, *FalseVal, *Cond; 4866 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) || 4867 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) || 4868 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond)) 4869 return error("Invalid record"); 4870 4871 I = SelectInst::Create(Cond, TrueVal, FalseVal); 4872 InstructionList.push_back(I); 4873 break; 4874 } 4875 4876 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred] 4877 // new form of select 4878 // handles select i1 or select [N x i1] 4879 unsigned OpNum = 0; 4880 Value *TrueVal, *FalseVal, *Cond; 4881 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) || 4882 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) || 4883 getValueTypePair(Record, OpNum, NextValueNo, Cond)) 4884 return error("Invalid record"); 4885 4886 // select condition can be either i1 or [N x i1] 4887 if (VectorType* vector_type = 4888 dyn_cast<VectorType>(Cond->getType())) { 4889 // expect <n x i1> 4890 if (vector_type->getElementType() != Type::getInt1Ty(Context)) 4891 return error("Invalid type for value"); 4892 } else { 4893 // expect i1 4894 if (Cond->getType() != Type::getInt1Ty(Context)) 4895 return error("Invalid type for value"); 4896 } 4897 4898 I = SelectInst::Create(Cond, TrueVal, FalseVal); 4899 InstructionList.push_back(I); 4900 break; 4901 } 4902 4903 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval] 4904 unsigned OpNum = 0; 4905 Value *Vec, *Idx; 4906 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) || 4907 getValueTypePair(Record, OpNum, NextValueNo, Idx)) 4908 return error("Invalid record"); 4909 if (!Vec->getType()->isVectorTy()) 4910 return error("Invalid type for value"); 4911 I = ExtractElementInst::Create(Vec, Idx); 4912 InstructionList.push_back(I); 4913 break; 4914 } 4915 4916 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval] 4917 unsigned OpNum = 0; 4918 Value *Vec, *Elt, *Idx; 4919 if (getValueTypePair(Record, OpNum, NextValueNo, Vec)) 4920 return error("Invalid record"); 4921 if (!Vec->getType()->isVectorTy()) 4922 return error("Invalid type for value"); 4923 if (popValue(Record, OpNum, NextValueNo, 4924 cast<VectorType>(Vec->getType())->getElementType(), Elt) || 4925 getValueTypePair(Record, OpNum, NextValueNo, Idx)) 4926 return error("Invalid record"); 4927 I = InsertElementInst::Create(Vec, Elt, Idx); 4928 InstructionList.push_back(I); 4929 break; 4930 } 4931 4932 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval] 4933 unsigned OpNum = 0; 4934 Value *Vec1, *Vec2, *Mask; 4935 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) || 4936 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2)) 4937 return error("Invalid record"); 4938 4939 if (getValueTypePair(Record, OpNum, NextValueNo, Mask)) 4940 return error("Invalid record"); 4941 if (!Vec1->getType()->isVectorTy() || !Vec2->getType()->isVectorTy()) 4942 return error("Invalid type for value"); 4943 I = new ShuffleVectorInst(Vec1, Vec2, Mask); 4944 InstructionList.push_back(I); 4945 break; 4946 } 4947 4948 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred] 4949 // Old form of ICmp/FCmp returning bool 4950 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were 4951 // both legal on vectors but had different behaviour. 4952 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred] 4953 // FCmp/ICmp returning bool or vector of bool 4954 4955 unsigned OpNum = 0; 4956 Value *LHS, *RHS; 4957 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) || 4958 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS)) 4959 return error("Invalid record"); 4960 4961 unsigned PredVal = Record[OpNum]; 4962 bool IsFP = LHS->getType()->isFPOrFPVectorTy(); 4963 FastMathFlags FMF; 4964 if (IsFP && Record.size() > OpNum+1) 4965 FMF = getDecodedFastMathFlags(Record[++OpNum]); 4966 4967 if (OpNum+1 != Record.size()) 4968 return error("Invalid record"); 4969 4970 if (LHS->getType()->isFPOrFPVectorTy()) 4971 I = new FCmpInst((FCmpInst::Predicate)PredVal, LHS, RHS); 4972 else 4973 I = new ICmpInst((ICmpInst::Predicate)PredVal, LHS, RHS); 4974 4975 if (FMF.any()) 4976 I->setFastMathFlags(FMF); 4977 InstructionList.push_back(I); 4978 break; 4979 } 4980 4981 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>] 4982 { 4983 unsigned Size = Record.size(); 4984 if (Size == 0) { 4985 I = ReturnInst::Create(Context); 4986 InstructionList.push_back(I); 4987 break; 4988 } 4989 4990 unsigned OpNum = 0; 4991 Value *Op = nullptr; 4992 if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 4993 return error("Invalid record"); 4994 if (OpNum != Record.size()) 4995 return error("Invalid record"); 4996 4997 I = ReturnInst::Create(Context, Op); 4998 InstructionList.push_back(I); 4999 break; 5000 } 5001 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#] 5002 if (Record.size() != 1 && Record.size() != 3) 5003 return error("Invalid record"); 5004 BasicBlock *TrueDest = getBasicBlock(Record[0]); 5005 if (!TrueDest) 5006 return error("Invalid record"); 5007 5008 if (Record.size() == 1) { 5009 I = BranchInst::Create(TrueDest); 5010 InstructionList.push_back(I); 5011 } 5012 else { 5013 BasicBlock *FalseDest = getBasicBlock(Record[1]); 5014 Value *Cond = getValue(Record, 2, NextValueNo, 5015 Type::getInt1Ty(Context)); 5016 if (!FalseDest || !Cond) 5017 return error("Invalid record"); 5018 I = BranchInst::Create(TrueDest, FalseDest, Cond); 5019 InstructionList.push_back(I); 5020 } 5021 break; 5022 } 5023 case bitc::FUNC_CODE_INST_CLEANUPRET: { // CLEANUPRET: [val] or [val,bb#] 5024 if (Record.size() != 1 && Record.size() != 2) 5025 return error("Invalid record"); 5026 unsigned Idx = 0; 5027 Value *CleanupPad = 5028 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context)); 5029 if (!CleanupPad) 5030 return error("Invalid record"); 5031 BasicBlock *UnwindDest = nullptr; 5032 if (Record.size() == 2) { 5033 UnwindDest = getBasicBlock(Record[Idx++]); 5034 if (!UnwindDest) 5035 return error("Invalid record"); 5036 } 5037 5038 I = CleanupReturnInst::Create(CleanupPad, UnwindDest); 5039 InstructionList.push_back(I); 5040 break; 5041 } 5042 case bitc::FUNC_CODE_INST_CATCHRET: { // CATCHRET: [val,bb#] 5043 if (Record.size() != 2) 5044 return error("Invalid record"); 5045 unsigned Idx = 0; 5046 Value *CatchPad = 5047 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context)); 5048 if (!CatchPad) 5049 return error("Invalid record"); 5050 BasicBlock *BB = getBasicBlock(Record[Idx++]); 5051 if (!BB) 5052 return error("Invalid record"); 5053 5054 I = CatchReturnInst::Create(CatchPad, BB); 5055 InstructionList.push_back(I); 5056 break; 5057 } 5058 case bitc::FUNC_CODE_INST_CATCHSWITCH: { // CATCHSWITCH: [tok,num,(bb)*,bb?] 5059 // We must have, at minimum, the outer scope and the number of arguments. 5060 if (Record.size() < 2) 5061 return error("Invalid record"); 5062 5063 unsigned Idx = 0; 5064 5065 Value *ParentPad = 5066 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context)); 5067 5068 unsigned NumHandlers = Record[Idx++]; 5069 5070 SmallVector<BasicBlock *, 2> Handlers; 5071 for (unsigned Op = 0; Op != NumHandlers; ++Op) { 5072 BasicBlock *BB = getBasicBlock(Record[Idx++]); 5073 if (!BB) 5074 return error("Invalid record"); 5075 Handlers.push_back(BB); 5076 } 5077 5078 BasicBlock *UnwindDest = nullptr; 5079 if (Idx + 1 == Record.size()) { 5080 UnwindDest = getBasicBlock(Record[Idx++]); 5081 if (!UnwindDest) 5082 return error("Invalid record"); 5083 } 5084 5085 if (Record.size() != Idx) 5086 return error("Invalid record"); 5087 5088 auto *CatchSwitch = 5089 CatchSwitchInst::Create(ParentPad, UnwindDest, NumHandlers); 5090 for (BasicBlock *Handler : Handlers) 5091 CatchSwitch->addHandler(Handler); 5092 I = CatchSwitch; 5093 InstructionList.push_back(I); 5094 break; 5095 } 5096 case bitc::FUNC_CODE_INST_CATCHPAD: 5097 case bitc::FUNC_CODE_INST_CLEANUPPAD: { // [tok,num,(ty,val)*] 5098 // We must have, at minimum, the outer scope and the number of arguments. 5099 if (Record.size() < 2) 5100 return error("Invalid record"); 5101 5102 unsigned Idx = 0; 5103 5104 Value *ParentPad = 5105 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context)); 5106 5107 unsigned NumArgOperands = Record[Idx++]; 5108 5109 SmallVector<Value *, 2> Args; 5110 for (unsigned Op = 0; Op != NumArgOperands; ++Op) { 5111 Value *Val; 5112 if (getValueTypePair(Record, Idx, NextValueNo, Val)) 5113 return error("Invalid record"); 5114 Args.push_back(Val); 5115 } 5116 5117 if (Record.size() != Idx) 5118 return error("Invalid record"); 5119 5120 if (BitCode == bitc::FUNC_CODE_INST_CLEANUPPAD) 5121 I = CleanupPadInst::Create(ParentPad, Args); 5122 else 5123 I = CatchPadInst::Create(ParentPad, Args); 5124 InstructionList.push_back(I); 5125 break; 5126 } 5127 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...] 5128 // Check magic 5129 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) { 5130 // "New" SwitchInst format with case ranges. The changes to write this 5131 // format were reverted but we still recognize bitcode that uses it. 5132 // Hopefully someday we will have support for case ranges and can use 5133 // this format again. 5134 5135 Type *OpTy = getTypeByID(Record[1]); 5136 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth(); 5137 5138 Value *Cond = getValue(Record, 2, NextValueNo, OpTy); 5139 BasicBlock *Default = getBasicBlock(Record[3]); 5140 if (!OpTy || !Cond || !Default) 5141 return error("Invalid record"); 5142 5143 unsigned NumCases = Record[4]; 5144 5145 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases); 5146 InstructionList.push_back(SI); 5147 5148 unsigned CurIdx = 5; 5149 for (unsigned i = 0; i != NumCases; ++i) { 5150 SmallVector<ConstantInt*, 1> CaseVals; 5151 unsigned NumItems = Record[CurIdx++]; 5152 for (unsigned ci = 0; ci != NumItems; ++ci) { 5153 bool isSingleNumber = Record[CurIdx++]; 5154 5155 APInt Low; 5156 unsigned ActiveWords = 1; 5157 if (ValueBitWidth > 64) 5158 ActiveWords = Record[CurIdx++]; 5159 Low = readWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords), 5160 ValueBitWidth); 5161 CurIdx += ActiveWords; 5162 5163 if (!isSingleNumber) { 5164 ActiveWords = 1; 5165 if (ValueBitWidth > 64) 5166 ActiveWords = Record[CurIdx++]; 5167 APInt High = readWideAPInt( 5168 makeArrayRef(&Record[CurIdx], ActiveWords), ValueBitWidth); 5169 CurIdx += ActiveWords; 5170 5171 // FIXME: It is not clear whether values in the range should be 5172 // compared as signed or unsigned values. The partially 5173 // implemented changes that used this format in the past used 5174 // unsigned comparisons. 5175 for ( ; Low.ule(High); ++Low) 5176 CaseVals.push_back(ConstantInt::get(Context, Low)); 5177 } else 5178 CaseVals.push_back(ConstantInt::get(Context, Low)); 5179 } 5180 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]); 5181 for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(), 5182 cve = CaseVals.end(); cvi != cve; ++cvi) 5183 SI->addCase(*cvi, DestBB); 5184 } 5185 I = SI; 5186 break; 5187 } 5188 5189 // Old SwitchInst format without case ranges. 5190 5191 if (Record.size() < 3 || (Record.size() & 1) == 0) 5192 return error("Invalid record"); 5193 Type *OpTy = getTypeByID(Record[0]); 5194 Value *Cond = getValue(Record, 1, NextValueNo, OpTy); 5195 BasicBlock *Default = getBasicBlock(Record[2]); 5196 if (!OpTy || !Cond || !Default) 5197 return error("Invalid record"); 5198 unsigned NumCases = (Record.size()-3)/2; 5199 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases); 5200 InstructionList.push_back(SI); 5201 for (unsigned i = 0, e = NumCases; i != e; ++i) { 5202 ConstantInt *CaseVal = 5203 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy)); 5204 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]); 5205 if (!CaseVal || !DestBB) { 5206 delete SI; 5207 return error("Invalid record"); 5208 } 5209 SI->addCase(CaseVal, DestBB); 5210 } 5211 I = SI; 5212 break; 5213 } 5214 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...] 5215 if (Record.size() < 2) 5216 return error("Invalid record"); 5217 Type *OpTy = getTypeByID(Record[0]); 5218 Value *Address = getValue(Record, 1, NextValueNo, OpTy); 5219 if (!OpTy || !Address) 5220 return error("Invalid record"); 5221 unsigned NumDests = Record.size()-2; 5222 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests); 5223 InstructionList.push_back(IBI); 5224 for (unsigned i = 0, e = NumDests; i != e; ++i) { 5225 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) { 5226 IBI->addDestination(DestBB); 5227 } else { 5228 delete IBI; 5229 return error("Invalid record"); 5230 } 5231 } 5232 I = IBI; 5233 break; 5234 } 5235 5236 case bitc::FUNC_CODE_INST_INVOKE: { 5237 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...] 5238 if (Record.size() < 4) 5239 return error("Invalid record"); 5240 unsigned OpNum = 0; 5241 AttributeSet PAL = getAttributes(Record[OpNum++]); 5242 unsigned CCInfo = Record[OpNum++]; 5243 BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]); 5244 BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]); 5245 5246 FunctionType *FTy = nullptr; 5247 if (CCInfo >> 13 & 1 && 5248 !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++])))) 5249 return error("Explicit invoke type is not a function type"); 5250 5251 Value *Callee; 5252 if (getValueTypePair(Record, OpNum, NextValueNo, Callee)) 5253 return error("Invalid record"); 5254 5255 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType()); 5256 if (!CalleeTy) 5257 return error("Callee is not a pointer"); 5258 if (!FTy) { 5259 FTy = dyn_cast<FunctionType>(CalleeTy->getElementType()); 5260 if (!FTy) 5261 return error("Callee is not of pointer to function type"); 5262 } else if (CalleeTy->getElementType() != FTy) 5263 return error("Explicit invoke type does not match pointee type of " 5264 "callee operand"); 5265 if (Record.size() < FTy->getNumParams() + OpNum) 5266 return error("Insufficient operands to call"); 5267 5268 SmallVector<Value*, 16> Ops; 5269 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) { 5270 Ops.push_back(getValue(Record, OpNum, NextValueNo, 5271 FTy->getParamType(i))); 5272 if (!Ops.back()) 5273 return error("Invalid record"); 5274 } 5275 5276 if (!FTy->isVarArg()) { 5277 if (Record.size() != OpNum) 5278 return error("Invalid record"); 5279 } else { 5280 // Read type/value pairs for varargs params. 5281 while (OpNum != Record.size()) { 5282 Value *Op; 5283 if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 5284 return error("Invalid record"); 5285 Ops.push_back(Op); 5286 } 5287 } 5288 5289 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops, OperandBundles); 5290 OperandBundles.clear(); 5291 InstructionList.push_back(I); 5292 cast<InvokeInst>(I)->setCallingConv( 5293 static_cast<CallingConv::ID>(CallingConv::MaxID & CCInfo)); 5294 cast<InvokeInst>(I)->setAttributes(PAL); 5295 break; 5296 } 5297 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval] 5298 unsigned Idx = 0; 5299 Value *Val = nullptr; 5300 if (getValueTypePair(Record, Idx, NextValueNo, Val)) 5301 return error("Invalid record"); 5302 I = ResumeInst::Create(Val); 5303 InstructionList.push_back(I); 5304 break; 5305 } 5306 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE 5307 I = new UnreachableInst(Context); 5308 InstructionList.push_back(I); 5309 break; 5310 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...] 5311 if (Record.size() < 1 || ((Record.size()-1)&1)) 5312 return error("Invalid record"); 5313 Type *Ty = getTypeByID(Record[0]); 5314 if (!Ty) 5315 return error("Invalid record"); 5316 5317 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2); 5318 InstructionList.push_back(PN); 5319 5320 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) { 5321 Value *V; 5322 // With the new function encoding, it is possible that operands have 5323 // negative IDs (for forward references). Use a signed VBR 5324 // representation to keep the encoding small. 5325 if (UseRelativeIDs) 5326 V = getValueSigned(Record, 1+i, NextValueNo, Ty); 5327 else 5328 V = getValue(Record, 1+i, NextValueNo, Ty); 5329 BasicBlock *BB = getBasicBlock(Record[2+i]); 5330 if (!V || !BB) 5331 return error("Invalid record"); 5332 PN->addIncoming(V, BB); 5333 } 5334 I = PN; 5335 break; 5336 } 5337 5338 case bitc::FUNC_CODE_INST_LANDINGPAD: 5339 case bitc::FUNC_CODE_INST_LANDINGPAD_OLD: { 5340 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?] 5341 unsigned Idx = 0; 5342 if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD) { 5343 if (Record.size() < 3) 5344 return error("Invalid record"); 5345 } else { 5346 assert(BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD); 5347 if (Record.size() < 4) 5348 return error("Invalid record"); 5349 } 5350 Type *Ty = getTypeByID(Record[Idx++]); 5351 if (!Ty) 5352 return error("Invalid record"); 5353 if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD) { 5354 Value *PersFn = nullptr; 5355 if (getValueTypePair(Record, Idx, NextValueNo, PersFn)) 5356 return error("Invalid record"); 5357 5358 if (!F->hasPersonalityFn()) 5359 F->setPersonalityFn(cast<Constant>(PersFn)); 5360 else if (F->getPersonalityFn() != cast<Constant>(PersFn)) 5361 return error("Personality function mismatch"); 5362 } 5363 5364 bool IsCleanup = !!Record[Idx++]; 5365 unsigned NumClauses = Record[Idx++]; 5366 LandingPadInst *LP = LandingPadInst::Create(Ty, NumClauses); 5367 LP->setCleanup(IsCleanup); 5368 for (unsigned J = 0; J != NumClauses; ++J) { 5369 LandingPadInst::ClauseType CT = 5370 LandingPadInst::ClauseType(Record[Idx++]); (void)CT; 5371 Value *Val; 5372 5373 if (getValueTypePair(Record, Idx, NextValueNo, Val)) { 5374 delete LP; 5375 return error("Invalid record"); 5376 } 5377 5378 assert((CT != LandingPadInst::Catch || 5379 !isa<ArrayType>(Val->getType())) && 5380 "Catch clause has a invalid type!"); 5381 assert((CT != LandingPadInst::Filter || 5382 isa<ArrayType>(Val->getType())) && 5383 "Filter clause has invalid type!"); 5384 LP->addClause(cast<Constant>(Val)); 5385 } 5386 5387 I = LP; 5388 InstructionList.push_back(I); 5389 break; 5390 } 5391 5392 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align] 5393 if (Record.size() != 4) 5394 return error("Invalid record"); 5395 uint64_t AlignRecord = Record[3]; 5396 const uint64_t InAllocaMask = uint64_t(1) << 5; 5397 const uint64_t ExplicitTypeMask = uint64_t(1) << 6; 5398 const uint64_t SwiftErrorMask = uint64_t(1) << 7; 5399 const uint64_t FlagMask = InAllocaMask | ExplicitTypeMask | 5400 SwiftErrorMask; 5401 bool InAlloca = AlignRecord & InAllocaMask; 5402 bool SwiftError = AlignRecord & SwiftErrorMask; 5403 Type *Ty = getTypeByID(Record[0]); 5404 if ((AlignRecord & ExplicitTypeMask) == 0) { 5405 auto *PTy = dyn_cast_or_null<PointerType>(Ty); 5406 if (!PTy) 5407 return error("Old-style alloca with a non-pointer type"); 5408 Ty = PTy->getElementType(); 5409 } 5410 Type *OpTy = getTypeByID(Record[1]); 5411 Value *Size = getFnValueByID(Record[2], OpTy); 5412 unsigned Align; 5413 if (std::error_code EC = 5414 parseAlignmentValue(AlignRecord & ~FlagMask, Align)) { 5415 return EC; 5416 } 5417 if (!Ty || !Size) 5418 return error("Invalid record"); 5419 AllocaInst *AI = new AllocaInst(Ty, Size, Align); 5420 AI->setUsedWithInAlloca(InAlloca); 5421 AI->setSwiftError(SwiftError); 5422 I = AI; 5423 InstructionList.push_back(I); 5424 break; 5425 } 5426 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol] 5427 unsigned OpNum = 0; 5428 Value *Op; 5429 if (getValueTypePair(Record, OpNum, NextValueNo, Op) || 5430 (OpNum + 2 != Record.size() && OpNum + 3 != Record.size())) 5431 return error("Invalid record"); 5432 5433 Type *Ty = nullptr; 5434 if (OpNum + 3 == Record.size()) 5435 Ty = getTypeByID(Record[OpNum++]); 5436 if (std::error_code EC = typeCheckLoadStoreInst(Ty, Op->getType())) 5437 return EC; 5438 if (!Ty) 5439 Ty = cast<PointerType>(Op->getType())->getElementType(); 5440 5441 unsigned Align; 5442 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align)) 5443 return EC; 5444 I = new LoadInst(Ty, Op, "", Record[OpNum + 1], Align); 5445 5446 InstructionList.push_back(I); 5447 break; 5448 } 5449 case bitc::FUNC_CODE_INST_LOADATOMIC: { 5450 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope] 5451 unsigned OpNum = 0; 5452 Value *Op; 5453 if (getValueTypePair(Record, OpNum, NextValueNo, Op) || 5454 (OpNum + 4 != Record.size() && OpNum + 5 != Record.size())) 5455 return error("Invalid record"); 5456 5457 Type *Ty = nullptr; 5458 if (OpNum + 5 == Record.size()) 5459 Ty = getTypeByID(Record[OpNum++]); 5460 if (std::error_code EC = typeCheckLoadStoreInst(Ty, Op->getType())) 5461 return EC; 5462 if (!Ty) 5463 Ty = cast<PointerType>(Op->getType())->getElementType(); 5464 5465 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]); 5466 if (Ordering == AtomicOrdering::NotAtomic || 5467 Ordering == AtomicOrdering::Release || 5468 Ordering == AtomicOrdering::AcquireRelease) 5469 return error("Invalid record"); 5470 if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0) 5471 return error("Invalid record"); 5472 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]); 5473 5474 unsigned Align; 5475 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align)) 5476 return EC; 5477 I = new LoadInst(Op, "", Record[OpNum+1], Align, Ordering, SynchScope); 5478 5479 InstructionList.push_back(I); 5480 break; 5481 } 5482 case bitc::FUNC_CODE_INST_STORE: 5483 case bitc::FUNC_CODE_INST_STORE_OLD: { // STORE2:[ptrty, ptr, val, align, vol] 5484 unsigned OpNum = 0; 5485 Value *Val, *Ptr; 5486 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) || 5487 (BitCode == bitc::FUNC_CODE_INST_STORE 5488 ? getValueTypePair(Record, OpNum, NextValueNo, Val) 5489 : popValue(Record, OpNum, NextValueNo, 5490 cast<PointerType>(Ptr->getType())->getElementType(), 5491 Val)) || 5492 OpNum + 2 != Record.size()) 5493 return error("Invalid record"); 5494 5495 if (std::error_code EC = 5496 typeCheckLoadStoreInst(Val->getType(), Ptr->getType())) 5497 return EC; 5498 unsigned Align; 5499 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align)) 5500 return EC; 5501 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align); 5502 InstructionList.push_back(I); 5503 break; 5504 } 5505 case bitc::FUNC_CODE_INST_STOREATOMIC: 5506 case bitc::FUNC_CODE_INST_STOREATOMIC_OLD: { 5507 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope] 5508 unsigned OpNum = 0; 5509 Value *Val, *Ptr; 5510 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) || 5511 !isa<PointerType>(Ptr->getType()) || 5512 (BitCode == bitc::FUNC_CODE_INST_STOREATOMIC 5513 ? getValueTypePair(Record, OpNum, NextValueNo, Val) 5514 : popValue(Record, OpNum, NextValueNo, 5515 cast<PointerType>(Ptr->getType())->getElementType(), 5516 Val)) || 5517 OpNum + 4 != Record.size()) 5518 return error("Invalid record"); 5519 5520 if (std::error_code EC = 5521 typeCheckLoadStoreInst(Val->getType(), Ptr->getType())) 5522 return EC; 5523 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]); 5524 if (Ordering == AtomicOrdering::NotAtomic || 5525 Ordering == AtomicOrdering::Acquire || 5526 Ordering == AtomicOrdering::AcquireRelease) 5527 return error("Invalid record"); 5528 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]); 5529 if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0) 5530 return error("Invalid record"); 5531 5532 unsigned Align; 5533 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align)) 5534 return EC; 5535 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align, Ordering, SynchScope); 5536 InstructionList.push_back(I); 5537 break; 5538 } 5539 case bitc::FUNC_CODE_INST_CMPXCHG_OLD: 5540 case bitc::FUNC_CODE_INST_CMPXCHG: { 5541 // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, synchscope, 5542 // failureordering?, isweak?] 5543 unsigned OpNum = 0; 5544 Value *Ptr, *Cmp, *New; 5545 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) || 5546 (BitCode == bitc::FUNC_CODE_INST_CMPXCHG 5547 ? getValueTypePair(Record, OpNum, NextValueNo, Cmp) 5548 : popValue(Record, OpNum, NextValueNo, 5549 cast<PointerType>(Ptr->getType())->getElementType(), 5550 Cmp)) || 5551 popValue(Record, OpNum, NextValueNo, Cmp->getType(), New) || 5552 Record.size() < OpNum + 3 || Record.size() > OpNum + 5) 5553 return error("Invalid record"); 5554 AtomicOrdering SuccessOrdering = getDecodedOrdering(Record[OpNum + 1]); 5555 if (SuccessOrdering == AtomicOrdering::NotAtomic || 5556 SuccessOrdering == AtomicOrdering::Unordered) 5557 return error("Invalid record"); 5558 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 2]); 5559 5560 if (std::error_code EC = 5561 typeCheckLoadStoreInst(Cmp->getType(), Ptr->getType())) 5562 return EC; 5563 AtomicOrdering FailureOrdering; 5564 if (Record.size() < 7) 5565 FailureOrdering = 5566 AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering); 5567 else 5568 FailureOrdering = getDecodedOrdering(Record[OpNum + 3]); 5569 5570 I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering, 5571 SynchScope); 5572 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]); 5573 5574 if (Record.size() < 8) { 5575 // Before weak cmpxchgs existed, the instruction simply returned the 5576 // value loaded from memory, so bitcode files from that era will be 5577 // expecting the first component of a modern cmpxchg. 5578 CurBB->getInstList().push_back(I); 5579 I = ExtractValueInst::Create(I, 0); 5580 } else { 5581 cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]); 5582 } 5583 5584 InstructionList.push_back(I); 5585 break; 5586 } 5587 case bitc::FUNC_CODE_INST_ATOMICRMW: { 5588 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope] 5589 unsigned OpNum = 0; 5590 Value *Ptr, *Val; 5591 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) || 5592 !isa<PointerType>(Ptr->getType()) || 5593 popValue(Record, OpNum, NextValueNo, 5594 cast<PointerType>(Ptr->getType())->getElementType(), Val) || 5595 OpNum+4 != Record.size()) 5596 return error("Invalid record"); 5597 AtomicRMWInst::BinOp Operation = getDecodedRMWOperation(Record[OpNum]); 5598 if (Operation < AtomicRMWInst::FIRST_BINOP || 5599 Operation > AtomicRMWInst::LAST_BINOP) 5600 return error("Invalid record"); 5601 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]); 5602 if (Ordering == AtomicOrdering::NotAtomic || 5603 Ordering == AtomicOrdering::Unordered) 5604 return error("Invalid record"); 5605 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]); 5606 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope); 5607 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]); 5608 InstructionList.push_back(I); 5609 break; 5610 } 5611 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope] 5612 if (2 != Record.size()) 5613 return error("Invalid record"); 5614 AtomicOrdering Ordering = getDecodedOrdering(Record[0]); 5615 if (Ordering == AtomicOrdering::NotAtomic || 5616 Ordering == AtomicOrdering::Unordered || 5617 Ordering == AtomicOrdering::Monotonic) 5618 return error("Invalid record"); 5619 SynchronizationScope SynchScope = getDecodedSynchScope(Record[1]); 5620 I = new FenceInst(Context, Ordering, SynchScope); 5621 InstructionList.push_back(I); 5622 break; 5623 } 5624 case bitc::FUNC_CODE_INST_CALL: { 5625 // CALL: [paramattrs, cc, fmf, fnty, fnid, arg0, arg1...] 5626 if (Record.size() < 3) 5627 return error("Invalid record"); 5628 5629 unsigned OpNum = 0; 5630 AttributeSet PAL = getAttributes(Record[OpNum++]); 5631 unsigned CCInfo = Record[OpNum++]; 5632 5633 FastMathFlags FMF; 5634 if ((CCInfo >> bitc::CALL_FMF) & 1) { 5635 FMF = getDecodedFastMathFlags(Record[OpNum++]); 5636 if (!FMF.any()) 5637 return error("Fast math flags indicator set for call with no FMF"); 5638 } 5639 5640 FunctionType *FTy = nullptr; 5641 if (CCInfo >> bitc::CALL_EXPLICIT_TYPE & 1 && 5642 !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++])))) 5643 return error("Explicit call type is not a function type"); 5644 5645 Value *Callee; 5646 if (getValueTypePair(Record, OpNum, NextValueNo, Callee)) 5647 return error("Invalid record"); 5648 5649 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType()); 5650 if (!OpTy) 5651 return error("Callee is not a pointer type"); 5652 if (!FTy) { 5653 FTy = dyn_cast<FunctionType>(OpTy->getElementType()); 5654 if (!FTy) 5655 return error("Callee is not of pointer to function type"); 5656 } else if (OpTy->getElementType() != FTy) 5657 return error("Explicit call type does not match pointee type of " 5658 "callee operand"); 5659 if (Record.size() < FTy->getNumParams() + OpNum) 5660 return error("Insufficient operands to call"); 5661 5662 SmallVector<Value*, 16> Args; 5663 // Read the fixed params. 5664 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) { 5665 if (FTy->getParamType(i)->isLabelTy()) 5666 Args.push_back(getBasicBlock(Record[OpNum])); 5667 else 5668 Args.push_back(getValue(Record, OpNum, NextValueNo, 5669 FTy->getParamType(i))); 5670 if (!Args.back()) 5671 return error("Invalid record"); 5672 } 5673 5674 // Read type/value pairs for varargs params. 5675 if (!FTy->isVarArg()) { 5676 if (OpNum != Record.size()) 5677 return error("Invalid record"); 5678 } else { 5679 while (OpNum != Record.size()) { 5680 Value *Op; 5681 if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 5682 return error("Invalid record"); 5683 Args.push_back(Op); 5684 } 5685 } 5686 5687 I = CallInst::Create(FTy, Callee, Args, OperandBundles); 5688 OperandBundles.clear(); 5689 InstructionList.push_back(I); 5690 cast<CallInst>(I)->setCallingConv( 5691 static_cast<CallingConv::ID>((0x7ff & CCInfo) >> bitc::CALL_CCONV)); 5692 CallInst::TailCallKind TCK = CallInst::TCK_None; 5693 if (CCInfo & 1 << bitc::CALL_TAIL) 5694 TCK = CallInst::TCK_Tail; 5695 if (CCInfo & (1 << bitc::CALL_MUSTTAIL)) 5696 TCK = CallInst::TCK_MustTail; 5697 if (CCInfo & (1 << bitc::CALL_NOTAIL)) 5698 TCK = CallInst::TCK_NoTail; 5699 cast<CallInst>(I)->setTailCallKind(TCK); 5700 cast<CallInst>(I)->setAttributes(PAL); 5701 if (FMF.any()) { 5702 if (!isa<FPMathOperator>(I)) 5703 return error("Fast-math-flags specified for call without " 5704 "floating-point scalar or vector return type"); 5705 I->setFastMathFlags(FMF); 5706 } 5707 break; 5708 } 5709 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty] 5710 if (Record.size() < 3) 5711 return error("Invalid record"); 5712 Type *OpTy = getTypeByID(Record[0]); 5713 Value *Op = getValue(Record, 1, NextValueNo, OpTy); 5714 Type *ResTy = getTypeByID(Record[2]); 5715 if (!OpTy || !Op || !ResTy) 5716 return error("Invalid record"); 5717 I = new VAArgInst(Op, ResTy); 5718 InstructionList.push_back(I); 5719 break; 5720 } 5721 5722 case bitc::FUNC_CODE_OPERAND_BUNDLE: { 5723 // A call or an invoke can be optionally prefixed with some variable 5724 // number of operand bundle blocks. These blocks are read into 5725 // OperandBundles and consumed at the next call or invoke instruction. 5726 5727 if (Record.size() < 1 || Record[0] >= BundleTags.size()) 5728 return error("Invalid record"); 5729 5730 std::vector<Value *> Inputs; 5731 5732 unsigned OpNum = 1; 5733 while (OpNum != Record.size()) { 5734 Value *Op; 5735 if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 5736 return error("Invalid record"); 5737 Inputs.push_back(Op); 5738 } 5739 5740 OperandBundles.emplace_back(BundleTags[Record[0]], std::move(Inputs)); 5741 continue; 5742 } 5743 } 5744 5745 // Add instruction to end of current BB. If there is no current BB, reject 5746 // this file. 5747 if (!CurBB) { 5748 delete I; 5749 return error("Invalid instruction with no BB"); 5750 } 5751 if (!OperandBundles.empty()) { 5752 delete I; 5753 return error("Operand bundles found with no consumer"); 5754 } 5755 CurBB->getInstList().push_back(I); 5756 5757 // If this was a terminator instruction, move to the next block. 5758 if (isa<TerminatorInst>(I)) { 5759 ++CurBBNo; 5760 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr; 5761 } 5762 5763 // Non-void values get registered in the value table for future use. 5764 if (I && !I->getType()->isVoidTy()) 5765 ValueList.assignValue(I, NextValueNo++); 5766 } 5767 5768 OutOfRecordLoop: 5769 5770 if (!OperandBundles.empty()) 5771 return error("Operand bundles found with no consumer"); 5772 5773 // Check the function list for unresolved values. 5774 if (Argument *A = dyn_cast<Argument>(ValueList.back())) { 5775 if (!A->getParent()) { 5776 // We found at least one unresolved value. Nuke them all to avoid leaks. 5777 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){ 5778 if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) { 5779 A->replaceAllUsesWith(UndefValue::get(A->getType())); 5780 delete A; 5781 } 5782 } 5783 return error("Never resolved value found in function"); 5784 } 5785 } 5786 5787 // Unexpected unresolved metadata about to be dropped. 5788 if (MetadataList.hasFwdRefs()) 5789 return error("Invalid function metadata: outgoing forward refs"); 5790 5791 // Trim the value list down to the size it was before we parsed this function. 5792 ValueList.shrinkTo(ModuleValueListSize); 5793 MetadataList.shrinkTo(ModuleMetadataListSize); 5794 std::vector<BasicBlock*>().swap(FunctionBBs); 5795 return std::error_code(); 5796 } 5797 5798 /// Find the function body in the bitcode stream 5799 std::error_code BitcodeReader::findFunctionInStream( 5800 Function *F, 5801 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) { 5802 while (DeferredFunctionInfoIterator->second == 0) { 5803 // This is the fallback handling for the old format bitcode that 5804 // didn't contain the function index in the VST, or when we have 5805 // an anonymous function which would not have a VST entry. 5806 // Assert that we have one of those two cases. 5807 assert(VSTOffset == 0 || !F->hasName()); 5808 // Parse the next body in the stream and set its position in the 5809 // DeferredFunctionInfo map. 5810 if (std::error_code EC = rememberAndSkipFunctionBodies()) 5811 return EC; 5812 } 5813 return std::error_code(); 5814 } 5815 5816 //===----------------------------------------------------------------------===// 5817 // GVMaterializer implementation 5818 //===----------------------------------------------------------------------===// 5819 5820 void BitcodeReader::releaseBuffer() { Buffer.release(); } 5821 5822 std::error_code BitcodeReader::materialize(GlobalValue *GV) { 5823 Function *F = dyn_cast<Function>(GV); 5824 // If it's not a function or is already material, ignore the request. 5825 if (!F || !F->isMaterializable()) 5826 return std::error_code(); 5827 5828 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F); 5829 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!"); 5830 // If its position is recorded as 0, its body is somewhere in the stream 5831 // but we haven't seen it yet. 5832 if (DFII->second == 0) 5833 if (std::error_code EC = findFunctionInStream(F, DFII)) 5834 return EC; 5835 5836 // Materialize metadata before parsing any function bodies. 5837 if (std::error_code EC = materializeMetadata()) 5838 return EC; 5839 5840 // Move the bit stream to the saved position of the deferred function body. 5841 Stream.JumpToBit(DFII->second); 5842 5843 if (std::error_code EC = parseFunctionBody(F)) 5844 return EC; 5845 F->setIsMaterializable(false); 5846 5847 if (StripDebugInfo) 5848 stripDebugInfo(*F); 5849 5850 // Upgrade any old intrinsic calls in the function. 5851 for (auto &I : UpgradedIntrinsics) { 5852 for (auto UI = I.first->materialized_user_begin(), UE = I.first->user_end(); 5853 UI != UE;) { 5854 User *U = *UI; 5855 ++UI; 5856 if (CallInst *CI = dyn_cast<CallInst>(U)) 5857 UpgradeIntrinsicCall(CI, I.second); 5858 } 5859 } 5860 5861 // Update calls to the remangled intrinsics 5862 for (auto &I : RemangledIntrinsics) 5863 for (auto UI = I.first->materialized_user_begin(), UE = I.first->user_end(); 5864 UI != UE;) 5865 // Don't expect any other users than call sites 5866 CallSite(*UI++).setCalledFunction(I.second); 5867 5868 // Finish fn->subprogram upgrade for materialized functions. 5869 if (DISubprogram *SP = FunctionsWithSPs.lookup(F)) 5870 F->setSubprogram(SP); 5871 5872 // Bring in any functions that this function forward-referenced via 5873 // blockaddresses. 5874 return materializeForwardReferencedFunctions(); 5875 } 5876 5877 std::error_code BitcodeReader::materializeModule() { 5878 if (std::error_code EC = materializeMetadata()) 5879 return EC; 5880 5881 // Promise to materialize all forward references. 5882 WillMaterializeAllForwardRefs = true; 5883 5884 // Iterate over the module, deserializing any functions that are still on 5885 // disk. 5886 for (Function &F : *TheModule) { 5887 if (std::error_code EC = materialize(&F)) 5888 return EC; 5889 } 5890 // At this point, if there are any function bodies, parse the rest of 5891 // the bits in the module past the last function block we have recorded 5892 // through either lazy scanning or the VST. 5893 if (LastFunctionBlockBit || NextUnreadBit) 5894 parseModule(LastFunctionBlockBit > NextUnreadBit ? LastFunctionBlockBit 5895 : NextUnreadBit); 5896 5897 // Check that all block address forward references got resolved (as we 5898 // promised above). 5899 if (!BasicBlockFwdRefs.empty()) 5900 return error("Never resolved function from blockaddress"); 5901 5902 // Upgrade any intrinsic calls that slipped through (should not happen!) and 5903 // delete the old functions to clean up. We can't do this unless the entire 5904 // module is materialized because there could always be another function body 5905 // with calls to the old function. 5906 for (auto &I : UpgradedIntrinsics) { 5907 for (auto *U : I.first->users()) { 5908 if (CallInst *CI = dyn_cast<CallInst>(U)) 5909 UpgradeIntrinsicCall(CI, I.second); 5910 } 5911 if (!I.first->use_empty()) 5912 I.first->replaceAllUsesWith(I.second); 5913 I.first->eraseFromParent(); 5914 } 5915 UpgradedIntrinsics.clear(); 5916 // Do the same for remangled intrinsics 5917 for (auto &I : RemangledIntrinsics) { 5918 I.first->replaceAllUsesWith(I.second); 5919 I.first->eraseFromParent(); 5920 } 5921 RemangledIntrinsics.clear(); 5922 5923 UpgradeDebugInfo(*TheModule); 5924 5925 UpgradeModuleFlags(*TheModule); 5926 return std::error_code(); 5927 } 5928 5929 std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const { 5930 return IdentifiedStructTypes; 5931 } 5932 5933 std::error_code ModuleSummaryIndexBitcodeReader::error(const Twine &Message) { 5934 return ::error(DiagnosticHandler, 5935 make_error_code(BitcodeError::CorruptedBitcode), Message); 5936 } 5937 5938 ModuleSummaryIndexBitcodeReader::ModuleSummaryIndexBitcodeReader( 5939 MemoryBuffer *Buffer, DiagnosticHandlerFunction DiagnosticHandler, 5940 bool CheckGlobalValSummaryPresenceOnly) 5941 : BitcodeReaderBase(Buffer), DiagnosticHandler(std::move(DiagnosticHandler)), 5942 CheckGlobalValSummaryPresenceOnly(CheckGlobalValSummaryPresenceOnly) {} 5943 5944 void ModuleSummaryIndexBitcodeReader::freeState() { Buffer = nullptr; } 5945 5946 void ModuleSummaryIndexBitcodeReader::releaseBuffer() { Buffer.release(); } 5947 5948 std::pair<GlobalValue::GUID, GlobalValue::GUID> 5949 ModuleSummaryIndexBitcodeReader::getGUIDFromValueId(unsigned ValueId) { 5950 auto VGI = ValueIdToCallGraphGUIDMap.find(ValueId); 5951 assert(VGI != ValueIdToCallGraphGUIDMap.end()); 5952 return VGI->second; 5953 } 5954 5955 // Specialized value symbol table parser used when reading module index 5956 // blocks where we don't actually create global values. The parsed information 5957 // is saved in the bitcode reader for use when later parsing summaries. 5958 std::error_code ModuleSummaryIndexBitcodeReader::parseValueSymbolTable( 5959 uint64_t Offset, 5960 DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap) { 5961 assert(Offset > 0 && "Expected non-zero VST offset"); 5962 uint64_t CurrentBit = jumpToValueSymbolTable(Offset, Stream); 5963 5964 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID)) 5965 return error("Invalid record"); 5966 5967 SmallVector<uint64_t, 64> Record; 5968 5969 // Read all the records for this value table. 5970 SmallString<128> ValueName; 5971 5972 while (true) { 5973 BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 5974 5975 switch (Entry.Kind) { 5976 case BitstreamEntry::SubBlock: // Handled for us already. 5977 case BitstreamEntry::Error: 5978 return error("Malformed block"); 5979 case BitstreamEntry::EndBlock: 5980 // Done parsing VST, jump back to wherever we came from. 5981 Stream.JumpToBit(CurrentBit); 5982 return std::error_code(); 5983 case BitstreamEntry::Record: 5984 // The interesting case. 5985 break; 5986 } 5987 5988 // Read a record. 5989 Record.clear(); 5990 switch (Stream.readRecord(Entry.ID, Record)) { 5991 default: // Default behavior: ignore (e.g. VST_CODE_BBENTRY records). 5992 break; 5993 case bitc::VST_CODE_ENTRY: { // VST_CODE_ENTRY: [valueid, namechar x N] 5994 if (convertToString(Record, 1, ValueName)) 5995 return error("Invalid record"); 5996 unsigned ValueID = Record[0]; 5997 assert(!SourceFileName.empty()); 5998 auto VLI = ValueIdToLinkageMap.find(ValueID); 5999 assert(VLI != ValueIdToLinkageMap.end() && 6000 "No linkage found for VST entry?"); 6001 auto Linkage = VLI->second; 6002 std::string GlobalId = 6003 GlobalValue::getGlobalIdentifier(ValueName, Linkage, SourceFileName); 6004 auto ValueGUID = GlobalValue::getGUID(GlobalId); 6005 auto OriginalNameID = ValueGUID; 6006 if (GlobalValue::isLocalLinkage(Linkage)) 6007 OriginalNameID = GlobalValue::getGUID(ValueName); 6008 if (PrintSummaryGUIDs) 6009 dbgs() << "GUID " << ValueGUID << "(" << OriginalNameID << ") is " 6010 << ValueName << "\n"; 6011 ValueIdToCallGraphGUIDMap[ValueID] = 6012 std::make_pair(ValueGUID, OriginalNameID); 6013 ValueName.clear(); 6014 break; 6015 } 6016 case bitc::VST_CODE_FNENTRY: { 6017 // VST_CODE_FNENTRY: [valueid, offset, namechar x N] 6018 if (convertToString(Record, 2, ValueName)) 6019 return error("Invalid record"); 6020 unsigned ValueID = Record[0]; 6021 assert(!SourceFileName.empty()); 6022 auto VLI = ValueIdToLinkageMap.find(ValueID); 6023 assert(VLI != ValueIdToLinkageMap.end() && 6024 "No linkage found for VST entry?"); 6025 auto Linkage = VLI->second; 6026 std::string FunctionGlobalId = GlobalValue::getGlobalIdentifier( 6027 ValueName, VLI->second, SourceFileName); 6028 auto FunctionGUID = GlobalValue::getGUID(FunctionGlobalId); 6029 auto OriginalNameID = FunctionGUID; 6030 if (GlobalValue::isLocalLinkage(Linkage)) 6031 OriginalNameID = GlobalValue::getGUID(ValueName); 6032 if (PrintSummaryGUIDs) 6033 dbgs() << "GUID " << FunctionGUID << "(" << OriginalNameID << ") is " 6034 << ValueName << "\n"; 6035 ValueIdToCallGraphGUIDMap[ValueID] = 6036 std::make_pair(FunctionGUID, OriginalNameID); 6037 6038 ValueName.clear(); 6039 break; 6040 } 6041 case bitc::VST_CODE_COMBINED_ENTRY: { 6042 // VST_CODE_COMBINED_ENTRY: [valueid, refguid] 6043 unsigned ValueID = Record[0]; 6044 GlobalValue::GUID RefGUID = Record[1]; 6045 // The "original name", which is the second value of the pair will be 6046 // overriden later by a FS_COMBINED_ORIGINAL_NAME in the combined index. 6047 ValueIdToCallGraphGUIDMap[ValueID] = std::make_pair(RefGUID, RefGUID); 6048 break; 6049 } 6050 } 6051 } 6052 } 6053 6054 // Parse just the blocks needed for building the index out of the module. 6055 // At the end of this routine the module Index is populated with a map 6056 // from global value id to GlobalValueSummary objects. 6057 std::error_code ModuleSummaryIndexBitcodeReader::parseModule() { 6058 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID)) 6059 return error("Invalid record"); 6060 6061 SmallVector<uint64_t, 64> Record; 6062 DenseMap<unsigned, GlobalValue::LinkageTypes> ValueIdToLinkageMap; 6063 unsigned ValueId = 0; 6064 6065 // Read the index for this module. 6066 while (true) { 6067 BitstreamEntry Entry = Stream.advance(); 6068 6069 switch (Entry.Kind) { 6070 case BitstreamEntry::Error: 6071 return error("Malformed block"); 6072 case BitstreamEntry::EndBlock: 6073 return std::error_code(); 6074 6075 case BitstreamEntry::SubBlock: 6076 if (CheckGlobalValSummaryPresenceOnly) { 6077 if (Entry.ID == bitc::GLOBALVAL_SUMMARY_BLOCK_ID) { 6078 SeenGlobalValSummary = true; 6079 // No need to parse the rest since we found the summary. 6080 return std::error_code(); 6081 } 6082 if (Stream.SkipBlock()) 6083 return error("Invalid record"); 6084 continue; 6085 } 6086 switch (Entry.ID) { 6087 default: // Skip unknown content. 6088 if (Stream.SkipBlock()) 6089 return error("Invalid record"); 6090 break; 6091 case bitc::BLOCKINFO_BLOCK_ID: 6092 // Need to parse these to get abbrev ids (e.g. for VST) 6093 if (Stream.ReadBlockInfoBlock()) 6094 return error("Malformed block"); 6095 break; 6096 case bitc::VALUE_SYMTAB_BLOCK_ID: 6097 // Should have been parsed earlier via VSTOffset, unless there 6098 // is no summary section. 6099 assert(((SeenValueSymbolTable && VSTOffset > 0) || 6100 !SeenGlobalValSummary) && 6101 "Expected early VST parse via VSTOffset record"); 6102 if (Stream.SkipBlock()) 6103 return error("Invalid record"); 6104 break; 6105 case bitc::GLOBALVAL_SUMMARY_BLOCK_ID: 6106 assert(!SeenValueSymbolTable && 6107 "Already read VST when parsing summary block?"); 6108 // We might not have a VST if there were no values in the 6109 // summary. An empty summary block generated when we are 6110 // performing ThinLTO compiles so we don't later invoke 6111 // the regular LTO process on them. 6112 if (VSTOffset > 0) { 6113 if (std::error_code EC = 6114 parseValueSymbolTable(VSTOffset, ValueIdToLinkageMap)) 6115 return EC; 6116 SeenValueSymbolTable = true; 6117 } 6118 SeenGlobalValSummary = true; 6119 if (std::error_code EC = parseEntireSummary()) 6120 return EC; 6121 break; 6122 case bitc::MODULE_STRTAB_BLOCK_ID: 6123 if (std::error_code EC = parseModuleStringTable()) 6124 return EC; 6125 break; 6126 } 6127 continue; 6128 6129 case BitstreamEntry::Record: { 6130 Record.clear(); 6131 auto BitCode = Stream.readRecord(Entry.ID, Record); 6132 switch (BitCode) { 6133 default: 6134 break; // Default behavior, ignore unknown content. 6135 /// MODULE_CODE_SOURCE_FILENAME: [namechar x N] 6136 case bitc::MODULE_CODE_SOURCE_FILENAME: { 6137 SmallString<128> ValueName; 6138 if (convertToString(Record, 0, ValueName)) 6139 return error("Invalid record"); 6140 SourceFileName = ValueName.c_str(); 6141 break; 6142 } 6143 /// MODULE_CODE_HASH: [5*i32] 6144 case bitc::MODULE_CODE_HASH: { 6145 if (Record.size() != 5) 6146 return error("Invalid hash length " + Twine(Record.size()).str()); 6147 if (!TheIndex) 6148 break; 6149 if (TheIndex->modulePaths().empty()) 6150 // Does not have any summary emitted. 6151 break; 6152 if (TheIndex->modulePaths().size() != 1) 6153 return error("Don't expect multiple modules defined?"); 6154 auto &Hash = TheIndex->modulePaths().begin()->second.second; 6155 int Pos = 0; 6156 for (auto &Val : Record) { 6157 assert(!(Val >> 32) && "Unexpected high bits set"); 6158 Hash[Pos++] = Val; 6159 } 6160 break; 6161 } 6162 /// MODULE_CODE_VSTOFFSET: [offset] 6163 case bitc::MODULE_CODE_VSTOFFSET: 6164 if (Record.size() < 1) 6165 return error("Invalid record"); 6166 VSTOffset = Record[0]; 6167 break; 6168 // GLOBALVAR: [pointer type, isconst, initid, 6169 // linkage, alignment, section, visibility, threadlocal, 6170 // unnamed_addr, externally_initialized, dllstorageclass, 6171 // comdat] 6172 case bitc::MODULE_CODE_GLOBALVAR: { 6173 if (Record.size() < 6) 6174 return error("Invalid record"); 6175 uint64_t RawLinkage = Record[3]; 6176 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage); 6177 ValueIdToLinkageMap[ValueId++] = Linkage; 6178 break; 6179 } 6180 // FUNCTION: [type, callingconv, isproto, linkage, paramattr, 6181 // alignment, section, visibility, gc, unnamed_addr, 6182 // prologuedata, dllstorageclass, comdat, prefixdata] 6183 case bitc::MODULE_CODE_FUNCTION: { 6184 if (Record.size() < 8) 6185 return error("Invalid record"); 6186 uint64_t RawLinkage = Record[3]; 6187 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage); 6188 ValueIdToLinkageMap[ValueId++] = Linkage; 6189 break; 6190 } 6191 // ALIAS: [alias type, addrspace, aliasee val#, linkage, visibility, 6192 // dllstorageclass] 6193 case bitc::MODULE_CODE_ALIAS: { 6194 if (Record.size() < 6) 6195 return error("Invalid record"); 6196 uint64_t RawLinkage = Record[3]; 6197 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage); 6198 ValueIdToLinkageMap[ValueId++] = Linkage; 6199 break; 6200 } 6201 } 6202 } 6203 continue; 6204 } 6205 } 6206 } 6207 6208 // Eagerly parse the entire summary block. This populates the GlobalValueSummary 6209 // objects in the index. 6210 std::error_code ModuleSummaryIndexBitcodeReader::parseEntireSummary() { 6211 if (Stream.EnterSubBlock(bitc::GLOBALVAL_SUMMARY_BLOCK_ID)) 6212 return error("Invalid record"); 6213 SmallVector<uint64_t, 64> Record; 6214 6215 // Parse version 6216 { 6217 BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 6218 if (Entry.Kind != BitstreamEntry::Record) 6219 return error("Invalid Summary Block: record for version expected"); 6220 if (Stream.readRecord(Entry.ID, Record) != bitc::FS_VERSION) 6221 return error("Invalid Summary Block: version expected"); 6222 } 6223 const uint64_t Version = Record[0]; 6224 const bool IsOldProfileFormat = Version == 1; 6225 if (!IsOldProfileFormat && Version != 2) 6226 return error("Invalid summary version " + Twine(Version) + 6227 ", 1 or 2 expected"); 6228 Record.clear(); 6229 6230 // Keep around the last seen summary to be used when we see an optional 6231 // "OriginalName" attachement. 6232 GlobalValueSummary *LastSeenSummary = nullptr; 6233 bool Combined = false; 6234 6235 while (true) { 6236 BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 6237 6238 switch (Entry.Kind) { 6239 case BitstreamEntry::SubBlock: // Handled for us already. 6240 case BitstreamEntry::Error: 6241 return error("Malformed block"); 6242 case BitstreamEntry::EndBlock: 6243 // For a per-module index, remove any entries that still have empty 6244 // summaries. The VST parsing creates entries eagerly for all symbols, 6245 // but not all have associated summaries (e.g. it doesn't know how to 6246 // distinguish between VST_CODE_ENTRY for function declarations vs global 6247 // variables with initializers that end up with a summary). Remove those 6248 // entries now so that we don't need to rely on the combined index merger 6249 // to clean them up (especially since that may not run for the first 6250 // module's index if we merge into that). 6251 if (!Combined) 6252 TheIndex->removeEmptySummaryEntries(); 6253 return std::error_code(); 6254 case BitstreamEntry::Record: 6255 // The interesting case. 6256 break; 6257 } 6258 6259 // Read a record. The record format depends on whether this 6260 // is a per-module index or a combined index file. In the per-module 6261 // case the records contain the associated value's ID for correlation 6262 // with VST entries. In the combined index the correlation is done 6263 // via the bitcode offset of the summary records (which were saved 6264 // in the combined index VST entries). The records also contain 6265 // information used for ThinLTO renaming and importing. 6266 Record.clear(); 6267 auto BitCode = Stream.readRecord(Entry.ID, Record); 6268 switch (BitCode) { 6269 default: // Default behavior: ignore. 6270 break; 6271 // FS_PERMODULE: [valueid, flags, instcount, numrefs, numrefs x valueid, 6272 // n x (valueid)] 6273 // FS_PERMODULE_PROFILE: [valueid, flags, instcount, numrefs, 6274 // numrefs x valueid, 6275 // n x (valueid, hotness)] 6276 case bitc::FS_PERMODULE: 6277 case bitc::FS_PERMODULE_PROFILE: { 6278 unsigned ValueID = Record[0]; 6279 uint64_t RawFlags = Record[1]; 6280 unsigned InstCount = Record[2]; 6281 unsigned NumRefs = Record[3]; 6282 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version); 6283 std::unique_ptr<FunctionSummary> FS = 6284 llvm::make_unique<FunctionSummary>(Flags, InstCount); 6285 // The module path string ref set in the summary must be owned by the 6286 // index's module string table. Since we don't have a module path 6287 // string table section in the per-module index, we create a single 6288 // module path string table entry with an empty (0) ID to take 6289 // ownership. 6290 FS->setModulePath( 6291 TheIndex->addModulePath(Buffer->getBufferIdentifier(), 0)->first()); 6292 static int RefListStartIndex = 4; 6293 int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs; 6294 assert(Record.size() >= RefListStartIndex + NumRefs && 6295 "Record size inconsistent with number of references"); 6296 for (unsigned I = 4, E = CallGraphEdgeStartIndex; I != E; ++I) { 6297 unsigned RefValueId = Record[I]; 6298 GlobalValue::GUID RefGUID = getGUIDFromValueId(RefValueId).first; 6299 FS->addRefEdge(RefGUID); 6300 } 6301 bool HasProfile = (BitCode == bitc::FS_PERMODULE_PROFILE); 6302 for (unsigned I = CallGraphEdgeStartIndex, E = Record.size(); I != E; 6303 ++I) { 6304 CalleeInfo::HotnessType Hotness; 6305 GlobalValue::GUID CalleeGUID; 6306 std::tie(CalleeGUID, Hotness) = 6307 readCallGraphEdge(Record, I, IsOldProfileFormat, HasProfile); 6308 FS->addCallGraphEdge(CalleeGUID, CalleeInfo(Hotness)); 6309 } 6310 auto GUID = getGUIDFromValueId(ValueID); 6311 FS->setOriginalName(GUID.second); 6312 TheIndex->addGlobalValueSummary(GUID.first, std::move(FS)); 6313 break; 6314 } 6315 // FS_ALIAS: [valueid, flags, valueid] 6316 // Aliases must be emitted (and parsed) after all FS_PERMODULE entries, as 6317 // they expect all aliasee summaries to be available. 6318 case bitc::FS_ALIAS: { 6319 unsigned ValueID = Record[0]; 6320 uint64_t RawFlags = Record[1]; 6321 unsigned AliaseeID = Record[2]; 6322 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version); 6323 std::unique_ptr<AliasSummary> AS = llvm::make_unique<AliasSummary>(Flags); 6324 // The module path string ref set in the summary must be owned by the 6325 // index's module string table. Since we don't have a module path 6326 // string table section in the per-module index, we create a single 6327 // module path string table entry with an empty (0) ID to take 6328 // ownership. 6329 AS->setModulePath( 6330 TheIndex->addModulePath(Buffer->getBufferIdentifier(), 0)->first()); 6331 6332 GlobalValue::GUID AliaseeGUID = getGUIDFromValueId(AliaseeID).first; 6333 auto *AliaseeSummary = TheIndex->getGlobalValueSummary(AliaseeGUID); 6334 if (!AliaseeSummary) 6335 return error("Alias expects aliasee summary to be parsed"); 6336 AS->setAliasee(AliaseeSummary); 6337 6338 auto GUID = getGUIDFromValueId(ValueID); 6339 AS->setOriginalName(GUID.second); 6340 TheIndex->addGlobalValueSummary(GUID.first, std::move(AS)); 6341 break; 6342 } 6343 // FS_PERMODULE_GLOBALVAR_INIT_REFS: [valueid, flags, n x valueid] 6344 case bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS: { 6345 unsigned ValueID = Record[0]; 6346 uint64_t RawFlags = Record[1]; 6347 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version); 6348 std::unique_ptr<GlobalVarSummary> FS = 6349 llvm::make_unique<GlobalVarSummary>(Flags); 6350 FS->setModulePath( 6351 TheIndex->addModulePath(Buffer->getBufferIdentifier(), 0)->first()); 6352 for (unsigned I = 2, E = Record.size(); I != E; ++I) { 6353 unsigned RefValueId = Record[I]; 6354 GlobalValue::GUID RefGUID = getGUIDFromValueId(RefValueId).first; 6355 FS->addRefEdge(RefGUID); 6356 } 6357 auto GUID = getGUIDFromValueId(ValueID); 6358 FS->setOriginalName(GUID.second); 6359 TheIndex->addGlobalValueSummary(GUID.first, std::move(FS)); 6360 break; 6361 } 6362 // FS_COMBINED: [valueid, modid, flags, instcount, numrefs, 6363 // numrefs x valueid, n x (valueid)] 6364 // FS_COMBINED_PROFILE: [valueid, modid, flags, instcount, numrefs, 6365 // numrefs x valueid, n x (valueid, hotness)] 6366 case bitc::FS_COMBINED: 6367 case bitc::FS_COMBINED_PROFILE: { 6368 unsigned ValueID = Record[0]; 6369 uint64_t ModuleId = Record[1]; 6370 uint64_t RawFlags = Record[2]; 6371 unsigned InstCount = Record[3]; 6372 unsigned NumRefs = Record[4]; 6373 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version); 6374 std::unique_ptr<FunctionSummary> FS = 6375 llvm::make_unique<FunctionSummary>(Flags, InstCount); 6376 LastSeenSummary = FS.get(); 6377 FS->setModulePath(ModuleIdMap[ModuleId]); 6378 static int RefListStartIndex = 5; 6379 int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs; 6380 assert(Record.size() >= RefListStartIndex + NumRefs && 6381 "Record size inconsistent with number of references"); 6382 for (unsigned I = RefListStartIndex, E = CallGraphEdgeStartIndex; I != E; 6383 ++I) { 6384 unsigned RefValueId = Record[I]; 6385 GlobalValue::GUID RefGUID = getGUIDFromValueId(RefValueId).first; 6386 FS->addRefEdge(RefGUID); 6387 } 6388 bool HasProfile = (BitCode == bitc::FS_COMBINED_PROFILE); 6389 for (unsigned I = CallGraphEdgeStartIndex, E = Record.size(); I != E; 6390 ++I) { 6391 CalleeInfo::HotnessType Hotness; 6392 GlobalValue::GUID CalleeGUID; 6393 std::tie(CalleeGUID, Hotness) = 6394 readCallGraphEdge(Record, I, IsOldProfileFormat, HasProfile); 6395 FS->addCallGraphEdge(CalleeGUID, CalleeInfo(Hotness)); 6396 } 6397 GlobalValue::GUID GUID = getGUIDFromValueId(ValueID).first; 6398 TheIndex->addGlobalValueSummary(GUID, std::move(FS)); 6399 Combined = true; 6400 break; 6401 } 6402 // FS_COMBINED_ALIAS: [valueid, modid, flags, valueid] 6403 // Aliases must be emitted (and parsed) after all FS_COMBINED entries, as 6404 // they expect all aliasee summaries to be available. 6405 case bitc::FS_COMBINED_ALIAS: { 6406 unsigned ValueID = Record[0]; 6407 uint64_t ModuleId = Record[1]; 6408 uint64_t RawFlags = Record[2]; 6409 unsigned AliaseeValueId = Record[3]; 6410 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version); 6411 std::unique_ptr<AliasSummary> AS = llvm::make_unique<AliasSummary>(Flags); 6412 LastSeenSummary = AS.get(); 6413 AS->setModulePath(ModuleIdMap[ModuleId]); 6414 6415 auto AliaseeGUID = getGUIDFromValueId(AliaseeValueId).first; 6416 auto AliaseeInModule = 6417 TheIndex->findSummaryInModule(AliaseeGUID, AS->modulePath()); 6418 if (!AliaseeInModule) 6419 return error("Alias expects aliasee summary to be parsed"); 6420 AS->setAliasee(AliaseeInModule); 6421 6422 GlobalValue::GUID GUID = getGUIDFromValueId(ValueID).first; 6423 TheIndex->addGlobalValueSummary(GUID, std::move(AS)); 6424 Combined = true; 6425 break; 6426 } 6427 // FS_COMBINED_GLOBALVAR_INIT_REFS: [valueid, modid, flags, n x valueid] 6428 case bitc::FS_COMBINED_GLOBALVAR_INIT_REFS: { 6429 unsigned ValueID = Record[0]; 6430 uint64_t ModuleId = Record[1]; 6431 uint64_t RawFlags = Record[2]; 6432 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version); 6433 std::unique_ptr<GlobalVarSummary> FS = 6434 llvm::make_unique<GlobalVarSummary>(Flags); 6435 LastSeenSummary = FS.get(); 6436 FS->setModulePath(ModuleIdMap[ModuleId]); 6437 for (unsigned I = 3, E = Record.size(); I != E; ++I) { 6438 unsigned RefValueId = Record[I]; 6439 GlobalValue::GUID RefGUID = getGUIDFromValueId(RefValueId).first; 6440 FS->addRefEdge(RefGUID); 6441 } 6442 GlobalValue::GUID GUID = getGUIDFromValueId(ValueID).first; 6443 TheIndex->addGlobalValueSummary(GUID, std::move(FS)); 6444 Combined = true; 6445 break; 6446 } 6447 // FS_COMBINED_ORIGINAL_NAME: [original_name] 6448 case bitc::FS_COMBINED_ORIGINAL_NAME: { 6449 uint64_t OriginalName = Record[0]; 6450 if (!LastSeenSummary) 6451 return error("Name attachment that does not follow a combined record"); 6452 LastSeenSummary->setOriginalName(OriginalName); 6453 // Reset the LastSeenSummary 6454 LastSeenSummary = nullptr; 6455 } 6456 } 6457 } 6458 llvm_unreachable("Exit infinite loop"); 6459 } 6460 6461 std::pair<GlobalValue::GUID, CalleeInfo::HotnessType> 6462 ModuleSummaryIndexBitcodeReader::readCallGraphEdge( 6463 const SmallVector<uint64_t, 64> &Record, unsigned int &I, 6464 const bool IsOldProfileFormat, const bool HasProfile) { 6465 6466 auto Hotness = CalleeInfo::HotnessType::Unknown; 6467 unsigned CalleeValueId = Record[I]; 6468 GlobalValue::GUID CalleeGUID = getGUIDFromValueId(CalleeValueId).first; 6469 if (IsOldProfileFormat) { 6470 I += 1; // Skip old callsitecount field 6471 if (HasProfile) 6472 I += 1; // Skip old profilecount field 6473 } else if (HasProfile) 6474 Hotness = static_cast<CalleeInfo::HotnessType>(Record[++I]); 6475 return {CalleeGUID, Hotness}; 6476 } 6477 6478 // Parse the module string table block into the Index. 6479 // This populates the ModulePathStringTable map in the index. 6480 std::error_code ModuleSummaryIndexBitcodeReader::parseModuleStringTable() { 6481 if (Stream.EnterSubBlock(bitc::MODULE_STRTAB_BLOCK_ID)) 6482 return error("Invalid record"); 6483 6484 SmallVector<uint64_t, 64> Record; 6485 6486 SmallString<128> ModulePath; 6487 ModulePathStringTableTy::iterator LastSeenModulePath; 6488 6489 while (true) { 6490 BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 6491 6492 switch (Entry.Kind) { 6493 case BitstreamEntry::SubBlock: // Handled for us already. 6494 case BitstreamEntry::Error: 6495 return error("Malformed block"); 6496 case BitstreamEntry::EndBlock: 6497 return std::error_code(); 6498 case BitstreamEntry::Record: 6499 // The interesting case. 6500 break; 6501 } 6502 6503 Record.clear(); 6504 switch (Stream.readRecord(Entry.ID, Record)) { 6505 default: // Default behavior: ignore. 6506 break; 6507 case bitc::MST_CODE_ENTRY: { 6508 // MST_ENTRY: [modid, namechar x N] 6509 uint64_t ModuleId = Record[0]; 6510 6511 if (convertToString(Record, 1, ModulePath)) 6512 return error("Invalid record"); 6513 6514 LastSeenModulePath = TheIndex->addModulePath(ModulePath, ModuleId); 6515 ModuleIdMap[ModuleId] = LastSeenModulePath->first(); 6516 6517 ModulePath.clear(); 6518 break; 6519 } 6520 /// MST_CODE_HASH: [5*i32] 6521 case bitc::MST_CODE_HASH: { 6522 if (Record.size() != 5) 6523 return error("Invalid hash length " + Twine(Record.size()).str()); 6524 if (LastSeenModulePath == TheIndex->modulePaths().end()) 6525 return error("Invalid hash that does not follow a module path"); 6526 int Pos = 0; 6527 for (auto &Val : Record) { 6528 assert(!(Val >> 32) && "Unexpected high bits set"); 6529 LastSeenModulePath->second.second[Pos++] = Val; 6530 } 6531 // Reset LastSeenModulePath to avoid overriding the hash unexpectedly. 6532 LastSeenModulePath = TheIndex->modulePaths().end(); 6533 break; 6534 } 6535 } 6536 } 6537 llvm_unreachable("Exit infinite loop"); 6538 } 6539 6540 // Parse the function info index from the bitcode streamer into the given index. 6541 std::error_code ModuleSummaryIndexBitcodeReader::parseSummaryIndexInto( 6542 std::unique_ptr<DataStreamer> Streamer, ModuleSummaryIndex *I) { 6543 TheIndex = I; 6544 6545 if (std::error_code EC = initStream(std::move(Streamer))) 6546 return EC; 6547 6548 // Sniff for the signature. 6549 if (!hasValidBitcodeHeader(Stream)) 6550 return error("Invalid bitcode signature"); 6551 6552 // We expect a number of well-defined blocks, though we don't necessarily 6553 // need to understand them all. 6554 while (true) { 6555 if (Stream.AtEndOfStream()) { 6556 // We didn't really read a proper Module block. 6557 return error("Malformed block"); 6558 } 6559 6560 BitstreamEntry Entry = 6561 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs); 6562 6563 if (Entry.Kind != BitstreamEntry::SubBlock) 6564 return error("Malformed block"); 6565 6566 // If we see a MODULE_BLOCK, parse it to find the blocks needed for 6567 // building the function summary index. 6568 if (Entry.ID == bitc::MODULE_BLOCK_ID) 6569 return parseModule(); 6570 6571 if (Stream.SkipBlock()) 6572 return error("Invalid record"); 6573 } 6574 } 6575 6576 namespace { 6577 6578 // FIXME: This class is only here to support the transition to llvm::Error. It 6579 // will be removed once this transition is complete. Clients should prefer to 6580 // deal with the Error value directly, rather than converting to error_code. 6581 class BitcodeErrorCategoryType : public std::error_category { 6582 const char *name() const LLVM_NOEXCEPT override { 6583 return "llvm.bitcode"; 6584 } 6585 std::string message(int IE) const override { 6586 BitcodeError E = static_cast<BitcodeError>(IE); 6587 switch (E) { 6588 case BitcodeError::InvalidBitcodeSignature: 6589 return "Invalid bitcode signature"; 6590 case BitcodeError::CorruptedBitcode: 6591 return "Corrupted bitcode"; 6592 } 6593 llvm_unreachable("Unknown error type!"); 6594 } 6595 }; 6596 6597 } // end anonymous namespace 6598 6599 static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory; 6600 6601 const std::error_category &llvm::BitcodeErrorCategory() { 6602 return *ErrorCategory; 6603 } 6604 6605 //===----------------------------------------------------------------------===// 6606 // External interface 6607 //===----------------------------------------------------------------------===// 6608 6609 static ErrorOr<std::unique_ptr<Module>> 6610 getBitcodeModuleImpl(std::unique_ptr<DataStreamer> Streamer, StringRef Name, 6611 BitcodeReader *R, LLVMContext &Context, 6612 bool MaterializeAll, bool ShouldLazyLoadMetadata) { 6613 std::unique_ptr<Module> M = llvm::make_unique<Module>(Name, Context); 6614 M->setMaterializer(R); 6615 6616 auto cleanupOnError = [&](std::error_code EC) { 6617 R->releaseBuffer(); // Never take ownership on error. 6618 return EC; 6619 }; 6620 6621 // Delay parsing Metadata if ShouldLazyLoadMetadata is true. 6622 if (std::error_code EC = R->parseBitcodeInto(std::move(Streamer), M.get(), 6623 ShouldLazyLoadMetadata)) 6624 return cleanupOnError(EC); 6625 6626 if (MaterializeAll) { 6627 // Read in the entire module, and destroy the BitcodeReader. 6628 if (std::error_code EC = M->materializeAll()) 6629 return cleanupOnError(EC); 6630 } else { 6631 // Resolve forward references from blockaddresses. 6632 if (std::error_code EC = R->materializeForwardReferencedFunctions()) 6633 return cleanupOnError(EC); 6634 } 6635 return std::move(M); 6636 } 6637 6638 /// \brief Get a lazy one-at-time loading module from bitcode. 6639 /// 6640 /// This isn't always used in a lazy context. In particular, it's also used by 6641 /// \a parseBitcodeFile(). If this is truly lazy, then we need to eagerly pull 6642 /// in forward-referenced functions from block address references. 6643 /// 6644 /// \param[in] MaterializeAll Set to \c true if we should materialize 6645 /// everything. 6646 static ErrorOr<std::unique_ptr<Module>> 6647 getLazyBitcodeModuleImpl(std::unique_ptr<MemoryBuffer> &&Buffer, 6648 LLVMContext &Context, bool MaterializeAll, 6649 bool ShouldLazyLoadMetadata = false) { 6650 BitcodeReader *R = new BitcodeReader(Buffer.get(), Context); 6651 6652 ErrorOr<std::unique_ptr<Module>> Ret = 6653 getBitcodeModuleImpl(nullptr, Buffer->getBufferIdentifier(), R, Context, 6654 MaterializeAll, ShouldLazyLoadMetadata); 6655 if (!Ret) 6656 return Ret; 6657 6658 Buffer.release(); // The BitcodeReader owns it now. 6659 return Ret; 6660 } 6661 6662 ErrorOr<std::unique_ptr<Module>> 6663 llvm::getLazyBitcodeModule(std::unique_ptr<MemoryBuffer> &&Buffer, 6664 LLVMContext &Context, bool ShouldLazyLoadMetadata) { 6665 return getLazyBitcodeModuleImpl(std::move(Buffer), Context, false, 6666 ShouldLazyLoadMetadata); 6667 } 6668 6669 ErrorOr<std::unique_ptr<Module>> 6670 llvm::getStreamedBitcodeModule(StringRef Name, 6671 std::unique_ptr<DataStreamer> Streamer, 6672 LLVMContext &Context) { 6673 std::unique_ptr<Module> M = llvm::make_unique<Module>(Name, Context); 6674 BitcodeReader *R = new BitcodeReader(Context); 6675 6676 return getBitcodeModuleImpl(std::move(Streamer), Name, R, Context, false, 6677 false); 6678 } 6679 6680 ErrorOr<std::unique_ptr<Module>> llvm::parseBitcodeFile(MemoryBufferRef Buffer, 6681 LLVMContext &Context) { 6682 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false); 6683 return getLazyBitcodeModuleImpl(std::move(Buf), Context, true); 6684 // TODO: Restore the use-lists to the in-memory state when the bitcode was 6685 // written. We must defer until the Module has been fully materialized. 6686 } 6687 6688 std::string llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer, 6689 LLVMContext &Context) { 6690 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false); 6691 auto R = llvm::make_unique<BitcodeReader>(Buf.release(), Context); 6692 ErrorOr<std::string> Triple = R->parseTriple(); 6693 if (Triple.getError()) 6694 return ""; 6695 return Triple.get(); 6696 } 6697 6698 bool llvm::isBitcodeContainingObjCCategory(MemoryBufferRef Buffer, 6699 LLVMContext &Context) { 6700 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false); 6701 auto R = llvm::make_unique<BitcodeReader>(Buf.release(), Context); 6702 ErrorOr<bool> hasObjCCategory = R->hasObjCCategory(); 6703 if (hasObjCCategory.getError()) 6704 return false; 6705 return hasObjCCategory.get(); 6706 } 6707 6708 std::string llvm::getBitcodeProducerString(MemoryBufferRef Buffer, 6709 LLVMContext &Context) { 6710 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false); 6711 BitcodeReader R(Buf.release(), Context); 6712 ErrorOr<std::string> ProducerString = R.parseIdentificationBlock(); 6713 if (ProducerString.getError()) 6714 return ""; 6715 return ProducerString.get(); 6716 } 6717 6718 // Parse the specified bitcode buffer, returning the function info index. 6719 ErrorOr<std::unique_ptr<ModuleSummaryIndex>> llvm::getModuleSummaryIndex( 6720 MemoryBufferRef Buffer, 6721 const DiagnosticHandlerFunction &DiagnosticHandler) { 6722 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false); 6723 ModuleSummaryIndexBitcodeReader R(Buf.get(), DiagnosticHandler); 6724 6725 auto Index = llvm::make_unique<ModuleSummaryIndex>(); 6726 6727 auto cleanupOnError = [&](std::error_code EC) { 6728 R.releaseBuffer(); // Never take ownership on error. 6729 return EC; 6730 }; 6731 6732 if (std::error_code EC = R.parseSummaryIndexInto(nullptr, Index.get())) 6733 return cleanupOnError(EC); 6734 6735 Buf.release(); // The ModuleSummaryIndexBitcodeReader owns it now. 6736 return std::move(Index); 6737 } 6738 6739 // Check if the given bitcode buffer contains a global value summary block. 6740 bool llvm::hasGlobalValueSummary( 6741 MemoryBufferRef Buffer, 6742 const DiagnosticHandlerFunction &DiagnosticHandler) { 6743 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false); 6744 ModuleSummaryIndexBitcodeReader R(Buf.get(), DiagnosticHandler, true); 6745 6746 auto cleanupOnError = [&](std::error_code EC) { 6747 R.releaseBuffer(); // Never take ownership on error. 6748 return false; 6749 }; 6750 6751 if (std::error_code EC = R.parseSummaryIndexInto(nullptr, nullptr)) 6752 return cleanupOnError(EC); 6753 6754 Buf.release(); // The ModuleSummaryIndexBitcodeReader owns it now. 6755 return R.foundGlobalValSummary(); 6756 } 6757