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