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