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