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