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