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