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