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