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