1 //===-- Verifier.cpp - Implement the Module Verifier -----------------------==// 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 // This file defines the function verifier interface, that can be used for some 11 // sanity checking of input to the system. 12 // 13 // Note that this does not provide full `Java style' security and verifications, 14 // instead it just tries to ensure that code is well-formed. 15 // 16 // * Both of a binary operator's parameters are of the same type 17 // * Verify that the indices of mem access instructions match other operands 18 // * Verify that arithmetic and other things are only performed on first-class 19 // types. Verify that shifts & logicals only happen on integrals f.e. 20 // * All of the constants in a switch statement are of the correct type 21 // * The code is in valid SSA form 22 // * It should be illegal to put a label into any other type (like a structure) 23 // or to return one. [except constant arrays!] 24 // * Only phi nodes can be self referential: 'add i32 %0, %0 ; <int>:0' is bad 25 // * PHI nodes must have an entry for each predecessor, with no extras. 26 // * PHI nodes must be the first thing in a basic block, all grouped together 27 // * PHI nodes must have at least one entry 28 // * All basic blocks should only end with terminator insts, not contain them 29 // * The entry node to a function must not have predecessors 30 // * All Instructions must be embedded into a basic block 31 // * Functions cannot take a void-typed parameter 32 // * Verify that a function's argument list agrees with it's declared type. 33 // * It is illegal to specify a name for a void value. 34 // * It is illegal to have a internal global value with no initializer 35 // * It is illegal to have a ret instruction that returns a value that does not 36 // agree with the function return value type. 37 // * Function call argument types match the function prototype 38 // * A landing pad is defined by a landingpad instruction, and can be jumped to 39 // only by the unwind edge of an invoke instruction. 40 // * A landingpad instruction must be the first non-PHI instruction in the 41 // block. 42 // * Landingpad instructions must be in a function with a personality function. 43 // * All other things that are tested by asserts spread about the code... 44 // 45 //===----------------------------------------------------------------------===// 46 47 #include "llvm/IR/Verifier.h" 48 #include "llvm/ADT/APFloat.h" 49 #include "llvm/ADT/APInt.h" 50 #include "llvm/ADT/ArrayRef.h" 51 #include "llvm/ADT/DenseMap.h" 52 #include "llvm/ADT/ilist.h" 53 #include "llvm/ADT/MapVector.h" 54 #include "llvm/ADT/Optional.h" 55 #include "llvm/ADT/STLExtras.h" 56 #include "llvm/ADT/SmallPtrSet.h" 57 #include "llvm/ADT/SmallSet.h" 58 #include "llvm/ADT/SmallVector.h" 59 #include "llvm/ADT/StringMap.h" 60 #include "llvm/ADT/StringRef.h" 61 #include "llvm/ADT/Twine.h" 62 #include "llvm/IR/Argument.h" 63 #include "llvm/IR/Attributes.h" 64 #include "llvm/IR/BasicBlock.h" 65 #include "llvm/IR/CFG.h" 66 #include "llvm/IR/CallSite.h" 67 #include "llvm/IR/CallingConv.h" 68 #include "llvm/IR/Comdat.h" 69 #include "llvm/IR/Constant.h" 70 #include "llvm/IR/ConstantRange.h" 71 #include "llvm/IR/Constants.h" 72 #include "llvm/IR/DataLayout.h" 73 #include "llvm/IR/DebugInfo.h" 74 #include "llvm/IR/DebugInfoMetadata.h" 75 #include "llvm/IR/DebugLoc.h" 76 #include "llvm/IR/DerivedTypes.h" 77 #include "llvm/IR/DiagnosticInfo.h" 78 #include "llvm/IR/Dominators.h" 79 #include "llvm/IR/Function.h" 80 #include "llvm/IR/GlobalAlias.h" 81 #include "llvm/IR/GlobalValue.h" 82 #include "llvm/IR/GlobalVariable.h" 83 #include "llvm/IR/InlineAsm.h" 84 #include "llvm/IR/InstrTypes.h" 85 #include "llvm/IR/Instruction.h" 86 #include "llvm/IR/Instructions.h" 87 #include "llvm/IR/InstVisitor.h" 88 #include "llvm/IR/IntrinsicInst.h" 89 #include "llvm/IR/Intrinsics.h" 90 #include "llvm/IR/LLVMContext.h" 91 #include "llvm/IR/Metadata.h" 92 #include "llvm/IR/Module.h" 93 #include "llvm/IR/ModuleSlotTracker.h" 94 #include "llvm/IR/PassManager.h" 95 #include "llvm/IR/Statepoint.h" 96 #include "llvm/IR/Type.h" 97 #include "llvm/IR/Use.h" 98 #include "llvm/IR/User.h" 99 #include "llvm/IR/Value.h" 100 #include "llvm/Pass.h" 101 #include "llvm/Support/AtomicOrdering.h" 102 #include "llvm/Support/Casting.h" 103 #include "llvm/Support/CommandLine.h" 104 #include "llvm/Support/Debug.h" 105 #include "llvm/Support/Dwarf.h" 106 #include "llvm/Support/ErrorHandling.h" 107 #include "llvm/Support/MathExtras.h" 108 #include "llvm/Support/raw_ostream.h" 109 #include <algorithm> 110 #include <cassert> 111 #include <cstdint> 112 #include <memory> 113 #include <string> 114 #include <utility> 115 116 using namespace llvm; 117 118 static cl::opt<bool> VerifyDebugInfo("verify-debug-info", cl::init(true)); 119 120 namespace llvm { 121 122 struct VerifierSupport { 123 raw_ostream *OS; 124 const Module &M; 125 ModuleSlotTracker MST; 126 const DataLayout &DL; 127 LLVMContext &Context; 128 129 /// Track the brokenness of the module while recursively visiting. 130 bool Broken = false; 131 /// Broken debug info can be "recovered" from by stripping the debug info. 132 bool BrokenDebugInfo = false; 133 /// Whether to treat broken debug info as an error. 134 bool TreatBrokenDebugInfoAsError = true; 135 136 explicit VerifierSupport(raw_ostream *OS, const Module &M) 137 : OS(OS), M(M), MST(&M), DL(M.getDataLayout()), Context(M.getContext()) {} 138 139 private: 140 void Write(const Module *M) { 141 *OS << "; ModuleID = '" << M->getModuleIdentifier() << "'\n"; 142 } 143 144 void Write(const Value *V) { 145 if (!V) 146 return; 147 if (isa<Instruction>(V)) { 148 V->print(*OS, MST); 149 *OS << '\n'; 150 } else { 151 V->printAsOperand(*OS, true, MST); 152 *OS << '\n'; 153 } 154 } 155 156 void Write(ImmutableCallSite CS) { 157 Write(CS.getInstruction()); 158 } 159 160 void Write(const Metadata *MD) { 161 if (!MD) 162 return; 163 MD->print(*OS, MST, &M); 164 *OS << '\n'; 165 } 166 167 template <class T> void Write(const MDTupleTypedArrayWrapper<T> &MD) { 168 Write(MD.get()); 169 } 170 171 void Write(const NamedMDNode *NMD) { 172 if (!NMD) 173 return; 174 NMD->print(*OS, MST); 175 *OS << '\n'; 176 } 177 178 void Write(Type *T) { 179 if (!T) 180 return; 181 *OS << ' ' << *T; 182 } 183 184 void Write(const Comdat *C) { 185 if (!C) 186 return; 187 *OS << *C; 188 } 189 190 void Write(const APInt *AI) { 191 if (!AI) 192 return; 193 *OS << *AI << '\n'; 194 } 195 196 void Write(const unsigned i) { *OS << i << '\n'; } 197 198 template <typename T> void Write(ArrayRef<T> Vs) { 199 for (const T &V : Vs) 200 Write(V); 201 } 202 203 template <typename T1, typename... Ts> 204 void WriteTs(const T1 &V1, const Ts &... Vs) { 205 Write(V1); 206 WriteTs(Vs...); 207 } 208 209 template <typename... Ts> void WriteTs() {} 210 211 public: 212 /// \brief A check failed, so printout out the condition and the message. 213 /// 214 /// This provides a nice place to put a breakpoint if you want to see why 215 /// something is not correct. 216 void CheckFailed(const Twine &Message) { 217 if (OS) 218 *OS << Message << '\n'; 219 Broken = true; 220 } 221 222 /// \brief A check failed (with values to print). 223 /// 224 /// This calls the Message-only version so that the above is easier to set a 225 /// breakpoint on. 226 template <typename T1, typename... Ts> 227 void CheckFailed(const Twine &Message, const T1 &V1, const Ts &... Vs) { 228 CheckFailed(Message); 229 if (OS) 230 WriteTs(V1, Vs...); 231 } 232 233 /// A debug info check failed. 234 void DebugInfoCheckFailed(const Twine &Message) { 235 if (OS) 236 *OS << Message << '\n'; 237 Broken |= TreatBrokenDebugInfoAsError; 238 BrokenDebugInfo = true; 239 } 240 241 /// A debug info check failed (with values to print). 242 template <typename T1, typename... Ts> 243 void DebugInfoCheckFailed(const Twine &Message, const T1 &V1, 244 const Ts &... Vs) { 245 DebugInfoCheckFailed(Message); 246 if (OS) 247 WriteTs(V1, Vs...); 248 } 249 }; 250 251 } // namespace llvm 252 253 namespace { 254 255 class Verifier : public InstVisitor<Verifier>, VerifierSupport { 256 friend class InstVisitor<Verifier>; 257 258 DominatorTree DT; 259 260 /// \brief When verifying a basic block, keep track of all of the 261 /// instructions we have seen so far. 262 /// 263 /// This allows us to do efficient dominance checks for the case when an 264 /// instruction has an operand that is an instruction in the same block. 265 SmallPtrSet<Instruction *, 16> InstsInThisBlock; 266 267 /// \brief Keep track of the metadata nodes that have been checked already. 268 SmallPtrSet<const Metadata *, 32> MDNodes; 269 270 /// Track all DICompileUnits visited. 271 SmallPtrSet<const Metadata *, 2> CUVisited; 272 273 /// \brief The result type for a landingpad. 274 Type *LandingPadResultTy; 275 276 /// \brief Whether we've seen a call to @llvm.localescape in this function 277 /// already. 278 bool SawFrameEscape; 279 280 /// Whether the current function has a DISubprogram attached to it. 281 bool HasDebugInfo = false; 282 283 /// Stores the count of how many objects were passed to llvm.localescape for a 284 /// given function and the largest index passed to llvm.localrecover. 285 DenseMap<Function *, std::pair<unsigned, unsigned>> FrameEscapeInfo; 286 287 // Maps catchswitches and cleanuppads that unwind to siblings to the 288 // terminators that indicate the unwind, used to detect cycles therein. 289 MapVector<Instruction *, TerminatorInst *> SiblingFuncletInfo; 290 291 /// Cache of constants visited in search of ConstantExprs. 292 SmallPtrSet<const Constant *, 32> ConstantExprVisited; 293 294 /// Cache of declarations of the llvm.experimental.deoptimize.<ty> intrinsic. 295 SmallVector<const Function *, 4> DeoptimizeDeclarations; 296 297 // Verify that this GlobalValue is only used in this module. 298 // This map is used to avoid visiting uses twice. We can arrive at a user 299 // twice, if they have multiple operands. In particular for very large 300 // constant expressions, we can arrive at a particular user many times. 301 SmallPtrSet<const Value *, 32> GlobalValueVisited; 302 303 // Keeps track of duplicate function argument debug info. 304 SmallVector<const DILocalVariable *, 16> DebugFnArgs; 305 306 TBAAVerifier TBAAVerifyHelper; 307 308 void checkAtomicMemAccessSize(Type *Ty, const Instruction *I); 309 310 public: 311 explicit Verifier(raw_ostream *OS, bool ShouldTreatBrokenDebugInfoAsError, 312 const Module &M) 313 : VerifierSupport(OS, M), LandingPadResultTy(nullptr), 314 SawFrameEscape(false), TBAAVerifyHelper(this) { 315 TreatBrokenDebugInfoAsError = ShouldTreatBrokenDebugInfoAsError; 316 } 317 318 bool hasBrokenDebugInfo() const { return BrokenDebugInfo; } 319 320 bool verify(const Function &F) { 321 assert(F.getParent() == &M && 322 "An instance of this class only works with a specific module!"); 323 324 // First ensure the function is well-enough formed to compute dominance 325 // information, and directly compute a dominance tree. We don't rely on the 326 // pass manager to provide this as it isolates us from a potentially 327 // out-of-date dominator tree and makes it significantly more complex to run 328 // this code outside of a pass manager. 329 // FIXME: It's really gross that we have to cast away constness here. 330 if (!F.empty()) 331 DT.recalculate(const_cast<Function &>(F)); 332 333 for (const BasicBlock &BB : F) { 334 if (!BB.empty() && BB.back().isTerminator()) 335 continue; 336 337 if (OS) { 338 *OS << "Basic Block in function '" << F.getName() 339 << "' does not have terminator!\n"; 340 BB.printAsOperand(*OS, true, MST); 341 *OS << "\n"; 342 } 343 return false; 344 } 345 346 Broken = false; 347 // FIXME: We strip const here because the inst visitor strips const. 348 visit(const_cast<Function &>(F)); 349 verifySiblingFuncletUnwinds(); 350 InstsInThisBlock.clear(); 351 DebugFnArgs.clear(); 352 LandingPadResultTy = nullptr; 353 SawFrameEscape = false; 354 SiblingFuncletInfo.clear(); 355 356 return !Broken; 357 } 358 359 /// Verify the module that this instance of \c Verifier was initialized with. 360 bool verify() { 361 Broken = false; 362 363 // Collect all declarations of the llvm.experimental.deoptimize intrinsic. 364 for (const Function &F : M) 365 if (F.getIntrinsicID() == Intrinsic::experimental_deoptimize) 366 DeoptimizeDeclarations.push_back(&F); 367 368 // Now that we've visited every function, verify that we never asked to 369 // recover a frame index that wasn't escaped. 370 verifyFrameRecoverIndices(); 371 for (const GlobalVariable &GV : M.globals()) 372 visitGlobalVariable(GV); 373 374 for (const GlobalAlias &GA : M.aliases()) 375 visitGlobalAlias(GA); 376 377 for (const NamedMDNode &NMD : M.named_metadata()) 378 visitNamedMDNode(NMD); 379 380 for (const StringMapEntry<Comdat> &SMEC : M.getComdatSymbolTable()) 381 visitComdat(SMEC.getValue()); 382 383 visitModuleFlags(M); 384 visitModuleIdents(M); 385 386 verifyCompileUnits(); 387 388 verifyDeoptimizeCallingConvs(); 389 390 return !Broken; 391 } 392 393 private: 394 // Verification methods... 395 void visitGlobalValue(const GlobalValue &GV); 396 void visitGlobalVariable(const GlobalVariable &GV); 397 void visitGlobalAlias(const GlobalAlias &GA); 398 void visitAliaseeSubExpr(const GlobalAlias &A, const Constant &C); 399 void visitAliaseeSubExpr(SmallPtrSetImpl<const GlobalAlias *> &Visited, 400 const GlobalAlias &A, const Constant &C); 401 void visitNamedMDNode(const NamedMDNode &NMD); 402 void visitMDNode(const MDNode &MD); 403 void visitMetadataAsValue(const MetadataAsValue &MD, Function *F); 404 void visitValueAsMetadata(const ValueAsMetadata &MD, Function *F); 405 void visitComdat(const Comdat &C); 406 void visitModuleIdents(const Module &M); 407 void visitModuleFlags(const Module &M); 408 void visitModuleFlag(const MDNode *Op, 409 DenseMap<const MDString *, const MDNode *> &SeenIDs, 410 SmallVectorImpl<const MDNode *> &Requirements); 411 void visitFunction(const Function &F); 412 void visitBasicBlock(BasicBlock &BB); 413 void visitRangeMetadata(Instruction &I, MDNode *Range, Type *Ty); 414 void visitDereferenceableMetadata(Instruction &I, MDNode *MD); 415 416 template <class Ty> bool isValidMetadataArray(const MDTuple &N); 417 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) void visit##CLASS(const CLASS &N); 418 #include "llvm/IR/Metadata.def" 419 void visitDIScope(const DIScope &N); 420 void visitDIVariable(const DIVariable &N); 421 void visitDILexicalBlockBase(const DILexicalBlockBase &N); 422 void visitDITemplateParameter(const DITemplateParameter &N); 423 424 void visitTemplateParams(const MDNode &N, const Metadata &RawParams); 425 426 // InstVisitor overrides... 427 using InstVisitor<Verifier>::visit; 428 void visit(Instruction &I); 429 430 void visitTruncInst(TruncInst &I); 431 void visitZExtInst(ZExtInst &I); 432 void visitSExtInst(SExtInst &I); 433 void visitFPTruncInst(FPTruncInst &I); 434 void visitFPExtInst(FPExtInst &I); 435 void visitFPToUIInst(FPToUIInst &I); 436 void visitFPToSIInst(FPToSIInst &I); 437 void visitUIToFPInst(UIToFPInst &I); 438 void visitSIToFPInst(SIToFPInst &I); 439 void visitIntToPtrInst(IntToPtrInst &I); 440 void visitPtrToIntInst(PtrToIntInst &I); 441 void visitBitCastInst(BitCastInst &I); 442 void visitAddrSpaceCastInst(AddrSpaceCastInst &I); 443 void visitPHINode(PHINode &PN); 444 void visitBinaryOperator(BinaryOperator &B); 445 void visitICmpInst(ICmpInst &IC); 446 void visitFCmpInst(FCmpInst &FC); 447 void visitExtractElementInst(ExtractElementInst &EI); 448 void visitInsertElementInst(InsertElementInst &EI); 449 void visitShuffleVectorInst(ShuffleVectorInst &EI); 450 void visitVAArgInst(VAArgInst &VAA) { visitInstruction(VAA); } 451 void visitCallInst(CallInst &CI); 452 void visitInvokeInst(InvokeInst &II); 453 void visitGetElementPtrInst(GetElementPtrInst &GEP); 454 void visitLoadInst(LoadInst &LI); 455 void visitStoreInst(StoreInst &SI); 456 void verifyDominatesUse(Instruction &I, unsigned i); 457 void visitInstruction(Instruction &I); 458 void visitTerminatorInst(TerminatorInst &I); 459 void visitBranchInst(BranchInst &BI); 460 void visitReturnInst(ReturnInst &RI); 461 void visitSwitchInst(SwitchInst &SI); 462 void visitIndirectBrInst(IndirectBrInst &BI); 463 void visitSelectInst(SelectInst &SI); 464 void visitUserOp1(Instruction &I); 465 void visitUserOp2(Instruction &I) { visitUserOp1(I); } 466 void visitIntrinsicCallSite(Intrinsic::ID ID, CallSite CS); 467 void visitConstrainedFPIntrinsic(ConstrainedFPIntrinsic &FPI); 468 template <class DbgIntrinsicTy> 469 void visitDbgIntrinsic(StringRef Kind, DbgIntrinsicTy &DII); 470 void visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI); 471 void visitAtomicRMWInst(AtomicRMWInst &RMWI); 472 void visitFenceInst(FenceInst &FI); 473 void visitAllocaInst(AllocaInst &AI); 474 void visitExtractValueInst(ExtractValueInst &EVI); 475 void visitInsertValueInst(InsertValueInst &IVI); 476 void visitEHPadPredecessors(Instruction &I); 477 void visitLandingPadInst(LandingPadInst &LPI); 478 void visitResumeInst(ResumeInst &RI); 479 void visitCatchPadInst(CatchPadInst &CPI); 480 void visitCatchReturnInst(CatchReturnInst &CatchReturn); 481 void visitCleanupPadInst(CleanupPadInst &CPI); 482 void visitFuncletPadInst(FuncletPadInst &FPI); 483 void visitCatchSwitchInst(CatchSwitchInst &CatchSwitch); 484 void visitCleanupReturnInst(CleanupReturnInst &CRI); 485 486 void verifyCallSite(CallSite CS); 487 void verifySwiftErrorCallSite(CallSite CS, const Value *SwiftErrorVal); 488 void verifySwiftErrorValue(const Value *SwiftErrorVal); 489 void verifyMustTailCall(CallInst &CI); 490 bool performTypeCheck(Intrinsic::ID ID, Function *F, Type *Ty, int VT, 491 unsigned ArgNo, std::string &Suffix); 492 bool verifyAttributeCount(AttributeList Attrs, unsigned Params); 493 void verifyAttributeTypes(AttributeSet Attrs, bool IsFunction, 494 const Value *V); 495 void verifyParameterAttrs(AttributeSet Attrs, Type *Ty, const Value *V); 496 void verifyFunctionAttrs(FunctionType *FT, AttributeList Attrs, 497 const Value *V); 498 void verifyFunctionMetadata(ArrayRef<std::pair<unsigned, MDNode *>> MDs); 499 500 void visitConstantExprsRecursively(const Constant *EntryC); 501 void visitConstantExpr(const ConstantExpr *CE); 502 void verifyStatepoint(ImmutableCallSite CS); 503 void verifyFrameRecoverIndices(); 504 void verifySiblingFuncletUnwinds(); 505 506 void verifyFragmentExpression(const DbgInfoIntrinsic &I); 507 void verifyFnArgs(const DbgInfoIntrinsic &I); 508 509 /// Module-level debug info verification... 510 void verifyCompileUnits(); 511 512 /// Module-level verification that all @llvm.experimental.deoptimize 513 /// declarations share the same calling convention. 514 void verifyDeoptimizeCallingConvs(); 515 }; 516 517 } // end anonymous namespace 518 519 /// We know that cond should be true, if not print an error message. 520 #define Assert(C, ...) \ 521 do { if (!(C)) { CheckFailed(__VA_ARGS__); return; } } while (false) 522 523 /// We know that a debug info condition should be true, if not print 524 /// an error message. 525 #define AssertDI(C, ...) \ 526 do { if (!(C)) { DebugInfoCheckFailed(__VA_ARGS__); return; } } while (false) 527 528 void Verifier::visit(Instruction &I) { 529 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) 530 Assert(I.getOperand(i) != nullptr, "Operand is null", &I); 531 InstVisitor<Verifier>::visit(I); 532 } 533 534 // Helper to recursively iterate over indirect users. By 535 // returning false, the callback can ask to stop recursing 536 // further. 537 static void forEachUser(const Value *User, 538 SmallPtrSet<const Value *, 32> &Visited, 539 llvm::function_ref<bool(const Value *)> Callback) { 540 if (!Visited.insert(User).second) 541 return; 542 for (const Value *TheNextUser : User->materialized_users()) 543 if (Callback(TheNextUser)) 544 forEachUser(TheNextUser, Visited, Callback); 545 } 546 547 void Verifier::visitGlobalValue(const GlobalValue &GV) { 548 Assert(!GV.isDeclaration() || GV.hasValidDeclarationLinkage(), 549 "Global is external, but doesn't have external or weak linkage!", &GV); 550 551 Assert(GV.getAlignment() <= Value::MaximumAlignment, 552 "huge alignment values are unsupported", &GV); 553 Assert(!GV.hasAppendingLinkage() || isa<GlobalVariable>(GV), 554 "Only global variables can have appending linkage!", &GV); 555 556 if (GV.hasAppendingLinkage()) { 557 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(&GV); 558 Assert(GVar && GVar->getValueType()->isArrayTy(), 559 "Only global arrays can have appending linkage!", GVar); 560 } 561 562 if (GV.isDeclarationForLinker()) 563 Assert(!GV.hasComdat(), "Declaration may not be in a Comdat!", &GV); 564 565 forEachUser(&GV, GlobalValueVisited, [&](const Value *V) -> bool { 566 if (const Instruction *I = dyn_cast<Instruction>(V)) { 567 if (!I->getParent() || !I->getParent()->getParent()) 568 CheckFailed("Global is referenced by parentless instruction!", &GV, &M, 569 I); 570 else if (I->getParent()->getParent()->getParent() != &M) 571 CheckFailed("Global is referenced in a different module!", &GV, &M, I, 572 I->getParent()->getParent(), 573 I->getParent()->getParent()->getParent()); 574 return false; 575 } else if (const Function *F = dyn_cast<Function>(V)) { 576 if (F->getParent() != &M) 577 CheckFailed("Global is used by function in a different module", &GV, &M, 578 F, F->getParent()); 579 return false; 580 } 581 return true; 582 }); 583 } 584 585 void Verifier::visitGlobalVariable(const GlobalVariable &GV) { 586 if (GV.hasInitializer()) { 587 Assert(GV.getInitializer()->getType() == GV.getValueType(), 588 "Global variable initializer type does not match global " 589 "variable type!", 590 &GV); 591 // If the global has common linkage, it must have a zero initializer and 592 // cannot be constant. 593 if (GV.hasCommonLinkage()) { 594 Assert(GV.getInitializer()->isNullValue(), 595 "'common' global must have a zero initializer!", &GV); 596 Assert(!GV.isConstant(), "'common' global may not be marked constant!", 597 &GV); 598 Assert(!GV.hasComdat(), "'common' global may not be in a Comdat!", &GV); 599 } 600 } 601 602 if (GV.hasName() && (GV.getName() == "llvm.global_ctors" || 603 GV.getName() == "llvm.global_dtors")) { 604 Assert(!GV.hasInitializer() || GV.hasAppendingLinkage(), 605 "invalid linkage for intrinsic global variable", &GV); 606 // Don't worry about emitting an error for it not being an array, 607 // visitGlobalValue will complain on appending non-array. 608 if (ArrayType *ATy = dyn_cast<ArrayType>(GV.getValueType())) { 609 StructType *STy = dyn_cast<StructType>(ATy->getElementType()); 610 PointerType *FuncPtrTy = 611 FunctionType::get(Type::getVoidTy(Context), false)->getPointerTo(); 612 // FIXME: Reject the 2-field form in LLVM 4.0. 613 Assert(STy && 614 (STy->getNumElements() == 2 || STy->getNumElements() == 3) && 615 STy->getTypeAtIndex(0u)->isIntegerTy(32) && 616 STy->getTypeAtIndex(1) == FuncPtrTy, 617 "wrong type for intrinsic global variable", &GV); 618 if (STy->getNumElements() == 3) { 619 Type *ETy = STy->getTypeAtIndex(2); 620 Assert(ETy->isPointerTy() && 621 cast<PointerType>(ETy)->getElementType()->isIntegerTy(8), 622 "wrong type for intrinsic global variable", &GV); 623 } 624 } 625 } 626 627 if (GV.hasName() && (GV.getName() == "llvm.used" || 628 GV.getName() == "llvm.compiler.used")) { 629 Assert(!GV.hasInitializer() || GV.hasAppendingLinkage(), 630 "invalid linkage for intrinsic global variable", &GV); 631 Type *GVType = GV.getValueType(); 632 if (ArrayType *ATy = dyn_cast<ArrayType>(GVType)) { 633 PointerType *PTy = dyn_cast<PointerType>(ATy->getElementType()); 634 Assert(PTy, "wrong type for intrinsic global variable", &GV); 635 if (GV.hasInitializer()) { 636 const Constant *Init = GV.getInitializer(); 637 const ConstantArray *InitArray = dyn_cast<ConstantArray>(Init); 638 Assert(InitArray, "wrong initalizer for intrinsic global variable", 639 Init); 640 for (Value *Op : InitArray->operands()) { 641 Value *V = Op->stripPointerCastsNoFollowAliases(); 642 Assert(isa<GlobalVariable>(V) || isa<Function>(V) || 643 isa<GlobalAlias>(V), 644 "invalid llvm.used member", V); 645 Assert(V->hasName(), "members of llvm.used must be named", V); 646 } 647 } 648 } 649 } 650 651 Assert(!GV.hasDLLImportStorageClass() || 652 (GV.isDeclaration() && GV.hasExternalLinkage()) || 653 GV.hasAvailableExternallyLinkage(), 654 "Global is marked as dllimport, but not external", &GV); 655 656 // Visit any debug info attachments. 657 SmallVector<MDNode *, 1> MDs; 658 GV.getMetadata(LLVMContext::MD_dbg, MDs); 659 for (auto *MD : MDs) { 660 if (auto *GVE = dyn_cast<DIGlobalVariableExpression>(MD)) 661 visitDIGlobalVariableExpression(*GVE); 662 else 663 AssertDI(false, "!dbg attachment of global variable must be a " 664 "DIGlobalVariableExpression"); 665 } 666 667 if (!GV.hasInitializer()) { 668 visitGlobalValue(GV); 669 return; 670 } 671 672 // Walk any aggregate initializers looking for bitcasts between address spaces 673 visitConstantExprsRecursively(GV.getInitializer()); 674 675 visitGlobalValue(GV); 676 } 677 678 void Verifier::visitAliaseeSubExpr(const GlobalAlias &GA, const Constant &C) { 679 SmallPtrSet<const GlobalAlias*, 4> Visited; 680 Visited.insert(&GA); 681 visitAliaseeSubExpr(Visited, GA, C); 682 } 683 684 void Verifier::visitAliaseeSubExpr(SmallPtrSetImpl<const GlobalAlias*> &Visited, 685 const GlobalAlias &GA, const Constant &C) { 686 if (const auto *GV = dyn_cast<GlobalValue>(&C)) { 687 Assert(!GV->isDeclarationForLinker(), "Alias must point to a definition", 688 &GA); 689 690 if (const auto *GA2 = dyn_cast<GlobalAlias>(GV)) { 691 Assert(Visited.insert(GA2).second, "Aliases cannot form a cycle", &GA); 692 693 Assert(!GA2->isInterposable(), "Alias cannot point to an interposable alias", 694 &GA); 695 } else { 696 // Only continue verifying subexpressions of GlobalAliases. 697 // Do not recurse into global initializers. 698 return; 699 } 700 } 701 702 if (const auto *CE = dyn_cast<ConstantExpr>(&C)) 703 visitConstantExprsRecursively(CE); 704 705 for (const Use &U : C.operands()) { 706 Value *V = &*U; 707 if (const auto *GA2 = dyn_cast<GlobalAlias>(V)) 708 visitAliaseeSubExpr(Visited, GA, *GA2->getAliasee()); 709 else if (const auto *C2 = dyn_cast<Constant>(V)) 710 visitAliaseeSubExpr(Visited, GA, *C2); 711 } 712 } 713 714 void Verifier::visitGlobalAlias(const GlobalAlias &GA) { 715 Assert(GlobalAlias::isValidLinkage(GA.getLinkage()), 716 "Alias should have private, internal, linkonce, weak, linkonce_odr, " 717 "weak_odr, or external linkage!", 718 &GA); 719 const Constant *Aliasee = GA.getAliasee(); 720 Assert(Aliasee, "Aliasee cannot be NULL!", &GA); 721 Assert(GA.getType() == Aliasee->getType(), 722 "Alias and aliasee types should match!", &GA); 723 724 Assert(isa<GlobalValue>(Aliasee) || isa<ConstantExpr>(Aliasee), 725 "Aliasee should be either GlobalValue or ConstantExpr", &GA); 726 727 visitAliaseeSubExpr(GA, *Aliasee); 728 729 visitGlobalValue(GA); 730 } 731 732 void Verifier::visitNamedMDNode(const NamedMDNode &NMD) { 733 // There used to be various other llvm.dbg.* nodes, but we don't support 734 // upgrading them and we want to reserve the namespace for future uses. 735 if (NMD.getName().startswith("llvm.dbg.")) 736 AssertDI(NMD.getName() == "llvm.dbg.cu", 737 "unrecognized named metadata node in the llvm.dbg namespace", 738 &NMD); 739 for (const MDNode *MD : NMD.operands()) { 740 if (NMD.getName() == "llvm.dbg.cu") 741 AssertDI(MD && isa<DICompileUnit>(MD), "invalid compile unit", &NMD, MD); 742 743 if (!MD) 744 continue; 745 746 visitMDNode(*MD); 747 } 748 } 749 750 void Verifier::visitMDNode(const MDNode &MD) { 751 // Only visit each node once. Metadata can be mutually recursive, so this 752 // avoids infinite recursion here, as well as being an optimization. 753 if (!MDNodes.insert(&MD).second) 754 return; 755 756 switch (MD.getMetadataID()) { 757 default: 758 llvm_unreachable("Invalid MDNode subclass"); 759 case Metadata::MDTupleKind: 760 break; 761 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \ 762 case Metadata::CLASS##Kind: \ 763 visit##CLASS(cast<CLASS>(MD)); \ 764 break; 765 #include "llvm/IR/Metadata.def" 766 } 767 768 for (const Metadata *Op : MD.operands()) { 769 if (!Op) 770 continue; 771 Assert(!isa<LocalAsMetadata>(Op), "Invalid operand for global metadata!", 772 &MD, Op); 773 if (auto *N = dyn_cast<MDNode>(Op)) { 774 visitMDNode(*N); 775 continue; 776 } 777 if (auto *V = dyn_cast<ValueAsMetadata>(Op)) { 778 visitValueAsMetadata(*V, nullptr); 779 continue; 780 } 781 } 782 783 // Check these last, so we diagnose problems in operands first. 784 Assert(!MD.isTemporary(), "Expected no forward declarations!", &MD); 785 Assert(MD.isResolved(), "All nodes should be resolved!", &MD); 786 } 787 788 void Verifier::visitValueAsMetadata(const ValueAsMetadata &MD, Function *F) { 789 Assert(MD.getValue(), "Expected valid value", &MD); 790 Assert(!MD.getValue()->getType()->isMetadataTy(), 791 "Unexpected metadata round-trip through values", &MD, MD.getValue()); 792 793 auto *L = dyn_cast<LocalAsMetadata>(&MD); 794 if (!L) 795 return; 796 797 Assert(F, "function-local metadata used outside a function", L); 798 799 // If this was an instruction, bb, or argument, verify that it is in the 800 // function that we expect. 801 Function *ActualF = nullptr; 802 if (Instruction *I = dyn_cast<Instruction>(L->getValue())) { 803 Assert(I->getParent(), "function-local metadata not in basic block", L, I); 804 ActualF = I->getParent()->getParent(); 805 } else if (BasicBlock *BB = dyn_cast<BasicBlock>(L->getValue())) 806 ActualF = BB->getParent(); 807 else if (Argument *A = dyn_cast<Argument>(L->getValue())) 808 ActualF = A->getParent(); 809 assert(ActualF && "Unimplemented function local metadata case!"); 810 811 Assert(ActualF == F, "function-local metadata used in wrong function", L); 812 } 813 814 void Verifier::visitMetadataAsValue(const MetadataAsValue &MDV, Function *F) { 815 Metadata *MD = MDV.getMetadata(); 816 if (auto *N = dyn_cast<MDNode>(MD)) { 817 visitMDNode(*N); 818 return; 819 } 820 821 // Only visit each node once. Metadata can be mutually recursive, so this 822 // avoids infinite recursion here, as well as being an optimization. 823 if (!MDNodes.insert(MD).second) 824 return; 825 826 if (auto *V = dyn_cast<ValueAsMetadata>(MD)) 827 visitValueAsMetadata(*V, F); 828 } 829 830 static bool isType(const Metadata *MD) { return !MD || isa<DIType>(MD); } 831 static bool isScope(const Metadata *MD) { return !MD || isa<DIScope>(MD); } 832 static bool isDINode(const Metadata *MD) { return !MD || isa<DINode>(MD); } 833 834 void Verifier::visitDILocation(const DILocation &N) { 835 AssertDI(N.getRawScope() && isa<DILocalScope>(N.getRawScope()), 836 "location requires a valid scope", &N, N.getRawScope()); 837 if (auto *IA = N.getRawInlinedAt()) 838 AssertDI(isa<DILocation>(IA), "inlined-at should be a location", &N, IA); 839 } 840 841 void Verifier::visitGenericDINode(const GenericDINode &N) { 842 AssertDI(N.getTag(), "invalid tag", &N); 843 } 844 845 void Verifier::visitDIScope(const DIScope &N) { 846 if (auto *F = N.getRawFile()) 847 AssertDI(isa<DIFile>(F), "invalid file", &N, F); 848 } 849 850 void Verifier::visitDISubrange(const DISubrange &N) { 851 AssertDI(N.getTag() == dwarf::DW_TAG_subrange_type, "invalid tag", &N); 852 AssertDI(N.getCount() >= -1, "invalid subrange count", &N); 853 } 854 855 void Verifier::visitDIEnumerator(const DIEnumerator &N) { 856 AssertDI(N.getTag() == dwarf::DW_TAG_enumerator, "invalid tag", &N); 857 } 858 859 void Verifier::visitDIBasicType(const DIBasicType &N) { 860 AssertDI(N.getTag() == dwarf::DW_TAG_base_type || 861 N.getTag() == dwarf::DW_TAG_unspecified_type, 862 "invalid tag", &N); 863 } 864 865 void Verifier::visitDIDerivedType(const DIDerivedType &N) { 866 // Common scope checks. 867 visitDIScope(N); 868 869 AssertDI(N.getTag() == dwarf::DW_TAG_typedef || 870 N.getTag() == dwarf::DW_TAG_pointer_type || 871 N.getTag() == dwarf::DW_TAG_ptr_to_member_type || 872 N.getTag() == dwarf::DW_TAG_reference_type || 873 N.getTag() == dwarf::DW_TAG_rvalue_reference_type || 874 N.getTag() == dwarf::DW_TAG_const_type || 875 N.getTag() == dwarf::DW_TAG_volatile_type || 876 N.getTag() == dwarf::DW_TAG_restrict_type || 877 N.getTag() == dwarf::DW_TAG_atomic_type || 878 N.getTag() == dwarf::DW_TAG_member || 879 N.getTag() == dwarf::DW_TAG_inheritance || 880 N.getTag() == dwarf::DW_TAG_friend, 881 "invalid tag", &N); 882 if (N.getTag() == dwarf::DW_TAG_ptr_to_member_type) { 883 AssertDI(isType(N.getRawExtraData()), "invalid pointer to member type", &N, 884 N.getRawExtraData()); 885 } 886 887 AssertDI(isScope(N.getRawScope()), "invalid scope", &N, N.getRawScope()); 888 AssertDI(isType(N.getRawBaseType()), "invalid base type", &N, 889 N.getRawBaseType()); 890 891 if (N.getDWARFAddressSpace()) { 892 AssertDI(N.getTag() == dwarf::DW_TAG_pointer_type || 893 N.getTag() == dwarf::DW_TAG_reference_type, 894 "DWARF address space only applies to pointer or reference types", 895 &N); 896 } 897 } 898 899 static bool hasConflictingReferenceFlags(unsigned Flags) { 900 return (Flags & DINode::FlagLValueReference) && 901 (Flags & DINode::FlagRValueReference); 902 } 903 904 void Verifier::visitTemplateParams(const MDNode &N, const Metadata &RawParams) { 905 auto *Params = dyn_cast<MDTuple>(&RawParams); 906 AssertDI(Params, "invalid template params", &N, &RawParams); 907 for (Metadata *Op : Params->operands()) { 908 AssertDI(Op && isa<DITemplateParameter>(Op), "invalid template parameter", 909 &N, Params, Op); 910 } 911 } 912 913 void Verifier::visitDICompositeType(const DICompositeType &N) { 914 // Common scope checks. 915 visitDIScope(N); 916 917 AssertDI(N.getTag() == dwarf::DW_TAG_array_type || 918 N.getTag() == dwarf::DW_TAG_structure_type || 919 N.getTag() == dwarf::DW_TAG_union_type || 920 N.getTag() == dwarf::DW_TAG_enumeration_type || 921 N.getTag() == dwarf::DW_TAG_class_type, 922 "invalid tag", &N); 923 924 AssertDI(isScope(N.getRawScope()), "invalid scope", &N, N.getRawScope()); 925 AssertDI(isType(N.getRawBaseType()), "invalid base type", &N, 926 N.getRawBaseType()); 927 928 AssertDI(!N.getRawElements() || isa<MDTuple>(N.getRawElements()), 929 "invalid composite elements", &N, N.getRawElements()); 930 AssertDI(isType(N.getRawVTableHolder()), "invalid vtable holder", &N, 931 N.getRawVTableHolder()); 932 AssertDI(!hasConflictingReferenceFlags(N.getFlags()), 933 "invalid reference flags", &N); 934 if (auto *Params = N.getRawTemplateParams()) 935 visitTemplateParams(N, *Params); 936 937 if (N.getTag() == dwarf::DW_TAG_class_type || 938 N.getTag() == dwarf::DW_TAG_union_type) { 939 AssertDI(N.getFile() && !N.getFile()->getFilename().empty(), 940 "class/union requires a filename", &N, N.getFile()); 941 } 942 } 943 944 void Verifier::visitDISubroutineType(const DISubroutineType &N) { 945 AssertDI(N.getTag() == dwarf::DW_TAG_subroutine_type, "invalid tag", &N); 946 if (auto *Types = N.getRawTypeArray()) { 947 AssertDI(isa<MDTuple>(Types), "invalid composite elements", &N, Types); 948 for (Metadata *Ty : N.getTypeArray()->operands()) { 949 AssertDI(isType(Ty), "invalid subroutine type ref", &N, Types, Ty); 950 } 951 } 952 AssertDI(!hasConflictingReferenceFlags(N.getFlags()), 953 "invalid reference flags", &N); 954 } 955 956 void Verifier::visitDIFile(const DIFile &N) { 957 AssertDI(N.getTag() == dwarf::DW_TAG_file_type, "invalid tag", &N); 958 AssertDI((N.getChecksumKind() != DIFile::CSK_None || 959 N.getChecksum().empty()), "invalid checksum kind", &N); 960 } 961 962 void Verifier::visitDICompileUnit(const DICompileUnit &N) { 963 AssertDI(N.isDistinct(), "compile units must be distinct", &N); 964 AssertDI(N.getTag() == dwarf::DW_TAG_compile_unit, "invalid tag", &N); 965 966 // Don't bother verifying the compilation directory or producer string 967 // as those could be empty. 968 AssertDI(N.getRawFile() && isa<DIFile>(N.getRawFile()), "invalid file", &N, 969 N.getRawFile()); 970 AssertDI(!N.getFile()->getFilename().empty(), "invalid filename", &N, 971 N.getFile()); 972 973 AssertDI((N.getEmissionKind() <= DICompileUnit::LastEmissionKind), 974 "invalid emission kind", &N); 975 976 if (auto *Array = N.getRawEnumTypes()) { 977 AssertDI(isa<MDTuple>(Array), "invalid enum list", &N, Array); 978 for (Metadata *Op : N.getEnumTypes()->operands()) { 979 auto *Enum = dyn_cast_or_null<DICompositeType>(Op); 980 AssertDI(Enum && Enum->getTag() == dwarf::DW_TAG_enumeration_type, 981 "invalid enum type", &N, N.getEnumTypes(), Op); 982 } 983 } 984 if (auto *Array = N.getRawRetainedTypes()) { 985 AssertDI(isa<MDTuple>(Array), "invalid retained type list", &N, Array); 986 for (Metadata *Op : N.getRetainedTypes()->operands()) { 987 AssertDI(Op && (isa<DIType>(Op) || 988 (isa<DISubprogram>(Op) && 989 !cast<DISubprogram>(Op)->isDefinition())), 990 "invalid retained type", &N, Op); 991 } 992 } 993 if (auto *Array = N.getRawGlobalVariables()) { 994 AssertDI(isa<MDTuple>(Array), "invalid global variable list", &N, Array); 995 for (Metadata *Op : N.getGlobalVariables()->operands()) { 996 AssertDI(Op && (isa<DIGlobalVariableExpression>(Op)), 997 "invalid global variable ref", &N, Op); 998 } 999 } 1000 if (auto *Array = N.getRawImportedEntities()) { 1001 AssertDI(isa<MDTuple>(Array), "invalid imported entity list", &N, Array); 1002 for (Metadata *Op : N.getImportedEntities()->operands()) { 1003 AssertDI(Op && isa<DIImportedEntity>(Op), "invalid imported entity ref", 1004 &N, Op); 1005 } 1006 } 1007 if (auto *Array = N.getRawMacros()) { 1008 AssertDI(isa<MDTuple>(Array), "invalid macro list", &N, Array); 1009 for (Metadata *Op : N.getMacros()->operands()) { 1010 AssertDI(Op && isa<DIMacroNode>(Op), "invalid macro ref", &N, Op); 1011 } 1012 } 1013 CUVisited.insert(&N); 1014 } 1015 1016 void Verifier::visitDISubprogram(const DISubprogram &N) { 1017 AssertDI(N.getTag() == dwarf::DW_TAG_subprogram, "invalid tag", &N); 1018 AssertDI(isScope(N.getRawScope()), "invalid scope", &N, N.getRawScope()); 1019 if (auto *F = N.getRawFile()) 1020 AssertDI(isa<DIFile>(F), "invalid file", &N, F); 1021 else 1022 AssertDI(N.getLine() == 0, "line specified with no file", &N, N.getLine()); 1023 if (auto *T = N.getRawType()) 1024 AssertDI(isa<DISubroutineType>(T), "invalid subroutine type", &N, T); 1025 AssertDI(isType(N.getRawContainingType()), "invalid containing type", &N, 1026 N.getRawContainingType()); 1027 if (auto *Params = N.getRawTemplateParams()) 1028 visitTemplateParams(N, *Params); 1029 if (auto *S = N.getRawDeclaration()) 1030 AssertDI(isa<DISubprogram>(S) && !cast<DISubprogram>(S)->isDefinition(), 1031 "invalid subprogram declaration", &N, S); 1032 if (auto *RawVars = N.getRawVariables()) { 1033 auto *Vars = dyn_cast<MDTuple>(RawVars); 1034 AssertDI(Vars, "invalid variable list", &N, RawVars); 1035 for (Metadata *Op : Vars->operands()) { 1036 AssertDI(Op && isa<DILocalVariable>(Op), "invalid local variable", &N, 1037 Vars, Op); 1038 } 1039 } 1040 AssertDI(!hasConflictingReferenceFlags(N.getFlags()), 1041 "invalid reference flags", &N); 1042 1043 auto *Unit = N.getRawUnit(); 1044 if (N.isDefinition()) { 1045 // Subprogram definitions (not part of the type hierarchy). 1046 AssertDI(N.isDistinct(), "subprogram definitions must be distinct", &N); 1047 AssertDI(Unit, "subprogram definitions must have a compile unit", &N); 1048 AssertDI(isa<DICompileUnit>(Unit), "invalid unit type", &N, Unit); 1049 } else { 1050 // Subprogram declarations (part of the type hierarchy). 1051 AssertDI(!Unit, "subprogram declarations must not have a compile unit", &N); 1052 } 1053 1054 if (auto *RawThrownTypes = N.getRawThrownTypes()) { 1055 auto *ThrownTypes = dyn_cast<MDTuple>(RawThrownTypes); 1056 AssertDI(ThrownTypes, "invalid thrown types list", &N, RawThrownTypes); 1057 for (Metadata *Op : ThrownTypes->operands()) 1058 AssertDI(Op && isa<DIType>(Op), "invalid thrown type", &N, ThrownTypes, 1059 Op); 1060 } 1061 } 1062 1063 void Verifier::visitDILexicalBlockBase(const DILexicalBlockBase &N) { 1064 AssertDI(N.getTag() == dwarf::DW_TAG_lexical_block, "invalid tag", &N); 1065 AssertDI(N.getRawScope() && isa<DILocalScope>(N.getRawScope()), 1066 "invalid local scope", &N, N.getRawScope()); 1067 } 1068 1069 void Verifier::visitDILexicalBlock(const DILexicalBlock &N) { 1070 visitDILexicalBlockBase(N); 1071 1072 AssertDI(N.getLine() || !N.getColumn(), 1073 "cannot have column info without line info", &N); 1074 } 1075 1076 void Verifier::visitDILexicalBlockFile(const DILexicalBlockFile &N) { 1077 visitDILexicalBlockBase(N); 1078 } 1079 1080 void Verifier::visitDINamespace(const DINamespace &N) { 1081 AssertDI(N.getTag() == dwarf::DW_TAG_namespace, "invalid tag", &N); 1082 if (auto *S = N.getRawScope()) 1083 AssertDI(isa<DIScope>(S), "invalid scope ref", &N, S); 1084 } 1085 1086 void Verifier::visitDIMacro(const DIMacro &N) { 1087 AssertDI(N.getMacinfoType() == dwarf::DW_MACINFO_define || 1088 N.getMacinfoType() == dwarf::DW_MACINFO_undef, 1089 "invalid macinfo type", &N); 1090 AssertDI(!N.getName().empty(), "anonymous macro", &N); 1091 if (!N.getValue().empty()) { 1092 assert(N.getValue().data()[0] != ' ' && "Macro value has a space prefix"); 1093 } 1094 } 1095 1096 void Verifier::visitDIMacroFile(const DIMacroFile &N) { 1097 AssertDI(N.getMacinfoType() == dwarf::DW_MACINFO_start_file, 1098 "invalid macinfo type", &N); 1099 if (auto *F = N.getRawFile()) 1100 AssertDI(isa<DIFile>(F), "invalid file", &N, F); 1101 1102 if (auto *Array = N.getRawElements()) { 1103 AssertDI(isa<MDTuple>(Array), "invalid macro list", &N, Array); 1104 for (Metadata *Op : N.getElements()->operands()) { 1105 AssertDI(Op && isa<DIMacroNode>(Op), "invalid macro ref", &N, Op); 1106 } 1107 } 1108 } 1109 1110 void Verifier::visitDIModule(const DIModule &N) { 1111 AssertDI(N.getTag() == dwarf::DW_TAG_module, "invalid tag", &N); 1112 AssertDI(!N.getName().empty(), "anonymous module", &N); 1113 } 1114 1115 void Verifier::visitDITemplateParameter(const DITemplateParameter &N) { 1116 AssertDI(isType(N.getRawType()), "invalid type ref", &N, N.getRawType()); 1117 } 1118 1119 void Verifier::visitDITemplateTypeParameter(const DITemplateTypeParameter &N) { 1120 visitDITemplateParameter(N); 1121 1122 AssertDI(N.getTag() == dwarf::DW_TAG_template_type_parameter, "invalid tag", 1123 &N); 1124 } 1125 1126 void Verifier::visitDITemplateValueParameter( 1127 const DITemplateValueParameter &N) { 1128 visitDITemplateParameter(N); 1129 1130 AssertDI(N.getTag() == dwarf::DW_TAG_template_value_parameter || 1131 N.getTag() == dwarf::DW_TAG_GNU_template_template_param || 1132 N.getTag() == dwarf::DW_TAG_GNU_template_parameter_pack, 1133 "invalid tag", &N); 1134 } 1135 1136 void Verifier::visitDIVariable(const DIVariable &N) { 1137 if (auto *S = N.getRawScope()) 1138 AssertDI(isa<DIScope>(S), "invalid scope", &N, S); 1139 AssertDI(isType(N.getRawType()), "invalid type ref", &N, N.getRawType()); 1140 if (auto *F = N.getRawFile()) 1141 AssertDI(isa<DIFile>(F), "invalid file", &N, F); 1142 } 1143 1144 void Verifier::visitDIGlobalVariable(const DIGlobalVariable &N) { 1145 // Checks common to all variables. 1146 visitDIVariable(N); 1147 1148 AssertDI(N.getTag() == dwarf::DW_TAG_variable, "invalid tag", &N); 1149 AssertDI(!N.getName().empty(), "missing global variable name", &N); 1150 if (auto *Member = N.getRawStaticDataMemberDeclaration()) { 1151 AssertDI(isa<DIDerivedType>(Member), 1152 "invalid static data member declaration", &N, Member); 1153 } 1154 } 1155 1156 void Verifier::visitDILocalVariable(const DILocalVariable &N) { 1157 // Checks common to all variables. 1158 visitDIVariable(N); 1159 1160 AssertDI(N.getTag() == dwarf::DW_TAG_variable, "invalid tag", &N); 1161 AssertDI(N.getRawScope() && isa<DILocalScope>(N.getRawScope()), 1162 "local variable requires a valid scope", &N, N.getRawScope()); 1163 } 1164 1165 void Verifier::visitDIExpression(const DIExpression &N) { 1166 AssertDI(N.isValid(), "invalid expression", &N); 1167 } 1168 1169 void Verifier::visitDIGlobalVariableExpression( 1170 const DIGlobalVariableExpression &GVE) { 1171 AssertDI(GVE.getVariable(), "missing variable"); 1172 if (auto *Var = GVE.getVariable()) 1173 visitDIGlobalVariable(*Var); 1174 if (auto *Expr = GVE.getExpression()) 1175 visitDIExpression(*Expr); 1176 } 1177 1178 void Verifier::visitDIObjCProperty(const DIObjCProperty &N) { 1179 AssertDI(N.getTag() == dwarf::DW_TAG_APPLE_property, "invalid tag", &N); 1180 if (auto *T = N.getRawType()) 1181 AssertDI(isType(T), "invalid type ref", &N, T); 1182 if (auto *F = N.getRawFile()) 1183 AssertDI(isa<DIFile>(F), "invalid file", &N, F); 1184 } 1185 1186 void Verifier::visitDIImportedEntity(const DIImportedEntity &N) { 1187 AssertDI(N.getTag() == dwarf::DW_TAG_imported_module || 1188 N.getTag() == dwarf::DW_TAG_imported_declaration, 1189 "invalid tag", &N); 1190 if (auto *S = N.getRawScope()) 1191 AssertDI(isa<DIScope>(S), "invalid scope for imported entity", &N, S); 1192 AssertDI(isDINode(N.getRawEntity()), "invalid imported entity", &N, 1193 N.getRawEntity()); 1194 } 1195 1196 void Verifier::visitComdat(const Comdat &C) { 1197 // The Module is invalid if the GlobalValue has private linkage. Entities 1198 // with private linkage don't have entries in the symbol table. 1199 if (const GlobalValue *GV = M.getNamedValue(C.getName())) 1200 Assert(!GV->hasPrivateLinkage(), "comdat global value has private linkage", 1201 GV); 1202 } 1203 1204 void Verifier::visitModuleIdents(const Module &M) { 1205 const NamedMDNode *Idents = M.getNamedMetadata("llvm.ident"); 1206 if (!Idents) 1207 return; 1208 1209 // llvm.ident takes a list of metadata entry. Each entry has only one string. 1210 // Scan each llvm.ident entry and make sure that this requirement is met. 1211 for (const MDNode *N : Idents->operands()) { 1212 Assert(N->getNumOperands() == 1, 1213 "incorrect number of operands in llvm.ident metadata", N); 1214 Assert(dyn_cast_or_null<MDString>(N->getOperand(0)), 1215 ("invalid value for llvm.ident metadata entry operand" 1216 "(the operand should be a string)"), 1217 N->getOperand(0)); 1218 } 1219 } 1220 1221 void Verifier::visitModuleFlags(const Module &M) { 1222 const NamedMDNode *Flags = M.getModuleFlagsMetadata(); 1223 if (!Flags) return; 1224 1225 // Scan each flag, and track the flags and requirements. 1226 DenseMap<const MDString*, const MDNode*> SeenIDs; 1227 SmallVector<const MDNode*, 16> Requirements; 1228 for (const MDNode *MDN : Flags->operands()) 1229 visitModuleFlag(MDN, SeenIDs, Requirements); 1230 1231 // Validate that the requirements in the module are valid. 1232 for (const MDNode *Requirement : Requirements) { 1233 const MDString *Flag = cast<MDString>(Requirement->getOperand(0)); 1234 const Metadata *ReqValue = Requirement->getOperand(1); 1235 1236 const MDNode *Op = SeenIDs.lookup(Flag); 1237 if (!Op) { 1238 CheckFailed("invalid requirement on flag, flag is not present in module", 1239 Flag); 1240 continue; 1241 } 1242 1243 if (Op->getOperand(2) != ReqValue) { 1244 CheckFailed(("invalid requirement on flag, " 1245 "flag does not have the required value"), 1246 Flag); 1247 continue; 1248 } 1249 } 1250 } 1251 1252 void 1253 Verifier::visitModuleFlag(const MDNode *Op, 1254 DenseMap<const MDString *, const MDNode *> &SeenIDs, 1255 SmallVectorImpl<const MDNode *> &Requirements) { 1256 // Each module flag should have three arguments, the merge behavior (a 1257 // constant int), the flag ID (an MDString), and the value. 1258 Assert(Op->getNumOperands() == 3, 1259 "incorrect number of operands in module flag", Op); 1260 Module::ModFlagBehavior MFB; 1261 if (!Module::isValidModFlagBehavior(Op->getOperand(0), MFB)) { 1262 Assert( 1263 mdconst::dyn_extract_or_null<ConstantInt>(Op->getOperand(0)), 1264 "invalid behavior operand in module flag (expected constant integer)", 1265 Op->getOperand(0)); 1266 Assert(false, 1267 "invalid behavior operand in module flag (unexpected constant)", 1268 Op->getOperand(0)); 1269 } 1270 MDString *ID = dyn_cast_or_null<MDString>(Op->getOperand(1)); 1271 Assert(ID, "invalid ID operand in module flag (expected metadata string)", 1272 Op->getOperand(1)); 1273 1274 // Sanity check the values for behaviors with additional requirements. 1275 switch (MFB) { 1276 case Module::Error: 1277 case Module::Warning: 1278 case Module::Override: 1279 // These behavior types accept any value. 1280 break; 1281 1282 case Module::Require: { 1283 // The value should itself be an MDNode with two operands, a flag ID (an 1284 // MDString), and a value. 1285 MDNode *Value = dyn_cast<MDNode>(Op->getOperand(2)); 1286 Assert(Value && Value->getNumOperands() == 2, 1287 "invalid value for 'require' module flag (expected metadata pair)", 1288 Op->getOperand(2)); 1289 Assert(isa<MDString>(Value->getOperand(0)), 1290 ("invalid value for 'require' module flag " 1291 "(first value operand should be a string)"), 1292 Value->getOperand(0)); 1293 1294 // Append it to the list of requirements, to check once all module flags are 1295 // scanned. 1296 Requirements.push_back(Value); 1297 break; 1298 } 1299 1300 case Module::Append: 1301 case Module::AppendUnique: { 1302 // These behavior types require the operand be an MDNode. 1303 Assert(isa<MDNode>(Op->getOperand(2)), 1304 "invalid value for 'append'-type module flag " 1305 "(expected a metadata node)", 1306 Op->getOperand(2)); 1307 break; 1308 } 1309 } 1310 1311 // Unless this is a "requires" flag, check the ID is unique. 1312 if (MFB != Module::Require) { 1313 bool Inserted = SeenIDs.insert(std::make_pair(ID, Op)).second; 1314 Assert(Inserted, 1315 "module flag identifiers must be unique (or of 'require' type)", ID); 1316 } 1317 } 1318 1319 /// Return true if this attribute kind only applies to functions. 1320 static bool isFuncOnlyAttr(Attribute::AttrKind Kind) { 1321 switch (Kind) { 1322 case Attribute::NoReturn: 1323 case Attribute::NoUnwind: 1324 case Attribute::NoInline: 1325 case Attribute::AlwaysInline: 1326 case Attribute::OptimizeForSize: 1327 case Attribute::StackProtect: 1328 case Attribute::StackProtectReq: 1329 case Attribute::StackProtectStrong: 1330 case Attribute::SafeStack: 1331 case Attribute::NoRedZone: 1332 case Attribute::NoImplicitFloat: 1333 case Attribute::Naked: 1334 case Attribute::InlineHint: 1335 case Attribute::StackAlignment: 1336 case Attribute::UWTable: 1337 case Attribute::NonLazyBind: 1338 case Attribute::ReturnsTwice: 1339 case Attribute::SanitizeAddress: 1340 case Attribute::SanitizeThread: 1341 case Attribute::SanitizeMemory: 1342 case Attribute::MinSize: 1343 case Attribute::NoDuplicate: 1344 case Attribute::Builtin: 1345 case Attribute::NoBuiltin: 1346 case Attribute::Cold: 1347 case Attribute::OptimizeNone: 1348 case Attribute::JumpTable: 1349 case Attribute::Convergent: 1350 case Attribute::ArgMemOnly: 1351 case Attribute::NoRecurse: 1352 case Attribute::InaccessibleMemOnly: 1353 case Attribute::InaccessibleMemOrArgMemOnly: 1354 case Attribute::AllocSize: 1355 case Attribute::Speculatable: 1356 return true; 1357 default: 1358 break; 1359 } 1360 return false; 1361 } 1362 1363 /// Return true if this is a function attribute that can also appear on 1364 /// arguments. 1365 static bool isFuncOrArgAttr(Attribute::AttrKind Kind) { 1366 return Kind == Attribute::ReadOnly || Kind == Attribute::WriteOnly || 1367 Kind == Attribute::ReadNone; 1368 } 1369 1370 void Verifier::verifyAttributeTypes(AttributeSet Attrs, bool IsFunction, 1371 const Value *V) { 1372 for (Attribute A : Attrs) { 1373 if (A.isStringAttribute()) 1374 continue; 1375 1376 if (isFuncOnlyAttr(A.getKindAsEnum())) { 1377 if (!IsFunction) { 1378 CheckFailed("Attribute '" + A.getAsString() + 1379 "' only applies to functions!", 1380 V); 1381 return; 1382 } 1383 } else if (IsFunction && !isFuncOrArgAttr(A.getKindAsEnum())) { 1384 CheckFailed("Attribute '" + A.getAsString() + 1385 "' does not apply to functions!", 1386 V); 1387 return; 1388 } 1389 } 1390 } 1391 1392 // VerifyParameterAttrs - Check the given attributes for an argument or return 1393 // value of the specified type. The value V is printed in error messages. 1394 void Verifier::verifyParameterAttrs(AttributeSet Attrs, Type *Ty, 1395 const Value *V) { 1396 if (!Attrs.hasAttributes()) 1397 return; 1398 1399 verifyAttributeTypes(Attrs, /*IsFunction=*/false, V); 1400 1401 // Check for mutually incompatible attributes. Only inreg is compatible with 1402 // sret. 1403 unsigned AttrCount = 0; 1404 AttrCount += Attrs.hasAttribute(Attribute::ByVal); 1405 AttrCount += Attrs.hasAttribute(Attribute::InAlloca); 1406 AttrCount += Attrs.hasAttribute(Attribute::StructRet) || 1407 Attrs.hasAttribute(Attribute::InReg); 1408 AttrCount += Attrs.hasAttribute(Attribute::Nest); 1409 Assert(AttrCount <= 1, "Attributes 'byval', 'inalloca', 'inreg', 'nest', " 1410 "and 'sret' are incompatible!", 1411 V); 1412 1413 Assert(!(Attrs.hasAttribute(Attribute::InAlloca) && 1414 Attrs.hasAttribute(Attribute::ReadOnly)), 1415 "Attributes " 1416 "'inalloca and readonly' are incompatible!", 1417 V); 1418 1419 Assert(!(Attrs.hasAttribute(Attribute::StructRet) && 1420 Attrs.hasAttribute(Attribute::Returned)), 1421 "Attributes " 1422 "'sret and returned' are incompatible!", 1423 V); 1424 1425 Assert(!(Attrs.hasAttribute(Attribute::ZExt) && 1426 Attrs.hasAttribute(Attribute::SExt)), 1427 "Attributes " 1428 "'zeroext and signext' are incompatible!", 1429 V); 1430 1431 Assert(!(Attrs.hasAttribute(Attribute::ReadNone) && 1432 Attrs.hasAttribute(Attribute::ReadOnly)), 1433 "Attributes " 1434 "'readnone and readonly' are incompatible!", 1435 V); 1436 1437 Assert(!(Attrs.hasAttribute(Attribute::ReadNone) && 1438 Attrs.hasAttribute(Attribute::WriteOnly)), 1439 "Attributes " 1440 "'readnone and writeonly' are incompatible!", 1441 V); 1442 1443 Assert(!(Attrs.hasAttribute(Attribute::ReadOnly) && 1444 Attrs.hasAttribute(Attribute::WriteOnly)), 1445 "Attributes " 1446 "'readonly and writeonly' are incompatible!", 1447 V); 1448 1449 Assert(!(Attrs.hasAttribute(Attribute::NoInline) && 1450 Attrs.hasAttribute(Attribute::AlwaysInline)), 1451 "Attributes " 1452 "'noinline and alwaysinline' are incompatible!", 1453 V); 1454 1455 AttrBuilder IncompatibleAttrs = AttributeFuncs::typeIncompatible(Ty); 1456 Assert(!AttrBuilder(Attrs).overlaps(IncompatibleAttrs), 1457 "Wrong types for attribute: " + 1458 AttributeSet::get(Context, IncompatibleAttrs).getAsString(), 1459 V); 1460 1461 if (PointerType *PTy = dyn_cast<PointerType>(Ty)) { 1462 SmallPtrSet<Type*, 4> Visited; 1463 if (!PTy->getElementType()->isSized(&Visited)) { 1464 Assert(!Attrs.hasAttribute(Attribute::ByVal) && 1465 !Attrs.hasAttribute(Attribute::InAlloca), 1466 "Attributes 'byval' and 'inalloca' do not support unsized types!", 1467 V); 1468 } 1469 if (!isa<PointerType>(PTy->getElementType())) 1470 Assert(!Attrs.hasAttribute(Attribute::SwiftError), 1471 "Attribute 'swifterror' only applies to parameters " 1472 "with pointer to pointer type!", 1473 V); 1474 } else { 1475 Assert(!Attrs.hasAttribute(Attribute::ByVal), 1476 "Attribute 'byval' only applies to parameters with pointer type!", 1477 V); 1478 Assert(!Attrs.hasAttribute(Attribute::SwiftError), 1479 "Attribute 'swifterror' only applies to parameters " 1480 "with pointer type!", 1481 V); 1482 } 1483 } 1484 1485 // Check parameter attributes against a function type. 1486 // The value V is printed in error messages. 1487 void Verifier::verifyFunctionAttrs(FunctionType *FT, AttributeList Attrs, 1488 const Value *V) { 1489 if (Attrs.isEmpty()) 1490 return; 1491 1492 bool SawNest = false; 1493 bool SawReturned = false; 1494 bool SawSRet = false; 1495 bool SawSwiftSelf = false; 1496 bool SawSwiftError = false; 1497 1498 // Verify return value attributes. 1499 AttributeSet RetAttrs = Attrs.getRetAttributes(); 1500 Assert((!RetAttrs.hasAttribute(Attribute::ByVal) && 1501 !RetAttrs.hasAttribute(Attribute::Nest) && 1502 !RetAttrs.hasAttribute(Attribute::StructRet) && 1503 !RetAttrs.hasAttribute(Attribute::NoCapture) && 1504 !RetAttrs.hasAttribute(Attribute::Returned) && 1505 !RetAttrs.hasAttribute(Attribute::InAlloca) && 1506 !RetAttrs.hasAttribute(Attribute::SwiftSelf) && 1507 !RetAttrs.hasAttribute(Attribute::SwiftError)), 1508 "Attributes 'byval', 'inalloca', 'nest', 'sret', 'nocapture', " 1509 "'returned', 'swiftself', and 'swifterror' do not apply to return " 1510 "values!", 1511 V); 1512 Assert((!RetAttrs.hasAttribute(Attribute::ReadOnly) && 1513 !RetAttrs.hasAttribute(Attribute::WriteOnly) && 1514 !RetAttrs.hasAttribute(Attribute::ReadNone)), 1515 "Attribute '" + RetAttrs.getAsString() + 1516 "' does not apply to function returns", 1517 V); 1518 verifyParameterAttrs(RetAttrs, FT->getReturnType(), V); 1519 1520 // Verify parameter attributes. 1521 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 1522 Type *Ty = FT->getParamType(i); 1523 AttributeSet ArgAttrs = Attrs.getParamAttributes(i); 1524 1525 verifyParameterAttrs(ArgAttrs, Ty, V); 1526 1527 if (ArgAttrs.hasAttribute(Attribute::Nest)) { 1528 Assert(!SawNest, "More than one parameter has attribute nest!", V); 1529 SawNest = true; 1530 } 1531 1532 if (ArgAttrs.hasAttribute(Attribute::Returned)) { 1533 Assert(!SawReturned, "More than one parameter has attribute returned!", 1534 V); 1535 Assert(Ty->canLosslesslyBitCastTo(FT->getReturnType()), 1536 "Incompatible argument and return types for 'returned' attribute", 1537 V); 1538 SawReturned = true; 1539 } 1540 1541 if (ArgAttrs.hasAttribute(Attribute::StructRet)) { 1542 Assert(!SawSRet, "Cannot have multiple 'sret' parameters!", V); 1543 Assert(i == 0 || i == 1, 1544 "Attribute 'sret' is not on first or second parameter!", V); 1545 SawSRet = true; 1546 } 1547 1548 if (ArgAttrs.hasAttribute(Attribute::SwiftSelf)) { 1549 Assert(!SawSwiftSelf, "Cannot have multiple 'swiftself' parameters!", V); 1550 SawSwiftSelf = true; 1551 } 1552 1553 if (ArgAttrs.hasAttribute(Attribute::SwiftError)) { 1554 Assert(!SawSwiftError, "Cannot have multiple 'swifterror' parameters!", 1555 V); 1556 SawSwiftError = true; 1557 } 1558 1559 if (ArgAttrs.hasAttribute(Attribute::InAlloca)) { 1560 Assert(i == FT->getNumParams() - 1, 1561 "inalloca isn't on the last parameter!", V); 1562 } 1563 } 1564 1565 if (!Attrs.hasAttributes(AttributeList::FunctionIndex)) 1566 return; 1567 1568 verifyAttributeTypes(Attrs.getFnAttributes(), /*IsFunction=*/true, V); 1569 1570 Assert(!(Attrs.hasFnAttribute(Attribute::ReadNone) && 1571 Attrs.hasFnAttribute(Attribute::ReadOnly)), 1572 "Attributes 'readnone and readonly' are incompatible!", V); 1573 1574 Assert(!(Attrs.hasFnAttribute(Attribute::ReadNone) && 1575 Attrs.hasFnAttribute(Attribute::WriteOnly)), 1576 "Attributes 'readnone and writeonly' are incompatible!", V); 1577 1578 Assert(!(Attrs.hasFnAttribute(Attribute::ReadOnly) && 1579 Attrs.hasFnAttribute(Attribute::WriteOnly)), 1580 "Attributes 'readonly and writeonly' are incompatible!", V); 1581 1582 Assert(!(Attrs.hasFnAttribute(Attribute::ReadNone) && 1583 Attrs.hasFnAttribute(Attribute::InaccessibleMemOrArgMemOnly)), 1584 "Attributes 'readnone and inaccessiblemem_or_argmemonly' are " 1585 "incompatible!", 1586 V); 1587 1588 Assert(!(Attrs.hasFnAttribute(Attribute::ReadNone) && 1589 Attrs.hasFnAttribute(Attribute::InaccessibleMemOnly)), 1590 "Attributes 'readnone and inaccessiblememonly' are incompatible!", V); 1591 1592 Assert(!(Attrs.hasFnAttribute(Attribute::NoInline) && 1593 Attrs.hasFnAttribute(Attribute::AlwaysInline)), 1594 "Attributes 'noinline and alwaysinline' are incompatible!", V); 1595 1596 if (Attrs.hasFnAttribute(Attribute::OptimizeNone)) { 1597 Assert(Attrs.hasFnAttribute(Attribute::NoInline), 1598 "Attribute 'optnone' requires 'noinline'!", V); 1599 1600 Assert(!Attrs.hasFnAttribute(Attribute::OptimizeForSize), 1601 "Attributes 'optsize and optnone' are incompatible!", V); 1602 1603 Assert(!Attrs.hasFnAttribute(Attribute::MinSize), 1604 "Attributes 'minsize and optnone' are incompatible!", V); 1605 } 1606 1607 if (Attrs.hasFnAttribute(Attribute::JumpTable)) { 1608 const GlobalValue *GV = cast<GlobalValue>(V); 1609 Assert(GV->hasGlobalUnnamedAddr(), 1610 "Attribute 'jumptable' requires 'unnamed_addr'", V); 1611 } 1612 1613 if (Attrs.hasFnAttribute(Attribute::AllocSize)) { 1614 std::pair<unsigned, Optional<unsigned>> Args = 1615 Attrs.getAllocSizeArgs(AttributeList::FunctionIndex); 1616 1617 auto CheckParam = [&](StringRef Name, unsigned ParamNo) { 1618 if (ParamNo >= FT->getNumParams()) { 1619 CheckFailed("'allocsize' " + Name + " argument is out of bounds", V); 1620 return false; 1621 } 1622 1623 if (!FT->getParamType(ParamNo)->isIntegerTy()) { 1624 CheckFailed("'allocsize' " + Name + 1625 " argument must refer to an integer parameter", 1626 V); 1627 return false; 1628 } 1629 1630 return true; 1631 }; 1632 1633 if (!CheckParam("element size", Args.first)) 1634 return; 1635 1636 if (Args.second && !CheckParam("number of elements", *Args.second)) 1637 return; 1638 } 1639 } 1640 1641 void Verifier::verifyFunctionMetadata( 1642 ArrayRef<std::pair<unsigned, MDNode *>> MDs) { 1643 for (const auto &Pair : MDs) { 1644 if (Pair.first == LLVMContext::MD_prof) { 1645 MDNode *MD = Pair.second; 1646 Assert(MD->getNumOperands() >= 2, 1647 "!prof annotations should have no less than 2 operands", MD); 1648 1649 // Check first operand. 1650 Assert(MD->getOperand(0) != nullptr, "first operand should not be null", 1651 MD); 1652 Assert(isa<MDString>(MD->getOperand(0)), 1653 "expected string with name of the !prof annotation", MD); 1654 MDString *MDS = cast<MDString>(MD->getOperand(0)); 1655 StringRef ProfName = MDS->getString(); 1656 Assert(ProfName.equals("function_entry_count"), 1657 "first operand should be 'function_entry_count'", MD); 1658 1659 // Check second operand. 1660 Assert(MD->getOperand(1) != nullptr, "second operand should not be null", 1661 MD); 1662 Assert(isa<ConstantAsMetadata>(MD->getOperand(1)), 1663 "expected integer argument to function_entry_count", MD); 1664 } 1665 } 1666 } 1667 1668 void Verifier::visitConstantExprsRecursively(const Constant *EntryC) { 1669 if (!ConstantExprVisited.insert(EntryC).second) 1670 return; 1671 1672 SmallVector<const Constant *, 16> Stack; 1673 Stack.push_back(EntryC); 1674 1675 while (!Stack.empty()) { 1676 const Constant *C = Stack.pop_back_val(); 1677 1678 // Check this constant expression. 1679 if (const auto *CE = dyn_cast<ConstantExpr>(C)) 1680 visitConstantExpr(CE); 1681 1682 if (const auto *GV = dyn_cast<GlobalValue>(C)) { 1683 // Global Values get visited separately, but we do need to make sure 1684 // that the global value is in the correct module 1685 Assert(GV->getParent() == &M, "Referencing global in another module!", 1686 EntryC, &M, GV, GV->getParent()); 1687 continue; 1688 } 1689 1690 // Visit all sub-expressions. 1691 for (const Use &U : C->operands()) { 1692 const auto *OpC = dyn_cast<Constant>(U); 1693 if (!OpC) 1694 continue; 1695 if (!ConstantExprVisited.insert(OpC).second) 1696 continue; 1697 Stack.push_back(OpC); 1698 } 1699 } 1700 } 1701 1702 void Verifier::visitConstantExpr(const ConstantExpr *CE) { 1703 if (CE->getOpcode() == Instruction::BitCast) 1704 Assert(CastInst::castIsValid(Instruction::BitCast, CE->getOperand(0), 1705 CE->getType()), 1706 "Invalid bitcast", CE); 1707 1708 if (CE->getOpcode() == Instruction::IntToPtr || 1709 CE->getOpcode() == Instruction::PtrToInt) { 1710 auto *PtrTy = CE->getOpcode() == Instruction::IntToPtr 1711 ? CE->getType() 1712 : CE->getOperand(0)->getType(); 1713 StringRef Msg = CE->getOpcode() == Instruction::IntToPtr 1714 ? "inttoptr not supported for non-integral pointers" 1715 : "ptrtoint not supported for non-integral pointers"; 1716 Assert( 1717 !DL.isNonIntegralPointerType(cast<PointerType>(PtrTy->getScalarType())), 1718 Msg); 1719 } 1720 } 1721 1722 bool Verifier::verifyAttributeCount(AttributeList Attrs, unsigned Params) { 1723 if (Attrs.getNumSlots() == 0) 1724 return true; 1725 1726 unsigned LastSlot = Attrs.getNumSlots() - 1; 1727 unsigned LastIndex = Attrs.getSlotIndex(LastSlot); 1728 if (LastIndex <= Params || 1729 (LastIndex == AttributeList::FunctionIndex && 1730 (LastSlot == 0 || Attrs.getSlotIndex(LastSlot - 1) <= Params))) 1731 return true; 1732 1733 return false; 1734 } 1735 1736 /// Verify that statepoint intrinsic is well formed. 1737 void Verifier::verifyStatepoint(ImmutableCallSite CS) { 1738 assert(CS.getCalledFunction() && 1739 CS.getCalledFunction()->getIntrinsicID() == 1740 Intrinsic::experimental_gc_statepoint); 1741 1742 const Instruction &CI = *CS.getInstruction(); 1743 1744 Assert(!CS.doesNotAccessMemory() && !CS.onlyReadsMemory() && 1745 !CS.onlyAccessesArgMemory(), 1746 "gc.statepoint must read and write all memory to preserve " 1747 "reordering restrictions required by safepoint semantics", 1748 &CI); 1749 1750 const Value *IDV = CS.getArgument(0); 1751 Assert(isa<ConstantInt>(IDV), "gc.statepoint ID must be a constant integer", 1752 &CI); 1753 1754 const Value *NumPatchBytesV = CS.getArgument(1); 1755 Assert(isa<ConstantInt>(NumPatchBytesV), 1756 "gc.statepoint number of patchable bytes must be a constant integer", 1757 &CI); 1758 const int64_t NumPatchBytes = 1759 cast<ConstantInt>(NumPatchBytesV)->getSExtValue(); 1760 assert(isInt<32>(NumPatchBytes) && "NumPatchBytesV is an i32!"); 1761 Assert(NumPatchBytes >= 0, "gc.statepoint number of patchable bytes must be " 1762 "positive", 1763 &CI); 1764 1765 const Value *Target = CS.getArgument(2); 1766 auto *PT = dyn_cast<PointerType>(Target->getType()); 1767 Assert(PT && PT->getElementType()->isFunctionTy(), 1768 "gc.statepoint callee must be of function pointer type", &CI, Target); 1769 FunctionType *TargetFuncType = cast<FunctionType>(PT->getElementType()); 1770 1771 const Value *NumCallArgsV = CS.getArgument(3); 1772 Assert(isa<ConstantInt>(NumCallArgsV), 1773 "gc.statepoint number of arguments to underlying call " 1774 "must be constant integer", 1775 &CI); 1776 const int NumCallArgs = cast<ConstantInt>(NumCallArgsV)->getZExtValue(); 1777 Assert(NumCallArgs >= 0, 1778 "gc.statepoint number of arguments to underlying call " 1779 "must be positive", 1780 &CI); 1781 const int NumParams = (int)TargetFuncType->getNumParams(); 1782 if (TargetFuncType->isVarArg()) { 1783 Assert(NumCallArgs >= NumParams, 1784 "gc.statepoint mismatch in number of vararg call args", &CI); 1785 1786 // TODO: Remove this limitation 1787 Assert(TargetFuncType->getReturnType()->isVoidTy(), 1788 "gc.statepoint doesn't support wrapping non-void " 1789 "vararg functions yet", 1790 &CI); 1791 } else 1792 Assert(NumCallArgs == NumParams, 1793 "gc.statepoint mismatch in number of call args", &CI); 1794 1795 const Value *FlagsV = CS.getArgument(4); 1796 Assert(isa<ConstantInt>(FlagsV), 1797 "gc.statepoint flags must be constant integer", &CI); 1798 const uint64_t Flags = cast<ConstantInt>(FlagsV)->getZExtValue(); 1799 Assert((Flags & ~(uint64_t)StatepointFlags::MaskAll) == 0, 1800 "unknown flag used in gc.statepoint flags argument", &CI); 1801 1802 // Verify that the types of the call parameter arguments match 1803 // the type of the wrapped callee. 1804 for (int i = 0; i < NumParams; i++) { 1805 Type *ParamType = TargetFuncType->getParamType(i); 1806 Type *ArgType = CS.getArgument(5 + i)->getType(); 1807 Assert(ArgType == ParamType, 1808 "gc.statepoint call argument does not match wrapped " 1809 "function type", 1810 &CI); 1811 } 1812 1813 const int EndCallArgsInx = 4 + NumCallArgs; 1814 1815 const Value *NumTransitionArgsV = CS.getArgument(EndCallArgsInx+1); 1816 Assert(isa<ConstantInt>(NumTransitionArgsV), 1817 "gc.statepoint number of transition arguments " 1818 "must be constant integer", 1819 &CI); 1820 const int NumTransitionArgs = 1821 cast<ConstantInt>(NumTransitionArgsV)->getZExtValue(); 1822 Assert(NumTransitionArgs >= 0, 1823 "gc.statepoint number of transition arguments must be positive", &CI); 1824 const int EndTransitionArgsInx = EndCallArgsInx + 1 + NumTransitionArgs; 1825 1826 const Value *NumDeoptArgsV = CS.getArgument(EndTransitionArgsInx+1); 1827 Assert(isa<ConstantInt>(NumDeoptArgsV), 1828 "gc.statepoint number of deoptimization arguments " 1829 "must be constant integer", 1830 &CI); 1831 const int NumDeoptArgs = cast<ConstantInt>(NumDeoptArgsV)->getZExtValue(); 1832 Assert(NumDeoptArgs >= 0, "gc.statepoint number of deoptimization arguments " 1833 "must be positive", 1834 &CI); 1835 1836 const int ExpectedNumArgs = 1837 7 + NumCallArgs + NumTransitionArgs + NumDeoptArgs; 1838 Assert(ExpectedNumArgs <= (int)CS.arg_size(), 1839 "gc.statepoint too few arguments according to length fields", &CI); 1840 1841 // Check that the only uses of this gc.statepoint are gc.result or 1842 // gc.relocate calls which are tied to this statepoint and thus part 1843 // of the same statepoint sequence 1844 for (const User *U : CI.users()) { 1845 const CallInst *Call = dyn_cast<const CallInst>(U); 1846 Assert(Call, "illegal use of statepoint token", &CI, U); 1847 if (!Call) continue; 1848 Assert(isa<GCRelocateInst>(Call) || isa<GCResultInst>(Call), 1849 "gc.result or gc.relocate are the only value uses " 1850 "of a gc.statepoint", 1851 &CI, U); 1852 if (isa<GCResultInst>(Call)) { 1853 Assert(Call->getArgOperand(0) == &CI, 1854 "gc.result connected to wrong gc.statepoint", &CI, Call); 1855 } else if (isa<GCRelocateInst>(Call)) { 1856 Assert(Call->getArgOperand(0) == &CI, 1857 "gc.relocate connected to wrong gc.statepoint", &CI, Call); 1858 } 1859 } 1860 1861 // Note: It is legal for a single derived pointer to be listed multiple 1862 // times. It's non-optimal, but it is legal. It can also happen after 1863 // insertion if we strip a bitcast away. 1864 // Note: It is really tempting to check that each base is relocated and 1865 // that a derived pointer is never reused as a base pointer. This turns 1866 // out to be problematic since optimizations run after safepoint insertion 1867 // can recognize equality properties that the insertion logic doesn't know 1868 // about. See example statepoint.ll in the verifier subdirectory 1869 } 1870 1871 void Verifier::verifyFrameRecoverIndices() { 1872 for (auto &Counts : FrameEscapeInfo) { 1873 Function *F = Counts.first; 1874 unsigned EscapedObjectCount = Counts.second.first; 1875 unsigned MaxRecoveredIndex = Counts.second.second; 1876 Assert(MaxRecoveredIndex <= EscapedObjectCount, 1877 "all indices passed to llvm.localrecover must be less than the " 1878 "number of arguments passed ot llvm.localescape in the parent " 1879 "function", 1880 F); 1881 } 1882 } 1883 1884 static Instruction *getSuccPad(TerminatorInst *Terminator) { 1885 BasicBlock *UnwindDest; 1886 if (auto *II = dyn_cast<InvokeInst>(Terminator)) 1887 UnwindDest = II->getUnwindDest(); 1888 else if (auto *CSI = dyn_cast<CatchSwitchInst>(Terminator)) 1889 UnwindDest = CSI->getUnwindDest(); 1890 else 1891 UnwindDest = cast<CleanupReturnInst>(Terminator)->getUnwindDest(); 1892 return UnwindDest->getFirstNonPHI(); 1893 } 1894 1895 void Verifier::verifySiblingFuncletUnwinds() { 1896 SmallPtrSet<Instruction *, 8> Visited; 1897 SmallPtrSet<Instruction *, 8> Active; 1898 for (const auto &Pair : SiblingFuncletInfo) { 1899 Instruction *PredPad = Pair.first; 1900 if (Visited.count(PredPad)) 1901 continue; 1902 Active.insert(PredPad); 1903 TerminatorInst *Terminator = Pair.second; 1904 do { 1905 Instruction *SuccPad = getSuccPad(Terminator); 1906 if (Active.count(SuccPad)) { 1907 // Found a cycle; report error 1908 Instruction *CyclePad = SuccPad; 1909 SmallVector<Instruction *, 8> CycleNodes; 1910 do { 1911 CycleNodes.push_back(CyclePad); 1912 TerminatorInst *CycleTerminator = SiblingFuncletInfo[CyclePad]; 1913 if (CycleTerminator != CyclePad) 1914 CycleNodes.push_back(CycleTerminator); 1915 CyclePad = getSuccPad(CycleTerminator); 1916 } while (CyclePad != SuccPad); 1917 Assert(false, "EH pads can't handle each other's exceptions", 1918 ArrayRef<Instruction *>(CycleNodes)); 1919 } 1920 // Don't re-walk a node we've already checked 1921 if (!Visited.insert(SuccPad).second) 1922 break; 1923 // Walk to this successor if it has a map entry. 1924 PredPad = SuccPad; 1925 auto TermI = SiblingFuncletInfo.find(PredPad); 1926 if (TermI == SiblingFuncletInfo.end()) 1927 break; 1928 Terminator = TermI->second; 1929 Active.insert(PredPad); 1930 } while (true); 1931 // Each node only has one successor, so we've walked all the active 1932 // nodes' successors. 1933 Active.clear(); 1934 } 1935 } 1936 1937 // visitFunction - Verify that a function is ok. 1938 // 1939 void Verifier::visitFunction(const Function &F) { 1940 visitGlobalValue(F); 1941 1942 // Check function arguments. 1943 FunctionType *FT = F.getFunctionType(); 1944 unsigned NumArgs = F.arg_size(); 1945 1946 Assert(&Context == &F.getContext(), 1947 "Function context does not match Module context!", &F); 1948 1949 Assert(!F.hasCommonLinkage(), "Functions may not have common linkage", &F); 1950 Assert(FT->getNumParams() == NumArgs, 1951 "# formal arguments must match # of arguments for function type!", &F, 1952 FT); 1953 Assert(F.getReturnType()->isFirstClassType() || 1954 F.getReturnType()->isVoidTy() || F.getReturnType()->isStructTy(), 1955 "Functions cannot return aggregate values!", &F); 1956 1957 Assert(!F.hasStructRetAttr() || F.getReturnType()->isVoidTy(), 1958 "Invalid struct return type!", &F); 1959 1960 AttributeList Attrs = F.getAttributes(); 1961 1962 Assert(verifyAttributeCount(Attrs, FT->getNumParams()), 1963 "Attribute after last parameter!", &F); 1964 1965 // Check function attributes. 1966 verifyFunctionAttrs(FT, Attrs, &F); 1967 1968 // On function declarations/definitions, we do not support the builtin 1969 // attribute. We do not check this in VerifyFunctionAttrs since that is 1970 // checking for Attributes that can/can not ever be on functions. 1971 Assert(!Attrs.hasFnAttribute(Attribute::Builtin), 1972 "Attribute 'builtin' can only be applied to a callsite.", &F); 1973 1974 // Check that this function meets the restrictions on this calling convention. 1975 // Sometimes varargs is used for perfectly forwarding thunks, so some of these 1976 // restrictions can be lifted. 1977 switch (F.getCallingConv()) { 1978 default: 1979 case CallingConv::C: 1980 break; 1981 case CallingConv::AMDGPU_KERNEL: 1982 case CallingConv::SPIR_KERNEL: 1983 Assert(F.getReturnType()->isVoidTy(), 1984 "Calling convention requires void return type", &F); 1985 LLVM_FALLTHROUGH; 1986 case CallingConv::AMDGPU_VS: 1987 case CallingConv::AMDGPU_HS: 1988 case CallingConv::AMDGPU_GS: 1989 case CallingConv::AMDGPU_PS: 1990 case CallingConv::AMDGPU_CS: 1991 Assert(!F.hasStructRetAttr(), 1992 "Calling convention does not allow sret", &F); 1993 LLVM_FALLTHROUGH; 1994 case CallingConv::Fast: 1995 case CallingConv::Cold: 1996 case CallingConv::Intel_OCL_BI: 1997 case CallingConv::PTX_Kernel: 1998 case CallingConv::PTX_Device: 1999 Assert(!F.isVarArg(), "Calling convention does not support varargs or " 2000 "perfect forwarding!", 2001 &F); 2002 break; 2003 } 2004 2005 bool isLLVMdotName = F.getName().size() >= 5 && 2006 F.getName().substr(0, 5) == "llvm."; 2007 2008 // Check that the argument values match the function type for this function... 2009 unsigned i = 0; 2010 for (const Argument &Arg : F.args()) { 2011 Assert(Arg.getType() == FT->getParamType(i), 2012 "Argument value does not match function argument type!", &Arg, 2013 FT->getParamType(i)); 2014 Assert(Arg.getType()->isFirstClassType(), 2015 "Function arguments must have first-class types!", &Arg); 2016 if (!isLLVMdotName) { 2017 Assert(!Arg.getType()->isMetadataTy(), 2018 "Function takes metadata but isn't an intrinsic", &Arg, &F); 2019 Assert(!Arg.getType()->isTokenTy(), 2020 "Function takes token but isn't an intrinsic", &Arg, &F); 2021 } 2022 2023 // Check that swifterror argument is only used by loads and stores. 2024 if (Attrs.hasParamAttribute(i, Attribute::SwiftError)) { 2025 verifySwiftErrorValue(&Arg); 2026 } 2027 ++i; 2028 } 2029 2030 if (!isLLVMdotName) 2031 Assert(!F.getReturnType()->isTokenTy(), 2032 "Functions returns a token but isn't an intrinsic", &F); 2033 2034 // Get the function metadata attachments. 2035 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs; 2036 F.getAllMetadata(MDs); 2037 assert(F.hasMetadata() != MDs.empty() && "Bit out-of-sync"); 2038 verifyFunctionMetadata(MDs); 2039 2040 // Check validity of the personality function 2041 if (F.hasPersonalityFn()) { 2042 auto *Per = dyn_cast<Function>(F.getPersonalityFn()->stripPointerCasts()); 2043 if (Per) 2044 Assert(Per->getParent() == F.getParent(), 2045 "Referencing personality function in another module!", 2046 &F, F.getParent(), Per, Per->getParent()); 2047 } 2048 2049 if (F.isMaterializable()) { 2050 // Function has a body somewhere we can't see. 2051 Assert(MDs.empty(), "unmaterialized function cannot have metadata", &F, 2052 MDs.empty() ? nullptr : MDs.front().second); 2053 } else if (F.isDeclaration()) { 2054 for (const auto &I : MDs) { 2055 AssertDI(I.first != LLVMContext::MD_dbg, 2056 "function declaration may not have a !dbg attachment", &F); 2057 Assert(I.first != LLVMContext::MD_prof, 2058 "function declaration may not have a !prof attachment", &F); 2059 2060 // Verify the metadata itself. 2061 visitMDNode(*I.second); 2062 } 2063 Assert(!F.hasPersonalityFn(), 2064 "Function declaration shouldn't have a personality routine", &F); 2065 } else { 2066 // Verify that this function (which has a body) is not named "llvm.*". It 2067 // is not legal to define intrinsics. 2068 Assert(!isLLVMdotName, "llvm intrinsics cannot be defined!", &F); 2069 2070 // Check the entry node 2071 const BasicBlock *Entry = &F.getEntryBlock(); 2072 Assert(pred_empty(Entry), 2073 "Entry block to function must not have predecessors!", Entry); 2074 2075 // The address of the entry block cannot be taken, unless it is dead. 2076 if (Entry->hasAddressTaken()) { 2077 Assert(!BlockAddress::lookup(Entry)->isConstantUsed(), 2078 "blockaddress may not be used with the entry block!", Entry); 2079 } 2080 2081 unsigned NumDebugAttachments = 0, NumProfAttachments = 0; 2082 // Visit metadata attachments. 2083 for (const auto &I : MDs) { 2084 // Verify that the attachment is legal. 2085 switch (I.first) { 2086 default: 2087 break; 2088 case LLVMContext::MD_dbg: 2089 ++NumDebugAttachments; 2090 AssertDI(NumDebugAttachments == 1, 2091 "function must have a single !dbg attachment", &F, I.second); 2092 AssertDI(isa<DISubprogram>(I.second), 2093 "function !dbg attachment must be a subprogram", &F, I.second); 2094 break; 2095 case LLVMContext::MD_prof: 2096 ++NumProfAttachments; 2097 Assert(NumProfAttachments == 1, 2098 "function must have a single !prof attachment", &F, I.second); 2099 break; 2100 } 2101 2102 // Verify the metadata itself. 2103 visitMDNode(*I.second); 2104 } 2105 } 2106 2107 // If this function is actually an intrinsic, verify that it is only used in 2108 // direct call/invokes, never having its "address taken". 2109 // Only do this if the module is materialized, otherwise we don't have all the 2110 // uses. 2111 if (F.getIntrinsicID() && F.getParent()->isMaterialized()) { 2112 const User *U; 2113 if (F.hasAddressTaken(&U)) 2114 Assert(false, "Invalid user of intrinsic instruction!", U); 2115 } 2116 2117 Assert(!F.hasDLLImportStorageClass() || 2118 (F.isDeclaration() && F.hasExternalLinkage()) || 2119 F.hasAvailableExternallyLinkage(), 2120 "Function is marked as dllimport, but not external.", &F); 2121 2122 auto *N = F.getSubprogram(); 2123 HasDebugInfo = (N != nullptr); 2124 if (!HasDebugInfo) 2125 return; 2126 2127 // Check that all !dbg attachments lead to back to N (or, at least, another 2128 // subprogram that describes the same function). 2129 // 2130 // FIXME: Check this incrementally while visiting !dbg attachments. 2131 // FIXME: Only check when N is the canonical subprogram for F. 2132 SmallPtrSet<const MDNode *, 32> Seen; 2133 for (auto &BB : F) 2134 for (auto &I : BB) { 2135 // Be careful about using DILocation here since we might be dealing with 2136 // broken code (this is the Verifier after all). 2137 DILocation *DL = 2138 dyn_cast_or_null<DILocation>(I.getDebugLoc().getAsMDNode()); 2139 if (!DL) 2140 continue; 2141 if (!Seen.insert(DL).second) 2142 continue; 2143 2144 DILocalScope *Scope = DL->getInlinedAtScope(); 2145 if (Scope && !Seen.insert(Scope).second) 2146 continue; 2147 2148 DISubprogram *SP = Scope ? Scope->getSubprogram() : nullptr; 2149 2150 // Scope and SP could be the same MDNode and we don't want to skip 2151 // validation in that case 2152 if (SP && ((Scope != SP) && !Seen.insert(SP).second)) 2153 continue; 2154 2155 // FIXME: Once N is canonical, check "SP == &N". 2156 AssertDI(SP->describes(&F), 2157 "!dbg attachment points at wrong subprogram for function", N, &F, 2158 &I, DL, Scope, SP); 2159 } 2160 } 2161 2162 // verifyBasicBlock - Verify that a basic block is well formed... 2163 // 2164 void Verifier::visitBasicBlock(BasicBlock &BB) { 2165 InstsInThisBlock.clear(); 2166 2167 // Ensure that basic blocks have terminators! 2168 Assert(BB.getTerminator(), "Basic Block does not have terminator!", &BB); 2169 2170 // Check constraints that this basic block imposes on all of the PHI nodes in 2171 // it. 2172 if (isa<PHINode>(BB.front())) { 2173 SmallVector<BasicBlock*, 8> Preds(pred_begin(&BB), pred_end(&BB)); 2174 SmallVector<std::pair<BasicBlock*, Value*>, 8> Values; 2175 std::sort(Preds.begin(), Preds.end()); 2176 PHINode *PN; 2177 for (BasicBlock::iterator I = BB.begin(); (PN = dyn_cast<PHINode>(I));++I) { 2178 // Ensure that PHI nodes have at least one entry! 2179 Assert(PN->getNumIncomingValues() != 0, 2180 "PHI nodes must have at least one entry. If the block is dead, " 2181 "the PHI should be removed!", 2182 PN); 2183 Assert(PN->getNumIncomingValues() == Preds.size(), 2184 "PHINode should have one entry for each predecessor of its " 2185 "parent basic block!", 2186 PN); 2187 2188 // Get and sort all incoming values in the PHI node... 2189 Values.clear(); 2190 Values.reserve(PN->getNumIncomingValues()); 2191 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 2192 Values.push_back(std::make_pair(PN->getIncomingBlock(i), 2193 PN->getIncomingValue(i))); 2194 std::sort(Values.begin(), Values.end()); 2195 2196 for (unsigned i = 0, e = Values.size(); i != e; ++i) { 2197 // Check to make sure that if there is more than one entry for a 2198 // particular basic block in this PHI node, that the incoming values are 2199 // all identical. 2200 // 2201 Assert(i == 0 || Values[i].first != Values[i - 1].first || 2202 Values[i].second == Values[i - 1].second, 2203 "PHI node has multiple entries for the same basic block with " 2204 "different incoming values!", 2205 PN, Values[i].first, Values[i].second, Values[i - 1].second); 2206 2207 // Check to make sure that the predecessors and PHI node entries are 2208 // matched up. 2209 Assert(Values[i].first == Preds[i], 2210 "PHI node entries do not match predecessors!", PN, 2211 Values[i].first, Preds[i]); 2212 } 2213 } 2214 } 2215 2216 // Check that all instructions have their parent pointers set up correctly. 2217 for (auto &I : BB) 2218 { 2219 Assert(I.getParent() == &BB, "Instruction has bogus parent pointer!"); 2220 } 2221 } 2222 2223 void Verifier::visitTerminatorInst(TerminatorInst &I) { 2224 // Ensure that terminators only exist at the end of the basic block. 2225 Assert(&I == I.getParent()->getTerminator(), 2226 "Terminator found in the middle of a basic block!", I.getParent()); 2227 visitInstruction(I); 2228 } 2229 2230 void Verifier::visitBranchInst(BranchInst &BI) { 2231 if (BI.isConditional()) { 2232 Assert(BI.getCondition()->getType()->isIntegerTy(1), 2233 "Branch condition is not 'i1' type!", &BI, BI.getCondition()); 2234 } 2235 visitTerminatorInst(BI); 2236 } 2237 2238 void Verifier::visitReturnInst(ReturnInst &RI) { 2239 Function *F = RI.getParent()->getParent(); 2240 unsigned N = RI.getNumOperands(); 2241 if (F->getReturnType()->isVoidTy()) 2242 Assert(N == 0, 2243 "Found return instr that returns non-void in Function of void " 2244 "return type!", 2245 &RI, F->getReturnType()); 2246 else 2247 Assert(N == 1 && F->getReturnType() == RI.getOperand(0)->getType(), 2248 "Function return type does not match operand " 2249 "type of return inst!", 2250 &RI, F->getReturnType()); 2251 2252 // Check to make sure that the return value has necessary properties for 2253 // terminators... 2254 visitTerminatorInst(RI); 2255 } 2256 2257 void Verifier::visitSwitchInst(SwitchInst &SI) { 2258 // Check to make sure that all of the constants in the switch instruction 2259 // have the same type as the switched-on value. 2260 Type *SwitchTy = SI.getCondition()->getType(); 2261 SmallPtrSet<ConstantInt*, 32> Constants; 2262 for (auto &Case : SI.cases()) { 2263 Assert(Case.getCaseValue()->getType() == SwitchTy, 2264 "Switch constants must all be same type as switch value!", &SI); 2265 Assert(Constants.insert(Case.getCaseValue()).second, 2266 "Duplicate integer as switch case", &SI, Case.getCaseValue()); 2267 } 2268 2269 visitTerminatorInst(SI); 2270 } 2271 2272 void Verifier::visitIndirectBrInst(IndirectBrInst &BI) { 2273 Assert(BI.getAddress()->getType()->isPointerTy(), 2274 "Indirectbr operand must have pointer type!", &BI); 2275 for (unsigned i = 0, e = BI.getNumDestinations(); i != e; ++i) 2276 Assert(BI.getDestination(i)->getType()->isLabelTy(), 2277 "Indirectbr destinations must all have pointer type!", &BI); 2278 2279 visitTerminatorInst(BI); 2280 } 2281 2282 void Verifier::visitSelectInst(SelectInst &SI) { 2283 Assert(!SelectInst::areInvalidOperands(SI.getOperand(0), SI.getOperand(1), 2284 SI.getOperand(2)), 2285 "Invalid operands for select instruction!", &SI); 2286 2287 Assert(SI.getTrueValue()->getType() == SI.getType(), 2288 "Select values must have same type as select instruction!", &SI); 2289 visitInstruction(SI); 2290 } 2291 2292 /// visitUserOp1 - User defined operators shouldn't live beyond the lifetime of 2293 /// a pass, if any exist, it's an error. 2294 /// 2295 void Verifier::visitUserOp1(Instruction &I) { 2296 Assert(false, "User-defined operators should not live outside of a pass!", &I); 2297 } 2298 2299 void Verifier::visitTruncInst(TruncInst &I) { 2300 // Get the source and destination types 2301 Type *SrcTy = I.getOperand(0)->getType(); 2302 Type *DestTy = I.getType(); 2303 2304 // Get the size of the types in bits, we'll need this later 2305 unsigned SrcBitSize = SrcTy->getScalarSizeInBits(); 2306 unsigned DestBitSize = DestTy->getScalarSizeInBits(); 2307 2308 Assert(SrcTy->isIntOrIntVectorTy(), "Trunc only operates on integer", &I); 2309 Assert(DestTy->isIntOrIntVectorTy(), "Trunc only produces integer", &I); 2310 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(), 2311 "trunc source and destination must both be a vector or neither", &I); 2312 Assert(SrcBitSize > DestBitSize, "DestTy too big for Trunc", &I); 2313 2314 visitInstruction(I); 2315 } 2316 2317 void Verifier::visitZExtInst(ZExtInst &I) { 2318 // Get the source and destination types 2319 Type *SrcTy = I.getOperand(0)->getType(); 2320 Type *DestTy = I.getType(); 2321 2322 // Get the size of the types in bits, we'll need this later 2323 Assert(SrcTy->isIntOrIntVectorTy(), "ZExt only operates on integer", &I); 2324 Assert(DestTy->isIntOrIntVectorTy(), "ZExt only produces an integer", &I); 2325 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(), 2326 "zext source and destination must both be a vector or neither", &I); 2327 unsigned SrcBitSize = SrcTy->getScalarSizeInBits(); 2328 unsigned DestBitSize = DestTy->getScalarSizeInBits(); 2329 2330 Assert(SrcBitSize < DestBitSize, "Type too small for ZExt", &I); 2331 2332 visitInstruction(I); 2333 } 2334 2335 void Verifier::visitSExtInst(SExtInst &I) { 2336 // Get the source and destination types 2337 Type *SrcTy = I.getOperand(0)->getType(); 2338 Type *DestTy = I.getType(); 2339 2340 // Get the size of the types in bits, we'll need this later 2341 unsigned SrcBitSize = SrcTy->getScalarSizeInBits(); 2342 unsigned DestBitSize = DestTy->getScalarSizeInBits(); 2343 2344 Assert(SrcTy->isIntOrIntVectorTy(), "SExt only operates on integer", &I); 2345 Assert(DestTy->isIntOrIntVectorTy(), "SExt only produces an integer", &I); 2346 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(), 2347 "sext source and destination must both be a vector or neither", &I); 2348 Assert(SrcBitSize < DestBitSize, "Type too small for SExt", &I); 2349 2350 visitInstruction(I); 2351 } 2352 2353 void Verifier::visitFPTruncInst(FPTruncInst &I) { 2354 // Get the source and destination types 2355 Type *SrcTy = I.getOperand(0)->getType(); 2356 Type *DestTy = I.getType(); 2357 // Get the size of the types in bits, we'll need this later 2358 unsigned SrcBitSize = SrcTy->getScalarSizeInBits(); 2359 unsigned DestBitSize = DestTy->getScalarSizeInBits(); 2360 2361 Assert(SrcTy->isFPOrFPVectorTy(), "FPTrunc only operates on FP", &I); 2362 Assert(DestTy->isFPOrFPVectorTy(), "FPTrunc only produces an FP", &I); 2363 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(), 2364 "fptrunc source and destination must both be a vector or neither", &I); 2365 Assert(SrcBitSize > DestBitSize, "DestTy too big for FPTrunc", &I); 2366 2367 visitInstruction(I); 2368 } 2369 2370 void Verifier::visitFPExtInst(FPExtInst &I) { 2371 // Get the source and destination types 2372 Type *SrcTy = I.getOperand(0)->getType(); 2373 Type *DestTy = I.getType(); 2374 2375 // Get the size of the types in bits, we'll need this later 2376 unsigned SrcBitSize = SrcTy->getScalarSizeInBits(); 2377 unsigned DestBitSize = DestTy->getScalarSizeInBits(); 2378 2379 Assert(SrcTy->isFPOrFPVectorTy(), "FPExt only operates on FP", &I); 2380 Assert(DestTy->isFPOrFPVectorTy(), "FPExt only produces an FP", &I); 2381 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(), 2382 "fpext source and destination must both be a vector or neither", &I); 2383 Assert(SrcBitSize < DestBitSize, "DestTy too small for FPExt", &I); 2384 2385 visitInstruction(I); 2386 } 2387 2388 void Verifier::visitUIToFPInst(UIToFPInst &I) { 2389 // Get the source and destination types 2390 Type *SrcTy = I.getOperand(0)->getType(); 2391 Type *DestTy = I.getType(); 2392 2393 bool SrcVec = SrcTy->isVectorTy(); 2394 bool DstVec = DestTy->isVectorTy(); 2395 2396 Assert(SrcVec == DstVec, 2397 "UIToFP source and dest must both be vector or scalar", &I); 2398 Assert(SrcTy->isIntOrIntVectorTy(), 2399 "UIToFP source must be integer or integer vector", &I); 2400 Assert(DestTy->isFPOrFPVectorTy(), "UIToFP result must be FP or FP vector", 2401 &I); 2402 2403 if (SrcVec && DstVec) 2404 Assert(cast<VectorType>(SrcTy)->getNumElements() == 2405 cast<VectorType>(DestTy)->getNumElements(), 2406 "UIToFP source and dest vector length mismatch", &I); 2407 2408 visitInstruction(I); 2409 } 2410 2411 void Verifier::visitSIToFPInst(SIToFPInst &I) { 2412 // Get the source and destination types 2413 Type *SrcTy = I.getOperand(0)->getType(); 2414 Type *DestTy = I.getType(); 2415 2416 bool SrcVec = SrcTy->isVectorTy(); 2417 bool DstVec = DestTy->isVectorTy(); 2418 2419 Assert(SrcVec == DstVec, 2420 "SIToFP source and dest must both be vector or scalar", &I); 2421 Assert(SrcTy->isIntOrIntVectorTy(), 2422 "SIToFP source must be integer or integer vector", &I); 2423 Assert(DestTy->isFPOrFPVectorTy(), "SIToFP result must be FP or FP vector", 2424 &I); 2425 2426 if (SrcVec && DstVec) 2427 Assert(cast<VectorType>(SrcTy)->getNumElements() == 2428 cast<VectorType>(DestTy)->getNumElements(), 2429 "SIToFP source and dest vector length mismatch", &I); 2430 2431 visitInstruction(I); 2432 } 2433 2434 void Verifier::visitFPToUIInst(FPToUIInst &I) { 2435 // Get the source and destination types 2436 Type *SrcTy = I.getOperand(0)->getType(); 2437 Type *DestTy = I.getType(); 2438 2439 bool SrcVec = SrcTy->isVectorTy(); 2440 bool DstVec = DestTy->isVectorTy(); 2441 2442 Assert(SrcVec == DstVec, 2443 "FPToUI source and dest must both be vector or scalar", &I); 2444 Assert(SrcTy->isFPOrFPVectorTy(), "FPToUI source must be FP or FP vector", 2445 &I); 2446 Assert(DestTy->isIntOrIntVectorTy(), 2447 "FPToUI result must be integer or integer vector", &I); 2448 2449 if (SrcVec && DstVec) 2450 Assert(cast<VectorType>(SrcTy)->getNumElements() == 2451 cast<VectorType>(DestTy)->getNumElements(), 2452 "FPToUI source and dest vector length mismatch", &I); 2453 2454 visitInstruction(I); 2455 } 2456 2457 void Verifier::visitFPToSIInst(FPToSIInst &I) { 2458 // Get the source and destination types 2459 Type *SrcTy = I.getOperand(0)->getType(); 2460 Type *DestTy = I.getType(); 2461 2462 bool SrcVec = SrcTy->isVectorTy(); 2463 bool DstVec = DestTy->isVectorTy(); 2464 2465 Assert(SrcVec == DstVec, 2466 "FPToSI source and dest must both be vector or scalar", &I); 2467 Assert(SrcTy->isFPOrFPVectorTy(), "FPToSI source must be FP or FP vector", 2468 &I); 2469 Assert(DestTy->isIntOrIntVectorTy(), 2470 "FPToSI result must be integer or integer vector", &I); 2471 2472 if (SrcVec && DstVec) 2473 Assert(cast<VectorType>(SrcTy)->getNumElements() == 2474 cast<VectorType>(DestTy)->getNumElements(), 2475 "FPToSI source and dest vector length mismatch", &I); 2476 2477 visitInstruction(I); 2478 } 2479 2480 void Verifier::visitPtrToIntInst(PtrToIntInst &I) { 2481 // Get the source and destination types 2482 Type *SrcTy = I.getOperand(0)->getType(); 2483 Type *DestTy = I.getType(); 2484 2485 Assert(SrcTy->getScalarType()->isPointerTy(), 2486 "PtrToInt source must be pointer", &I); 2487 2488 if (auto *PTy = dyn_cast<PointerType>(SrcTy->getScalarType())) 2489 Assert(!DL.isNonIntegralPointerType(PTy), 2490 "ptrtoint not supported for non-integral pointers"); 2491 2492 Assert(DestTy->getScalarType()->isIntegerTy(), 2493 "PtrToInt result must be integral", &I); 2494 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(), "PtrToInt type mismatch", 2495 &I); 2496 2497 if (SrcTy->isVectorTy()) { 2498 VectorType *VSrc = dyn_cast<VectorType>(SrcTy); 2499 VectorType *VDest = dyn_cast<VectorType>(DestTy); 2500 Assert(VSrc->getNumElements() == VDest->getNumElements(), 2501 "PtrToInt Vector width mismatch", &I); 2502 } 2503 2504 visitInstruction(I); 2505 } 2506 2507 void Verifier::visitIntToPtrInst(IntToPtrInst &I) { 2508 // Get the source and destination types 2509 Type *SrcTy = I.getOperand(0)->getType(); 2510 Type *DestTy = I.getType(); 2511 2512 Assert(SrcTy->getScalarType()->isIntegerTy(), 2513 "IntToPtr source must be an integral", &I); 2514 Assert(DestTy->getScalarType()->isPointerTy(), 2515 "IntToPtr result must be a pointer", &I); 2516 2517 if (auto *PTy = dyn_cast<PointerType>(DestTy->getScalarType())) 2518 Assert(!DL.isNonIntegralPointerType(PTy), 2519 "inttoptr not supported for non-integral pointers"); 2520 2521 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(), "IntToPtr type mismatch", 2522 &I); 2523 if (SrcTy->isVectorTy()) { 2524 VectorType *VSrc = dyn_cast<VectorType>(SrcTy); 2525 VectorType *VDest = dyn_cast<VectorType>(DestTy); 2526 Assert(VSrc->getNumElements() == VDest->getNumElements(), 2527 "IntToPtr Vector width mismatch", &I); 2528 } 2529 visitInstruction(I); 2530 } 2531 2532 void Verifier::visitBitCastInst(BitCastInst &I) { 2533 Assert( 2534 CastInst::castIsValid(Instruction::BitCast, I.getOperand(0), I.getType()), 2535 "Invalid bitcast", &I); 2536 visitInstruction(I); 2537 } 2538 2539 void Verifier::visitAddrSpaceCastInst(AddrSpaceCastInst &I) { 2540 Type *SrcTy = I.getOperand(0)->getType(); 2541 Type *DestTy = I.getType(); 2542 2543 Assert(SrcTy->isPtrOrPtrVectorTy(), "AddrSpaceCast source must be a pointer", 2544 &I); 2545 Assert(DestTy->isPtrOrPtrVectorTy(), "AddrSpaceCast result must be a pointer", 2546 &I); 2547 Assert(SrcTy->getPointerAddressSpace() != DestTy->getPointerAddressSpace(), 2548 "AddrSpaceCast must be between different address spaces", &I); 2549 if (SrcTy->isVectorTy()) 2550 Assert(SrcTy->getVectorNumElements() == DestTy->getVectorNumElements(), 2551 "AddrSpaceCast vector pointer number of elements mismatch", &I); 2552 visitInstruction(I); 2553 } 2554 2555 /// visitPHINode - Ensure that a PHI node is well formed. 2556 /// 2557 void Verifier::visitPHINode(PHINode &PN) { 2558 // Ensure that the PHI nodes are all grouped together at the top of the block. 2559 // This can be tested by checking whether the instruction before this is 2560 // either nonexistent (because this is begin()) or is a PHI node. If not, 2561 // then there is some other instruction before a PHI. 2562 Assert(&PN == &PN.getParent()->front() || 2563 isa<PHINode>(--BasicBlock::iterator(&PN)), 2564 "PHI nodes not grouped at top of basic block!", &PN, PN.getParent()); 2565 2566 // Check that a PHI doesn't yield a Token. 2567 Assert(!PN.getType()->isTokenTy(), "PHI nodes cannot have token type!"); 2568 2569 // Check that all of the values of the PHI node have the same type as the 2570 // result, and that the incoming blocks are really basic blocks. 2571 for (Value *IncValue : PN.incoming_values()) { 2572 Assert(PN.getType() == IncValue->getType(), 2573 "PHI node operands are not the same type as the result!", &PN); 2574 } 2575 2576 // All other PHI node constraints are checked in the visitBasicBlock method. 2577 2578 visitInstruction(PN); 2579 } 2580 2581 void Verifier::verifyCallSite(CallSite CS) { 2582 Instruction *I = CS.getInstruction(); 2583 2584 Assert(CS.getCalledValue()->getType()->isPointerTy(), 2585 "Called function must be a pointer!", I); 2586 PointerType *FPTy = cast<PointerType>(CS.getCalledValue()->getType()); 2587 2588 Assert(FPTy->getElementType()->isFunctionTy(), 2589 "Called function is not pointer to function type!", I); 2590 2591 Assert(FPTy->getElementType() == CS.getFunctionType(), 2592 "Called function is not the same type as the call!", I); 2593 2594 FunctionType *FTy = CS.getFunctionType(); 2595 2596 // Verify that the correct number of arguments are being passed 2597 if (FTy->isVarArg()) 2598 Assert(CS.arg_size() >= FTy->getNumParams(), 2599 "Called function requires more parameters than were provided!", I); 2600 else 2601 Assert(CS.arg_size() == FTy->getNumParams(), 2602 "Incorrect number of arguments passed to called function!", I); 2603 2604 // Verify that all arguments to the call match the function type. 2605 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) 2606 Assert(CS.getArgument(i)->getType() == FTy->getParamType(i), 2607 "Call parameter type does not match function signature!", 2608 CS.getArgument(i), FTy->getParamType(i), I); 2609 2610 AttributeList Attrs = CS.getAttributes(); 2611 2612 Assert(verifyAttributeCount(Attrs, CS.arg_size()), 2613 "Attribute after last parameter!", I); 2614 2615 if (Attrs.hasAttribute(AttributeList::FunctionIndex, Attribute::Speculatable)) { 2616 // Don't allow speculatable on call sites, unless the underlying function 2617 // declaration is also speculatable. 2618 Function *Callee 2619 = dyn_cast<Function>(CS.getCalledValue()->stripPointerCasts()); 2620 Assert(Callee && Callee->isSpeculatable(), 2621 "speculatable attribute may not apply to call sites", I); 2622 } 2623 2624 // Verify call attributes. 2625 verifyFunctionAttrs(FTy, Attrs, I); 2626 2627 // Conservatively check the inalloca argument. 2628 // We have a bug if we can find that there is an underlying alloca without 2629 // inalloca. 2630 if (CS.hasInAllocaArgument()) { 2631 Value *InAllocaArg = CS.getArgument(FTy->getNumParams() - 1); 2632 if (auto AI = dyn_cast<AllocaInst>(InAllocaArg->stripInBoundsOffsets())) 2633 Assert(AI->isUsedWithInAlloca(), 2634 "inalloca argument for call has mismatched alloca", AI, I); 2635 } 2636 2637 // For each argument of the callsite, if it has the swifterror argument, 2638 // make sure the underlying alloca/parameter it comes from has a swifterror as 2639 // well. 2640 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) 2641 if (CS.paramHasAttr(i, Attribute::SwiftError)) { 2642 Value *SwiftErrorArg = CS.getArgument(i); 2643 if (auto AI = dyn_cast<AllocaInst>(SwiftErrorArg->stripInBoundsOffsets())) { 2644 Assert(AI->isSwiftError(), 2645 "swifterror argument for call has mismatched alloca", AI, I); 2646 continue; 2647 } 2648 auto ArgI = dyn_cast<Argument>(SwiftErrorArg); 2649 Assert(ArgI, "swifterror argument should come from an alloca or parameter", SwiftErrorArg, I); 2650 Assert(ArgI->hasSwiftErrorAttr(), 2651 "swifterror argument for call has mismatched parameter", ArgI, I); 2652 } 2653 2654 if (FTy->isVarArg()) { 2655 // FIXME? is 'nest' even legal here? 2656 bool SawNest = false; 2657 bool SawReturned = false; 2658 2659 for (unsigned Idx = 0; Idx < FTy->getNumParams(); ++Idx) { 2660 if (Attrs.hasParamAttribute(Idx, Attribute::Nest)) 2661 SawNest = true; 2662 if (Attrs.hasParamAttribute(Idx, Attribute::Returned)) 2663 SawReturned = true; 2664 } 2665 2666 // Check attributes on the varargs part. 2667 for (unsigned Idx = FTy->getNumParams(); Idx < CS.arg_size(); ++Idx) { 2668 Type *Ty = CS.getArgument(Idx)->getType(); 2669 AttributeSet ArgAttrs = Attrs.getParamAttributes(Idx); 2670 verifyParameterAttrs(ArgAttrs, Ty, I); 2671 2672 if (ArgAttrs.hasAttribute(Attribute::Nest)) { 2673 Assert(!SawNest, "More than one parameter has attribute nest!", I); 2674 SawNest = true; 2675 } 2676 2677 if (ArgAttrs.hasAttribute(Attribute::Returned)) { 2678 Assert(!SawReturned, "More than one parameter has attribute returned!", 2679 I); 2680 Assert(Ty->canLosslesslyBitCastTo(FTy->getReturnType()), 2681 "Incompatible argument and return types for 'returned' " 2682 "attribute", 2683 I); 2684 SawReturned = true; 2685 } 2686 2687 Assert(!ArgAttrs.hasAttribute(Attribute::StructRet), 2688 "Attribute 'sret' cannot be used for vararg call arguments!", I); 2689 2690 if (ArgAttrs.hasAttribute(Attribute::InAlloca)) 2691 Assert(Idx == CS.arg_size() - 1, "inalloca isn't on the last argument!", 2692 I); 2693 } 2694 } 2695 2696 // Verify that there's no metadata unless it's a direct call to an intrinsic. 2697 if (CS.getCalledFunction() == nullptr || 2698 !CS.getCalledFunction()->getName().startswith("llvm.")) { 2699 for (Type *ParamTy : FTy->params()) { 2700 Assert(!ParamTy->isMetadataTy(), 2701 "Function has metadata parameter but isn't an intrinsic", I); 2702 Assert(!ParamTy->isTokenTy(), 2703 "Function has token parameter but isn't an intrinsic", I); 2704 } 2705 } 2706 2707 // Verify that indirect calls don't return tokens. 2708 if (CS.getCalledFunction() == nullptr) 2709 Assert(!FTy->getReturnType()->isTokenTy(), 2710 "Return type cannot be token for indirect call!"); 2711 2712 if (Function *F = CS.getCalledFunction()) 2713 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID()) 2714 visitIntrinsicCallSite(ID, CS); 2715 2716 // Verify that a callsite has at most one "deopt", at most one "funclet" and 2717 // at most one "gc-transition" operand bundle. 2718 bool FoundDeoptBundle = false, FoundFuncletBundle = false, 2719 FoundGCTransitionBundle = false; 2720 for (unsigned i = 0, e = CS.getNumOperandBundles(); i < e; ++i) { 2721 OperandBundleUse BU = CS.getOperandBundleAt(i); 2722 uint32_t Tag = BU.getTagID(); 2723 if (Tag == LLVMContext::OB_deopt) { 2724 Assert(!FoundDeoptBundle, "Multiple deopt operand bundles", I); 2725 FoundDeoptBundle = true; 2726 } else if (Tag == LLVMContext::OB_gc_transition) { 2727 Assert(!FoundGCTransitionBundle, "Multiple gc-transition operand bundles", 2728 I); 2729 FoundGCTransitionBundle = true; 2730 } else if (Tag == LLVMContext::OB_funclet) { 2731 Assert(!FoundFuncletBundle, "Multiple funclet operand bundles", I); 2732 FoundFuncletBundle = true; 2733 Assert(BU.Inputs.size() == 1, 2734 "Expected exactly one funclet bundle operand", I); 2735 Assert(isa<FuncletPadInst>(BU.Inputs.front()), 2736 "Funclet bundle operands should correspond to a FuncletPadInst", 2737 I); 2738 } 2739 } 2740 2741 // Verify that each inlinable callsite of a debug-info-bearing function in a 2742 // debug-info-bearing function has a debug location attached to it. Failure to 2743 // do so causes assertion failures when the inliner sets up inline scope info. 2744 if (I->getFunction()->getSubprogram() && CS.getCalledFunction() && 2745 CS.getCalledFunction()->getSubprogram()) 2746 AssertDI(I->getDebugLoc(), "inlinable function call in a function with " 2747 "debug info must have a !dbg location", 2748 I); 2749 2750 visitInstruction(*I); 2751 } 2752 2753 /// Two types are "congruent" if they are identical, or if they are both pointer 2754 /// types with different pointee types and the same address space. 2755 static bool isTypeCongruent(Type *L, Type *R) { 2756 if (L == R) 2757 return true; 2758 PointerType *PL = dyn_cast<PointerType>(L); 2759 PointerType *PR = dyn_cast<PointerType>(R); 2760 if (!PL || !PR) 2761 return false; 2762 return PL->getAddressSpace() == PR->getAddressSpace(); 2763 } 2764 2765 static AttrBuilder getParameterABIAttributes(int I, AttributeList Attrs) { 2766 static const Attribute::AttrKind ABIAttrs[] = { 2767 Attribute::StructRet, Attribute::ByVal, Attribute::InAlloca, 2768 Attribute::InReg, Attribute::Returned, Attribute::SwiftSelf, 2769 Attribute::SwiftError}; 2770 AttrBuilder Copy; 2771 for (auto AK : ABIAttrs) { 2772 if (Attrs.hasParamAttribute(I, AK)) 2773 Copy.addAttribute(AK); 2774 } 2775 if (Attrs.hasParamAttribute(I, Attribute::Alignment)) 2776 Copy.addAlignmentAttr(Attrs.getParamAlignment(I)); 2777 return Copy; 2778 } 2779 2780 void Verifier::verifyMustTailCall(CallInst &CI) { 2781 Assert(!CI.isInlineAsm(), "cannot use musttail call with inline asm", &CI); 2782 2783 // - The caller and callee prototypes must match. Pointer types of 2784 // parameters or return types may differ in pointee type, but not 2785 // address space. 2786 Function *F = CI.getParent()->getParent(); 2787 FunctionType *CallerTy = F->getFunctionType(); 2788 FunctionType *CalleeTy = CI.getFunctionType(); 2789 Assert(CallerTy->getNumParams() == CalleeTy->getNumParams(), 2790 "cannot guarantee tail call due to mismatched parameter counts", &CI); 2791 Assert(CallerTy->isVarArg() == CalleeTy->isVarArg(), 2792 "cannot guarantee tail call due to mismatched varargs", &CI); 2793 Assert(isTypeCongruent(CallerTy->getReturnType(), CalleeTy->getReturnType()), 2794 "cannot guarantee tail call due to mismatched return types", &CI); 2795 for (int I = 0, E = CallerTy->getNumParams(); I != E; ++I) { 2796 Assert( 2797 isTypeCongruent(CallerTy->getParamType(I), CalleeTy->getParamType(I)), 2798 "cannot guarantee tail call due to mismatched parameter types", &CI); 2799 } 2800 2801 // - The calling conventions of the caller and callee must match. 2802 Assert(F->getCallingConv() == CI.getCallingConv(), 2803 "cannot guarantee tail call due to mismatched calling conv", &CI); 2804 2805 // - All ABI-impacting function attributes, such as sret, byval, inreg, 2806 // returned, and inalloca, must match. 2807 AttributeList CallerAttrs = F->getAttributes(); 2808 AttributeList CalleeAttrs = CI.getAttributes(); 2809 for (int I = 0, E = CallerTy->getNumParams(); I != E; ++I) { 2810 AttrBuilder CallerABIAttrs = getParameterABIAttributes(I, CallerAttrs); 2811 AttrBuilder CalleeABIAttrs = getParameterABIAttributes(I, CalleeAttrs); 2812 Assert(CallerABIAttrs == CalleeABIAttrs, 2813 "cannot guarantee tail call due to mismatched ABI impacting " 2814 "function attributes", 2815 &CI, CI.getOperand(I)); 2816 } 2817 2818 // - The call must immediately precede a :ref:`ret <i_ret>` instruction, 2819 // or a pointer bitcast followed by a ret instruction. 2820 // - The ret instruction must return the (possibly bitcasted) value 2821 // produced by the call or void. 2822 Value *RetVal = &CI; 2823 Instruction *Next = CI.getNextNode(); 2824 2825 // Handle the optional bitcast. 2826 if (BitCastInst *BI = dyn_cast_or_null<BitCastInst>(Next)) { 2827 Assert(BI->getOperand(0) == RetVal, 2828 "bitcast following musttail call must use the call", BI); 2829 RetVal = BI; 2830 Next = BI->getNextNode(); 2831 } 2832 2833 // Check the return. 2834 ReturnInst *Ret = dyn_cast_or_null<ReturnInst>(Next); 2835 Assert(Ret, "musttail call must be precede a ret with an optional bitcast", 2836 &CI); 2837 Assert(!Ret->getReturnValue() || Ret->getReturnValue() == RetVal, 2838 "musttail call result must be returned", Ret); 2839 } 2840 2841 void Verifier::visitCallInst(CallInst &CI) { 2842 verifyCallSite(&CI); 2843 2844 if (CI.isMustTailCall()) 2845 verifyMustTailCall(CI); 2846 } 2847 2848 void Verifier::visitInvokeInst(InvokeInst &II) { 2849 verifyCallSite(&II); 2850 2851 // Verify that the first non-PHI instruction of the unwind destination is an 2852 // exception handling instruction. 2853 Assert( 2854 II.getUnwindDest()->isEHPad(), 2855 "The unwind destination does not have an exception handling instruction!", 2856 &II); 2857 2858 visitTerminatorInst(II); 2859 } 2860 2861 /// visitBinaryOperator - Check that both arguments to the binary operator are 2862 /// of the same type! 2863 /// 2864 void Verifier::visitBinaryOperator(BinaryOperator &B) { 2865 Assert(B.getOperand(0)->getType() == B.getOperand(1)->getType(), 2866 "Both operands to a binary operator are not of the same type!", &B); 2867 2868 switch (B.getOpcode()) { 2869 // Check that integer arithmetic operators are only used with 2870 // integral operands. 2871 case Instruction::Add: 2872 case Instruction::Sub: 2873 case Instruction::Mul: 2874 case Instruction::SDiv: 2875 case Instruction::UDiv: 2876 case Instruction::SRem: 2877 case Instruction::URem: 2878 Assert(B.getType()->isIntOrIntVectorTy(), 2879 "Integer arithmetic operators only work with integral types!", &B); 2880 Assert(B.getType() == B.getOperand(0)->getType(), 2881 "Integer arithmetic operators must have same type " 2882 "for operands and result!", 2883 &B); 2884 break; 2885 // Check that floating-point arithmetic operators are only used with 2886 // floating-point operands. 2887 case Instruction::FAdd: 2888 case Instruction::FSub: 2889 case Instruction::FMul: 2890 case Instruction::FDiv: 2891 case Instruction::FRem: 2892 Assert(B.getType()->isFPOrFPVectorTy(), 2893 "Floating-point arithmetic operators only work with " 2894 "floating-point types!", 2895 &B); 2896 Assert(B.getType() == B.getOperand(0)->getType(), 2897 "Floating-point arithmetic operators must have same type " 2898 "for operands and result!", 2899 &B); 2900 break; 2901 // Check that logical operators are only used with integral operands. 2902 case Instruction::And: 2903 case Instruction::Or: 2904 case Instruction::Xor: 2905 Assert(B.getType()->isIntOrIntVectorTy(), 2906 "Logical operators only work with integral types!", &B); 2907 Assert(B.getType() == B.getOperand(0)->getType(), 2908 "Logical operators must have same type for operands and result!", 2909 &B); 2910 break; 2911 case Instruction::Shl: 2912 case Instruction::LShr: 2913 case Instruction::AShr: 2914 Assert(B.getType()->isIntOrIntVectorTy(), 2915 "Shifts only work with integral types!", &B); 2916 Assert(B.getType() == B.getOperand(0)->getType(), 2917 "Shift return type must be same as operands!", &B); 2918 break; 2919 default: 2920 llvm_unreachable("Unknown BinaryOperator opcode!"); 2921 } 2922 2923 visitInstruction(B); 2924 } 2925 2926 void Verifier::visitICmpInst(ICmpInst &IC) { 2927 // Check that the operands are the same type 2928 Type *Op0Ty = IC.getOperand(0)->getType(); 2929 Type *Op1Ty = IC.getOperand(1)->getType(); 2930 Assert(Op0Ty == Op1Ty, 2931 "Both operands to ICmp instruction are not of the same type!", &IC); 2932 // Check that the operands are the right type 2933 Assert(Op0Ty->isIntOrIntVectorTy() || Op0Ty->getScalarType()->isPointerTy(), 2934 "Invalid operand types for ICmp instruction", &IC); 2935 // Check that the predicate is valid. 2936 Assert(IC.getPredicate() >= CmpInst::FIRST_ICMP_PREDICATE && 2937 IC.getPredicate() <= CmpInst::LAST_ICMP_PREDICATE, 2938 "Invalid predicate in ICmp instruction!", &IC); 2939 2940 visitInstruction(IC); 2941 } 2942 2943 void Verifier::visitFCmpInst(FCmpInst &FC) { 2944 // Check that the operands are the same type 2945 Type *Op0Ty = FC.getOperand(0)->getType(); 2946 Type *Op1Ty = FC.getOperand(1)->getType(); 2947 Assert(Op0Ty == Op1Ty, 2948 "Both operands to FCmp instruction are not of the same type!", &FC); 2949 // Check that the operands are the right type 2950 Assert(Op0Ty->isFPOrFPVectorTy(), 2951 "Invalid operand types for FCmp instruction", &FC); 2952 // Check that the predicate is valid. 2953 Assert(FC.getPredicate() >= CmpInst::FIRST_FCMP_PREDICATE && 2954 FC.getPredicate() <= CmpInst::LAST_FCMP_PREDICATE, 2955 "Invalid predicate in FCmp instruction!", &FC); 2956 2957 visitInstruction(FC); 2958 } 2959 2960 void Verifier::visitExtractElementInst(ExtractElementInst &EI) { 2961 Assert( 2962 ExtractElementInst::isValidOperands(EI.getOperand(0), EI.getOperand(1)), 2963 "Invalid extractelement operands!", &EI); 2964 visitInstruction(EI); 2965 } 2966 2967 void Verifier::visitInsertElementInst(InsertElementInst &IE) { 2968 Assert(InsertElementInst::isValidOperands(IE.getOperand(0), IE.getOperand(1), 2969 IE.getOperand(2)), 2970 "Invalid insertelement operands!", &IE); 2971 visitInstruction(IE); 2972 } 2973 2974 void Verifier::visitShuffleVectorInst(ShuffleVectorInst &SV) { 2975 Assert(ShuffleVectorInst::isValidOperands(SV.getOperand(0), SV.getOperand(1), 2976 SV.getOperand(2)), 2977 "Invalid shufflevector operands!", &SV); 2978 visitInstruction(SV); 2979 } 2980 2981 void Verifier::visitGetElementPtrInst(GetElementPtrInst &GEP) { 2982 Type *TargetTy = GEP.getPointerOperandType()->getScalarType(); 2983 2984 Assert(isa<PointerType>(TargetTy), 2985 "GEP base pointer is not a vector or a vector of pointers", &GEP); 2986 Assert(GEP.getSourceElementType()->isSized(), "GEP into unsized type!", &GEP); 2987 SmallVector<Value*, 16> Idxs(GEP.idx_begin(), GEP.idx_end()); 2988 Type *ElTy = 2989 GetElementPtrInst::getIndexedType(GEP.getSourceElementType(), Idxs); 2990 Assert(ElTy, "Invalid indices for GEP pointer type!", &GEP); 2991 2992 Assert(GEP.getType()->getScalarType()->isPointerTy() && 2993 GEP.getResultElementType() == ElTy, 2994 "GEP is not of right type for indices!", &GEP, ElTy); 2995 2996 if (GEP.getType()->isVectorTy()) { 2997 // Additional checks for vector GEPs. 2998 unsigned GEPWidth = GEP.getType()->getVectorNumElements(); 2999 if (GEP.getPointerOperandType()->isVectorTy()) 3000 Assert(GEPWidth == GEP.getPointerOperandType()->getVectorNumElements(), 3001 "Vector GEP result width doesn't match operand's", &GEP); 3002 for (Value *Idx : Idxs) { 3003 Type *IndexTy = Idx->getType(); 3004 if (IndexTy->isVectorTy()) { 3005 unsigned IndexWidth = IndexTy->getVectorNumElements(); 3006 Assert(IndexWidth == GEPWidth, "Invalid GEP index vector width", &GEP); 3007 } 3008 Assert(IndexTy->getScalarType()->isIntegerTy(), 3009 "All GEP indices should be of integer type"); 3010 } 3011 } 3012 visitInstruction(GEP); 3013 } 3014 3015 static bool isContiguous(const ConstantRange &A, const ConstantRange &B) { 3016 return A.getUpper() == B.getLower() || A.getLower() == B.getUpper(); 3017 } 3018 3019 void Verifier::visitRangeMetadata(Instruction &I, MDNode *Range, Type *Ty) { 3020 assert(Range && Range == I.getMetadata(LLVMContext::MD_range) && 3021 "precondition violation"); 3022 3023 unsigned NumOperands = Range->getNumOperands(); 3024 Assert(NumOperands % 2 == 0, "Unfinished range!", Range); 3025 unsigned NumRanges = NumOperands / 2; 3026 Assert(NumRanges >= 1, "It should have at least one range!", Range); 3027 3028 ConstantRange LastRange(1); // Dummy initial value 3029 for (unsigned i = 0; i < NumRanges; ++i) { 3030 ConstantInt *Low = 3031 mdconst::dyn_extract<ConstantInt>(Range->getOperand(2 * i)); 3032 Assert(Low, "The lower limit must be an integer!", Low); 3033 ConstantInt *High = 3034 mdconst::dyn_extract<ConstantInt>(Range->getOperand(2 * i + 1)); 3035 Assert(High, "The upper limit must be an integer!", High); 3036 Assert(High->getType() == Low->getType() && High->getType() == Ty, 3037 "Range types must match instruction type!", &I); 3038 3039 APInt HighV = High->getValue(); 3040 APInt LowV = Low->getValue(); 3041 ConstantRange CurRange(LowV, HighV); 3042 Assert(!CurRange.isEmptySet() && !CurRange.isFullSet(), 3043 "Range must not be empty!", Range); 3044 if (i != 0) { 3045 Assert(CurRange.intersectWith(LastRange).isEmptySet(), 3046 "Intervals are overlapping", Range); 3047 Assert(LowV.sgt(LastRange.getLower()), "Intervals are not in order", 3048 Range); 3049 Assert(!isContiguous(CurRange, LastRange), "Intervals are contiguous", 3050 Range); 3051 } 3052 LastRange = ConstantRange(LowV, HighV); 3053 } 3054 if (NumRanges > 2) { 3055 APInt FirstLow = 3056 mdconst::dyn_extract<ConstantInt>(Range->getOperand(0))->getValue(); 3057 APInt FirstHigh = 3058 mdconst::dyn_extract<ConstantInt>(Range->getOperand(1))->getValue(); 3059 ConstantRange FirstRange(FirstLow, FirstHigh); 3060 Assert(FirstRange.intersectWith(LastRange).isEmptySet(), 3061 "Intervals are overlapping", Range); 3062 Assert(!isContiguous(FirstRange, LastRange), "Intervals are contiguous", 3063 Range); 3064 } 3065 } 3066 3067 void Verifier::checkAtomicMemAccessSize(Type *Ty, const Instruction *I) { 3068 unsigned Size = DL.getTypeSizeInBits(Ty); 3069 Assert(Size >= 8, "atomic memory access' size must be byte-sized", Ty, I); 3070 Assert(!(Size & (Size - 1)), 3071 "atomic memory access' operand must have a power-of-two size", Ty, I); 3072 } 3073 3074 void Verifier::visitLoadInst(LoadInst &LI) { 3075 PointerType *PTy = dyn_cast<PointerType>(LI.getOperand(0)->getType()); 3076 Assert(PTy, "Load operand must be a pointer.", &LI); 3077 Type *ElTy = LI.getType(); 3078 Assert(LI.getAlignment() <= Value::MaximumAlignment, 3079 "huge alignment values are unsupported", &LI); 3080 Assert(ElTy->isSized(), "loading unsized types is not allowed", &LI); 3081 if (LI.isAtomic()) { 3082 Assert(LI.getOrdering() != AtomicOrdering::Release && 3083 LI.getOrdering() != AtomicOrdering::AcquireRelease, 3084 "Load cannot have Release ordering", &LI); 3085 Assert(LI.getAlignment() != 0, 3086 "Atomic load must specify explicit alignment", &LI); 3087 Assert(ElTy->isIntegerTy() || ElTy->isPointerTy() || 3088 ElTy->isFloatingPointTy(), 3089 "atomic load operand must have integer, pointer, or floating point " 3090 "type!", 3091 ElTy, &LI); 3092 checkAtomicMemAccessSize(ElTy, &LI); 3093 } else { 3094 Assert(LI.getSynchScope() == CrossThread, 3095 "Non-atomic load cannot have SynchronizationScope specified", &LI); 3096 } 3097 3098 visitInstruction(LI); 3099 } 3100 3101 void Verifier::visitStoreInst(StoreInst &SI) { 3102 PointerType *PTy = dyn_cast<PointerType>(SI.getOperand(1)->getType()); 3103 Assert(PTy, "Store operand must be a pointer.", &SI); 3104 Type *ElTy = PTy->getElementType(); 3105 Assert(ElTy == SI.getOperand(0)->getType(), 3106 "Stored value type does not match pointer operand type!", &SI, ElTy); 3107 Assert(SI.getAlignment() <= Value::MaximumAlignment, 3108 "huge alignment values are unsupported", &SI); 3109 Assert(ElTy->isSized(), "storing unsized types is not allowed", &SI); 3110 if (SI.isAtomic()) { 3111 Assert(SI.getOrdering() != AtomicOrdering::Acquire && 3112 SI.getOrdering() != AtomicOrdering::AcquireRelease, 3113 "Store cannot have Acquire ordering", &SI); 3114 Assert(SI.getAlignment() != 0, 3115 "Atomic store must specify explicit alignment", &SI); 3116 Assert(ElTy->isIntegerTy() || ElTy->isPointerTy() || 3117 ElTy->isFloatingPointTy(), 3118 "atomic store operand must have integer, pointer, or floating point " 3119 "type!", 3120 ElTy, &SI); 3121 checkAtomicMemAccessSize(ElTy, &SI); 3122 } else { 3123 Assert(SI.getSynchScope() == CrossThread, 3124 "Non-atomic store cannot have SynchronizationScope specified", &SI); 3125 } 3126 visitInstruction(SI); 3127 } 3128 3129 /// Check that SwiftErrorVal is used as a swifterror argument in CS. 3130 void Verifier::verifySwiftErrorCallSite(CallSite CS, 3131 const Value *SwiftErrorVal) { 3132 unsigned Idx = 0; 3133 for (CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end(); 3134 I != E; ++I, ++Idx) { 3135 if (*I == SwiftErrorVal) { 3136 Assert(CS.paramHasAttr(Idx, Attribute::SwiftError), 3137 "swifterror value when used in a callsite should be marked " 3138 "with swifterror attribute", 3139 SwiftErrorVal, CS); 3140 } 3141 } 3142 } 3143 3144 void Verifier::verifySwiftErrorValue(const Value *SwiftErrorVal) { 3145 // Check that swifterror value is only used by loads, stores, or as 3146 // a swifterror argument. 3147 for (const User *U : SwiftErrorVal->users()) { 3148 Assert(isa<LoadInst>(U) || isa<StoreInst>(U) || isa<CallInst>(U) || 3149 isa<InvokeInst>(U), 3150 "swifterror value can only be loaded and stored from, or " 3151 "as a swifterror argument!", 3152 SwiftErrorVal, U); 3153 // If it is used by a store, check it is the second operand. 3154 if (auto StoreI = dyn_cast<StoreInst>(U)) 3155 Assert(StoreI->getOperand(1) == SwiftErrorVal, 3156 "swifterror value should be the second operand when used " 3157 "by stores", SwiftErrorVal, U); 3158 if (auto CallI = dyn_cast<CallInst>(U)) 3159 verifySwiftErrorCallSite(const_cast<CallInst*>(CallI), SwiftErrorVal); 3160 if (auto II = dyn_cast<InvokeInst>(U)) 3161 verifySwiftErrorCallSite(const_cast<InvokeInst*>(II), SwiftErrorVal); 3162 } 3163 } 3164 3165 void Verifier::visitAllocaInst(AllocaInst &AI) { 3166 SmallPtrSet<Type*, 4> Visited; 3167 PointerType *PTy = AI.getType(); 3168 // TODO: Relax this restriction? 3169 Assert(PTy->getAddressSpace() == DL.getAllocaAddrSpace(), 3170 "Allocation instruction pointer not in the stack address space!", 3171 &AI); 3172 Assert(AI.getAllocatedType()->isSized(&Visited), 3173 "Cannot allocate unsized type", &AI); 3174 Assert(AI.getArraySize()->getType()->isIntegerTy(), 3175 "Alloca array size must have integer type", &AI); 3176 Assert(AI.getAlignment() <= Value::MaximumAlignment, 3177 "huge alignment values are unsupported", &AI); 3178 3179 if (AI.isSwiftError()) { 3180 verifySwiftErrorValue(&AI); 3181 } 3182 3183 visitInstruction(AI); 3184 } 3185 3186 void Verifier::visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI) { 3187 3188 // FIXME: more conditions??? 3189 Assert(CXI.getSuccessOrdering() != AtomicOrdering::NotAtomic, 3190 "cmpxchg instructions must be atomic.", &CXI); 3191 Assert(CXI.getFailureOrdering() != AtomicOrdering::NotAtomic, 3192 "cmpxchg instructions must be atomic.", &CXI); 3193 Assert(CXI.getSuccessOrdering() != AtomicOrdering::Unordered, 3194 "cmpxchg instructions cannot be unordered.", &CXI); 3195 Assert(CXI.getFailureOrdering() != AtomicOrdering::Unordered, 3196 "cmpxchg instructions cannot be unordered.", &CXI); 3197 Assert(!isStrongerThan(CXI.getFailureOrdering(), CXI.getSuccessOrdering()), 3198 "cmpxchg instructions failure argument shall be no stronger than the " 3199 "success argument", 3200 &CXI); 3201 Assert(CXI.getFailureOrdering() != AtomicOrdering::Release && 3202 CXI.getFailureOrdering() != AtomicOrdering::AcquireRelease, 3203 "cmpxchg failure ordering cannot include release semantics", &CXI); 3204 3205 PointerType *PTy = dyn_cast<PointerType>(CXI.getOperand(0)->getType()); 3206 Assert(PTy, "First cmpxchg operand must be a pointer.", &CXI); 3207 Type *ElTy = PTy->getElementType(); 3208 Assert(ElTy->isIntegerTy() || ElTy->isPointerTy(), 3209 "cmpxchg operand must have integer or pointer type", 3210 ElTy, &CXI); 3211 checkAtomicMemAccessSize(ElTy, &CXI); 3212 Assert(ElTy == CXI.getOperand(1)->getType(), 3213 "Expected value type does not match pointer operand type!", &CXI, 3214 ElTy); 3215 Assert(ElTy == CXI.getOperand(2)->getType(), 3216 "Stored value type does not match pointer operand type!", &CXI, ElTy); 3217 visitInstruction(CXI); 3218 } 3219 3220 void Verifier::visitAtomicRMWInst(AtomicRMWInst &RMWI) { 3221 Assert(RMWI.getOrdering() != AtomicOrdering::NotAtomic, 3222 "atomicrmw instructions must be atomic.", &RMWI); 3223 Assert(RMWI.getOrdering() != AtomicOrdering::Unordered, 3224 "atomicrmw instructions cannot be unordered.", &RMWI); 3225 PointerType *PTy = dyn_cast<PointerType>(RMWI.getOperand(0)->getType()); 3226 Assert(PTy, "First atomicrmw operand must be a pointer.", &RMWI); 3227 Type *ElTy = PTy->getElementType(); 3228 Assert(ElTy->isIntegerTy(), "atomicrmw operand must have integer type!", 3229 &RMWI, ElTy); 3230 checkAtomicMemAccessSize(ElTy, &RMWI); 3231 Assert(ElTy == RMWI.getOperand(1)->getType(), 3232 "Argument value type does not match pointer operand type!", &RMWI, 3233 ElTy); 3234 Assert(AtomicRMWInst::FIRST_BINOP <= RMWI.getOperation() && 3235 RMWI.getOperation() <= AtomicRMWInst::LAST_BINOP, 3236 "Invalid binary operation!", &RMWI); 3237 visitInstruction(RMWI); 3238 } 3239 3240 void Verifier::visitFenceInst(FenceInst &FI) { 3241 const AtomicOrdering Ordering = FI.getOrdering(); 3242 Assert(Ordering == AtomicOrdering::Acquire || 3243 Ordering == AtomicOrdering::Release || 3244 Ordering == AtomicOrdering::AcquireRelease || 3245 Ordering == AtomicOrdering::SequentiallyConsistent, 3246 "fence instructions may only have acquire, release, acq_rel, or " 3247 "seq_cst ordering.", 3248 &FI); 3249 visitInstruction(FI); 3250 } 3251 3252 void Verifier::visitExtractValueInst(ExtractValueInst &EVI) { 3253 Assert(ExtractValueInst::getIndexedType(EVI.getAggregateOperand()->getType(), 3254 EVI.getIndices()) == EVI.getType(), 3255 "Invalid ExtractValueInst operands!", &EVI); 3256 3257 visitInstruction(EVI); 3258 } 3259 3260 void Verifier::visitInsertValueInst(InsertValueInst &IVI) { 3261 Assert(ExtractValueInst::getIndexedType(IVI.getAggregateOperand()->getType(), 3262 IVI.getIndices()) == 3263 IVI.getOperand(1)->getType(), 3264 "Invalid InsertValueInst operands!", &IVI); 3265 3266 visitInstruction(IVI); 3267 } 3268 3269 static Value *getParentPad(Value *EHPad) { 3270 if (auto *FPI = dyn_cast<FuncletPadInst>(EHPad)) 3271 return FPI->getParentPad(); 3272 3273 return cast<CatchSwitchInst>(EHPad)->getParentPad(); 3274 } 3275 3276 void Verifier::visitEHPadPredecessors(Instruction &I) { 3277 assert(I.isEHPad()); 3278 3279 BasicBlock *BB = I.getParent(); 3280 Function *F = BB->getParent(); 3281 3282 Assert(BB != &F->getEntryBlock(), "EH pad cannot be in entry block.", &I); 3283 3284 if (auto *LPI = dyn_cast<LandingPadInst>(&I)) { 3285 // The landingpad instruction defines its parent as a landing pad block. The 3286 // landing pad block may be branched to only by the unwind edge of an 3287 // invoke. 3288 for (BasicBlock *PredBB : predecessors(BB)) { 3289 const auto *II = dyn_cast<InvokeInst>(PredBB->getTerminator()); 3290 Assert(II && II->getUnwindDest() == BB && II->getNormalDest() != BB, 3291 "Block containing LandingPadInst must be jumped to " 3292 "only by the unwind edge of an invoke.", 3293 LPI); 3294 } 3295 return; 3296 } 3297 if (auto *CPI = dyn_cast<CatchPadInst>(&I)) { 3298 if (!pred_empty(BB)) 3299 Assert(BB->getUniquePredecessor() == CPI->getCatchSwitch()->getParent(), 3300 "Block containg CatchPadInst must be jumped to " 3301 "only by its catchswitch.", 3302 CPI); 3303 Assert(BB != CPI->getCatchSwitch()->getUnwindDest(), 3304 "Catchswitch cannot unwind to one of its catchpads", 3305 CPI->getCatchSwitch(), CPI); 3306 return; 3307 } 3308 3309 // Verify that each pred has a legal terminator with a legal to/from EH 3310 // pad relationship. 3311 Instruction *ToPad = &I; 3312 Value *ToPadParent = getParentPad(ToPad); 3313 for (BasicBlock *PredBB : predecessors(BB)) { 3314 TerminatorInst *TI = PredBB->getTerminator(); 3315 Value *FromPad; 3316 if (auto *II = dyn_cast<InvokeInst>(TI)) { 3317 Assert(II->getUnwindDest() == BB && II->getNormalDest() != BB, 3318 "EH pad must be jumped to via an unwind edge", ToPad, II); 3319 if (auto Bundle = II->getOperandBundle(LLVMContext::OB_funclet)) 3320 FromPad = Bundle->Inputs[0]; 3321 else 3322 FromPad = ConstantTokenNone::get(II->getContext()); 3323 } else if (auto *CRI = dyn_cast<CleanupReturnInst>(TI)) { 3324 FromPad = CRI->getOperand(0); 3325 Assert(FromPad != ToPadParent, "A cleanupret must exit its cleanup", CRI); 3326 } else if (auto *CSI = dyn_cast<CatchSwitchInst>(TI)) { 3327 FromPad = CSI; 3328 } else { 3329 Assert(false, "EH pad must be jumped to via an unwind edge", ToPad, TI); 3330 } 3331 3332 // The edge may exit from zero or more nested pads. 3333 SmallSet<Value *, 8> Seen; 3334 for (;; FromPad = getParentPad(FromPad)) { 3335 Assert(FromPad != ToPad, 3336 "EH pad cannot handle exceptions raised within it", FromPad, TI); 3337 if (FromPad == ToPadParent) { 3338 // This is a legal unwind edge. 3339 break; 3340 } 3341 Assert(!isa<ConstantTokenNone>(FromPad), 3342 "A single unwind edge may only enter one EH pad", TI); 3343 Assert(Seen.insert(FromPad).second, 3344 "EH pad jumps through a cycle of pads", FromPad); 3345 } 3346 } 3347 } 3348 3349 void Verifier::visitLandingPadInst(LandingPadInst &LPI) { 3350 // The landingpad instruction is ill-formed if it doesn't have any clauses and 3351 // isn't a cleanup. 3352 Assert(LPI.getNumClauses() > 0 || LPI.isCleanup(), 3353 "LandingPadInst needs at least one clause or to be a cleanup.", &LPI); 3354 3355 visitEHPadPredecessors(LPI); 3356 3357 if (!LandingPadResultTy) 3358 LandingPadResultTy = LPI.getType(); 3359 else 3360 Assert(LandingPadResultTy == LPI.getType(), 3361 "The landingpad instruction should have a consistent result type " 3362 "inside a function.", 3363 &LPI); 3364 3365 Function *F = LPI.getParent()->getParent(); 3366 Assert(F->hasPersonalityFn(), 3367 "LandingPadInst needs to be in a function with a personality.", &LPI); 3368 3369 // The landingpad instruction must be the first non-PHI instruction in the 3370 // block. 3371 Assert(LPI.getParent()->getLandingPadInst() == &LPI, 3372 "LandingPadInst not the first non-PHI instruction in the block.", 3373 &LPI); 3374 3375 for (unsigned i = 0, e = LPI.getNumClauses(); i < e; ++i) { 3376 Constant *Clause = LPI.getClause(i); 3377 if (LPI.isCatch(i)) { 3378 Assert(isa<PointerType>(Clause->getType()), 3379 "Catch operand does not have pointer type!", &LPI); 3380 } else { 3381 Assert(LPI.isFilter(i), "Clause is neither catch nor filter!", &LPI); 3382 Assert(isa<ConstantArray>(Clause) || isa<ConstantAggregateZero>(Clause), 3383 "Filter operand is not an array of constants!", &LPI); 3384 } 3385 } 3386 3387 visitInstruction(LPI); 3388 } 3389 3390 void Verifier::visitResumeInst(ResumeInst &RI) { 3391 Assert(RI.getFunction()->hasPersonalityFn(), 3392 "ResumeInst needs to be in a function with a personality.", &RI); 3393 3394 if (!LandingPadResultTy) 3395 LandingPadResultTy = RI.getValue()->getType(); 3396 else 3397 Assert(LandingPadResultTy == RI.getValue()->getType(), 3398 "The resume instruction should have a consistent result type " 3399 "inside a function.", 3400 &RI); 3401 3402 visitTerminatorInst(RI); 3403 } 3404 3405 void Verifier::visitCatchPadInst(CatchPadInst &CPI) { 3406 BasicBlock *BB = CPI.getParent(); 3407 3408 Function *F = BB->getParent(); 3409 Assert(F->hasPersonalityFn(), 3410 "CatchPadInst needs to be in a function with a personality.", &CPI); 3411 3412 Assert(isa<CatchSwitchInst>(CPI.getParentPad()), 3413 "CatchPadInst needs to be directly nested in a CatchSwitchInst.", 3414 CPI.getParentPad()); 3415 3416 // The catchpad instruction must be the first non-PHI instruction in the 3417 // block. 3418 Assert(BB->getFirstNonPHI() == &CPI, 3419 "CatchPadInst not the first non-PHI instruction in the block.", &CPI); 3420 3421 visitEHPadPredecessors(CPI); 3422 visitFuncletPadInst(CPI); 3423 } 3424 3425 void Verifier::visitCatchReturnInst(CatchReturnInst &CatchReturn) { 3426 Assert(isa<CatchPadInst>(CatchReturn.getOperand(0)), 3427 "CatchReturnInst needs to be provided a CatchPad", &CatchReturn, 3428 CatchReturn.getOperand(0)); 3429 3430 visitTerminatorInst(CatchReturn); 3431 } 3432 3433 void Verifier::visitCleanupPadInst(CleanupPadInst &CPI) { 3434 BasicBlock *BB = CPI.getParent(); 3435 3436 Function *F = BB->getParent(); 3437 Assert(F->hasPersonalityFn(), 3438 "CleanupPadInst needs to be in a function with a personality.", &CPI); 3439 3440 // The cleanuppad instruction must be the first non-PHI instruction in the 3441 // block. 3442 Assert(BB->getFirstNonPHI() == &CPI, 3443 "CleanupPadInst not the first non-PHI instruction in the block.", 3444 &CPI); 3445 3446 auto *ParentPad = CPI.getParentPad(); 3447 Assert(isa<ConstantTokenNone>(ParentPad) || isa<FuncletPadInst>(ParentPad), 3448 "CleanupPadInst has an invalid parent.", &CPI); 3449 3450 visitEHPadPredecessors(CPI); 3451 visitFuncletPadInst(CPI); 3452 } 3453 3454 void Verifier::visitFuncletPadInst(FuncletPadInst &FPI) { 3455 User *FirstUser = nullptr; 3456 Value *FirstUnwindPad = nullptr; 3457 SmallVector<FuncletPadInst *, 8> Worklist({&FPI}); 3458 SmallSet<FuncletPadInst *, 8> Seen; 3459 3460 while (!Worklist.empty()) { 3461 FuncletPadInst *CurrentPad = Worklist.pop_back_val(); 3462 Assert(Seen.insert(CurrentPad).second, 3463 "FuncletPadInst must not be nested within itself", CurrentPad); 3464 Value *UnresolvedAncestorPad = nullptr; 3465 for (User *U : CurrentPad->users()) { 3466 BasicBlock *UnwindDest; 3467 if (auto *CRI = dyn_cast<CleanupReturnInst>(U)) { 3468 UnwindDest = CRI->getUnwindDest(); 3469 } else if (auto *CSI = dyn_cast<CatchSwitchInst>(U)) { 3470 // We allow catchswitch unwind to caller to nest 3471 // within an outer pad that unwinds somewhere else, 3472 // because catchswitch doesn't have a nounwind variant. 3473 // See e.g. SimplifyCFGOpt::SimplifyUnreachable. 3474 if (CSI->unwindsToCaller()) 3475 continue; 3476 UnwindDest = CSI->getUnwindDest(); 3477 } else if (auto *II = dyn_cast<InvokeInst>(U)) { 3478 UnwindDest = II->getUnwindDest(); 3479 } else if (isa<CallInst>(U)) { 3480 // Calls which don't unwind may be found inside funclet 3481 // pads that unwind somewhere else. We don't *require* 3482 // such calls to be annotated nounwind. 3483 continue; 3484 } else if (auto *CPI = dyn_cast<CleanupPadInst>(U)) { 3485 // The unwind dest for a cleanup can only be found by 3486 // recursive search. Add it to the worklist, and we'll 3487 // search for its first use that determines where it unwinds. 3488 Worklist.push_back(CPI); 3489 continue; 3490 } else { 3491 Assert(isa<CatchReturnInst>(U), "Bogus funclet pad use", U); 3492 continue; 3493 } 3494 3495 Value *UnwindPad; 3496 bool ExitsFPI; 3497 if (UnwindDest) { 3498 UnwindPad = UnwindDest->getFirstNonPHI(); 3499 if (!cast<Instruction>(UnwindPad)->isEHPad()) 3500 continue; 3501 Value *UnwindParent = getParentPad(UnwindPad); 3502 // Ignore unwind edges that don't exit CurrentPad. 3503 if (UnwindParent == CurrentPad) 3504 continue; 3505 // Determine whether the original funclet pad is exited, 3506 // and if we are scanning nested pads determine how many 3507 // of them are exited so we can stop searching their 3508 // children. 3509 Value *ExitedPad = CurrentPad; 3510 ExitsFPI = false; 3511 do { 3512 if (ExitedPad == &FPI) { 3513 ExitsFPI = true; 3514 // Now we can resolve any ancestors of CurrentPad up to 3515 // FPI, but not including FPI since we need to make sure 3516 // to check all direct users of FPI for consistency. 3517 UnresolvedAncestorPad = &FPI; 3518 break; 3519 } 3520 Value *ExitedParent = getParentPad(ExitedPad); 3521 if (ExitedParent == UnwindParent) { 3522 // ExitedPad is the ancestor-most pad which this unwind 3523 // edge exits, so we can resolve up to it, meaning that 3524 // ExitedParent is the first ancestor still unresolved. 3525 UnresolvedAncestorPad = ExitedParent; 3526 break; 3527 } 3528 ExitedPad = ExitedParent; 3529 } while (!isa<ConstantTokenNone>(ExitedPad)); 3530 } else { 3531 // Unwinding to caller exits all pads. 3532 UnwindPad = ConstantTokenNone::get(FPI.getContext()); 3533 ExitsFPI = true; 3534 UnresolvedAncestorPad = &FPI; 3535 } 3536 3537 if (ExitsFPI) { 3538 // This unwind edge exits FPI. Make sure it agrees with other 3539 // such edges. 3540 if (FirstUser) { 3541 Assert(UnwindPad == FirstUnwindPad, "Unwind edges out of a funclet " 3542 "pad must have the same unwind " 3543 "dest", 3544 &FPI, U, FirstUser); 3545 } else { 3546 FirstUser = U; 3547 FirstUnwindPad = UnwindPad; 3548 // Record cleanup sibling unwinds for verifySiblingFuncletUnwinds 3549 if (isa<CleanupPadInst>(&FPI) && !isa<ConstantTokenNone>(UnwindPad) && 3550 getParentPad(UnwindPad) == getParentPad(&FPI)) 3551 SiblingFuncletInfo[&FPI] = cast<TerminatorInst>(U); 3552 } 3553 } 3554 // Make sure we visit all uses of FPI, but for nested pads stop as 3555 // soon as we know where they unwind to. 3556 if (CurrentPad != &FPI) 3557 break; 3558 } 3559 if (UnresolvedAncestorPad) { 3560 if (CurrentPad == UnresolvedAncestorPad) { 3561 // When CurrentPad is FPI itself, we don't mark it as resolved even if 3562 // we've found an unwind edge that exits it, because we need to verify 3563 // all direct uses of FPI. 3564 assert(CurrentPad == &FPI); 3565 continue; 3566 } 3567 // Pop off the worklist any nested pads that we've found an unwind 3568 // destination for. The pads on the worklist are the uncles, 3569 // great-uncles, etc. of CurrentPad. We've found an unwind destination 3570 // for all ancestors of CurrentPad up to but not including 3571 // UnresolvedAncestorPad. 3572 Value *ResolvedPad = CurrentPad; 3573 while (!Worklist.empty()) { 3574 Value *UnclePad = Worklist.back(); 3575 Value *AncestorPad = getParentPad(UnclePad); 3576 // Walk ResolvedPad up the ancestor list until we either find the 3577 // uncle's parent or the last resolved ancestor. 3578 while (ResolvedPad != AncestorPad) { 3579 Value *ResolvedParent = getParentPad(ResolvedPad); 3580 if (ResolvedParent == UnresolvedAncestorPad) { 3581 break; 3582 } 3583 ResolvedPad = ResolvedParent; 3584 } 3585 // If the resolved ancestor search didn't find the uncle's parent, 3586 // then the uncle is not yet resolved. 3587 if (ResolvedPad != AncestorPad) 3588 break; 3589 // This uncle is resolved, so pop it from the worklist. 3590 Worklist.pop_back(); 3591 } 3592 } 3593 } 3594 3595 if (FirstUnwindPad) { 3596 if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(FPI.getParentPad())) { 3597 BasicBlock *SwitchUnwindDest = CatchSwitch->getUnwindDest(); 3598 Value *SwitchUnwindPad; 3599 if (SwitchUnwindDest) 3600 SwitchUnwindPad = SwitchUnwindDest->getFirstNonPHI(); 3601 else 3602 SwitchUnwindPad = ConstantTokenNone::get(FPI.getContext()); 3603 Assert(SwitchUnwindPad == FirstUnwindPad, 3604 "Unwind edges out of a catch must have the same unwind dest as " 3605 "the parent catchswitch", 3606 &FPI, FirstUser, CatchSwitch); 3607 } 3608 } 3609 3610 visitInstruction(FPI); 3611 } 3612 3613 void Verifier::visitCatchSwitchInst(CatchSwitchInst &CatchSwitch) { 3614 BasicBlock *BB = CatchSwitch.getParent(); 3615 3616 Function *F = BB->getParent(); 3617 Assert(F->hasPersonalityFn(), 3618 "CatchSwitchInst needs to be in a function with a personality.", 3619 &CatchSwitch); 3620 3621 // The catchswitch instruction must be the first non-PHI instruction in the 3622 // block. 3623 Assert(BB->getFirstNonPHI() == &CatchSwitch, 3624 "CatchSwitchInst not the first non-PHI instruction in the block.", 3625 &CatchSwitch); 3626 3627 auto *ParentPad = CatchSwitch.getParentPad(); 3628 Assert(isa<ConstantTokenNone>(ParentPad) || isa<FuncletPadInst>(ParentPad), 3629 "CatchSwitchInst has an invalid parent.", ParentPad); 3630 3631 if (BasicBlock *UnwindDest = CatchSwitch.getUnwindDest()) { 3632 Instruction *I = UnwindDest->getFirstNonPHI(); 3633 Assert(I->isEHPad() && !isa<LandingPadInst>(I), 3634 "CatchSwitchInst must unwind to an EH block which is not a " 3635 "landingpad.", 3636 &CatchSwitch); 3637 3638 // Record catchswitch sibling unwinds for verifySiblingFuncletUnwinds 3639 if (getParentPad(I) == ParentPad) 3640 SiblingFuncletInfo[&CatchSwitch] = &CatchSwitch; 3641 } 3642 3643 Assert(CatchSwitch.getNumHandlers() != 0, 3644 "CatchSwitchInst cannot have empty handler list", &CatchSwitch); 3645 3646 for (BasicBlock *Handler : CatchSwitch.handlers()) { 3647 Assert(isa<CatchPadInst>(Handler->getFirstNonPHI()), 3648 "CatchSwitchInst handlers must be catchpads", &CatchSwitch, Handler); 3649 } 3650 3651 visitEHPadPredecessors(CatchSwitch); 3652 visitTerminatorInst(CatchSwitch); 3653 } 3654 3655 void Verifier::visitCleanupReturnInst(CleanupReturnInst &CRI) { 3656 Assert(isa<CleanupPadInst>(CRI.getOperand(0)), 3657 "CleanupReturnInst needs to be provided a CleanupPad", &CRI, 3658 CRI.getOperand(0)); 3659 3660 if (BasicBlock *UnwindDest = CRI.getUnwindDest()) { 3661 Instruction *I = UnwindDest->getFirstNonPHI(); 3662 Assert(I->isEHPad() && !isa<LandingPadInst>(I), 3663 "CleanupReturnInst must unwind to an EH block which is not a " 3664 "landingpad.", 3665 &CRI); 3666 } 3667 3668 visitTerminatorInst(CRI); 3669 } 3670 3671 void Verifier::verifyDominatesUse(Instruction &I, unsigned i) { 3672 Instruction *Op = cast<Instruction>(I.getOperand(i)); 3673 // If the we have an invalid invoke, don't try to compute the dominance. 3674 // We already reject it in the invoke specific checks and the dominance 3675 // computation doesn't handle multiple edges. 3676 if (InvokeInst *II = dyn_cast<InvokeInst>(Op)) { 3677 if (II->getNormalDest() == II->getUnwindDest()) 3678 return; 3679 } 3680 3681 // Quick check whether the def has already been encountered in the same block. 3682 // PHI nodes are not checked to prevent accepting preceeding PHIs, because PHI 3683 // uses are defined to happen on the incoming edge, not at the instruction. 3684 // 3685 // FIXME: If this operand is a MetadataAsValue (wrapping a LocalAsMetadata) 3686 // wrapping an SSA value, assert that we've already encountered it. See 3687 // related FIXME in Mapper::mapLocalAsMetadata in ValueMapper.cpp. 3688 if (!isa<PHINode>(I) && InstsInThisBlock.count(Op)) 3689 return; 3690 3691 const Use &U = I.getOperandUse(i); 3692 Assert(DT.dominates(Op, U), 3693 "Instruction does not dominate all uses!", Op, &I); 3694 } 3695 3696 void Verifier::visitDereferenceableMetadata(Instruction& I, MDNode* MD) { 3697 Assert(I.getType()->isPointerTy(), "dereferenceable, dereferenceable_or_null " 3698 "apply only to pointer types", &I); 3699 Assert(isa<LoadInst>(I), 3700 "dereferenceable, dereferenceable_or_null apply only to load" 3701 " instructions, use attributes for calls or invokes", &I); 3702 Assert(MD->getNumOperands() == 1, "dereferenceable, dereferenceable_or_null " 3703 "take one operand!", &I); 3704 ConstantInt *CI = mdconst::dyn_extract<ConstantInt>(MD->getOperand(0)); 3705 Assert(CI && CI->getType()->isIntegerTy(64), "dereferenceable, " 3706 "dereferenceable_or_null metadata value must be an i64!", &I); 3707 } 3708 3709 /// verifyInstruction - Verify that an instruction is well formed. 3710 /// 3711 void Verifier::visitInstruction(Instruction &I) { 3712 BasicBlock *BB = I.getParent(); 3713 Assert(BB, "Instruction not embedded in basic block!", &I); 3714 3715 if (!isa<PHINode>(I)) { // Check that non-phi nodes are not self referential 3716 for (User *U : I.users()) { 3717 Assert(U != (User *)&I || !DT.isReachableFromEntry(BB), 3718 "Only PHI nodes may reference their own value!", &I); 3719 } 3720 } 3721 3722 // Check that void typed values don't have names 3723 Assert(!I.getType()->isVoidTy() || !I.hasName(), 3724 "Instruction has a name, but provides a void value!", &I); 3725 3726 // Check that the return value of the instruction is either void or a legal 3727 // value type. 3728 Assert(I.getType()->isVoidTy() || I.getType()->isFirstClassType(), 3729 "Instruction returns a non-scalar type!", &I); 3730 3731 // Check that the instruction doesn't produce metadata. Calls are already 3732 // checked against the callee type. 3733 Assert(!I.getType()->isMetadataTy() || isa<CallInst>(I) || isa<InvokeInst>(I), 3734 "Invalid use of metadata!", &I); 3735 3736 // Check that all uses of the instruction, if they are instructions 3737 // themselves, actually have parent basic blocks. If the use is not an 3738 // instruction, it is an error! 3739 for (Use &U : I.uses()) { 3740 if (Instruction *Used = dyn_cast<Instruction>(U.getUser())) 3741 Assert(Used->getParent() != nullptr, 3742 "Instruction referencing" 3743 " instruction not embedded in a basic block!", 3744 &I, Used); 3745 else { 3746 CheckFailed("Use of instruction is not an instruction!", U); 3747 return; 3748 } 3749 } 3750 3751 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) { 3752 Assert(I.getOperand(i) != nullptr, "Instruction has null operand!", &I); 3753 3754 // Check to make sure that only first-class-values are operands to 3755 // instructions. 3756 if (!I.getOperand(i)->getType()->isFirstClassType()) { 3757 Assert(false, "Instruction operands must be first-class values!", &I); 3758 } 3759 3760 if (Function *F = dyn_cast<Function>(I.getOperand(i))) { 3761 // Check to make sure that the "address of" an intrinsic function is never 3762 // taken. 3763 Assert( 3764 !F->isIntrinsic() || 3765 i == (isa<CallInst>(I) ? e - 1 : isa<InvokeInst>(I) ? e - 3 : 0), 3766 "Cannot take the address of an intrinsic!", &I); 3767 Assert( 3768 !F->isIntrinsic() || isa<CallInst>(I) || 3769 F->getIntrinsicID() == Intrinsic::donothing || 3770 F->getIntrinsicID() == Intrinsic::coro_resume || 3771 F->getIntrinsicID() == Intrinsic::coro_destroy || 3772 F->getIntrinsicID() == Intrinsic::experimental_patchpoint_void || 3773 F->getIntrinsicID() == Intrinsic::experimental_patchpoint_i64 || 3774 F->getIntrinsicID() == Intrinsic::experimental_gc_statepoint, 3775 "Cannot invoke an intrinsic other than donothing, patchpoint, " 3776 "statepoint, coro_resume or coro_destroy", 3777 &I); 3778 Assert(F->getParent() == &M, "Referencing function in another module!", 3779 &I, &M, F, F->getParent()); 3780 } else if (BasicBlock *OpBB = dyn_cast<BasicBlock>(I.getOperand(i))) { 3781 Assert(OpBB->getParent() == BB->getParent(), 3782 "Referring to a basic block in another function!", &I); 3783 } else if (Argument *OpArg = dyn_cast<Argument>(I.getOperand(i))) { 3784 Assert(OpArg->getParent() == BB->getParent(), 3785 "Referring to an argument in another function!", &I); 3786 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(I.getOperand(i))) { 3787 Assert(GV->getParent() == &M, "Referencing global in another module!", &I, 3788 &M, GV, GV->getParent()); 3789 } else if (isa<Instruction>(I.getOperand(i))) { 3790 verifyDominatesUse(I, i); 3791 } else if (isa<InlineAsm>(I.getOperand(i))) { 3792 Assert((i + 1 == e && isa<CallInst>(I)) || 3793 (i + 3 == e && isa<InvokeInst>(I)), 3794 "Cannot take the address of an inline asm!", &I); 3795 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(I.getOperand(i))) { 3796 if (CE->getType()->isPtrOrPtrVectorTy() || 3797 !DL.getNonIntegralAddressSpaces().empty()) { 3798 // If we have a ConstantExpr pointer, we need to see if it came from an 3799 // illegal bitcast. If the datalayout string specifies non-integral 3800 // address spaces then we also need to check for illegal ptrtoint and 3801 // inttoptr expressions. 3802 visitConstantExprsRecursively(CE); 3803 } 3804 } 3805 } 3806 3807 if (MDNode *MD = I.getMetadata(LLVMContext::MD_fpmath)) { 3808 Assert(I.getType()->isFPOrFPVectorTy(), 3809 "fpmath requires a floating point result!", &I); 3810 Assert(MD->getNumOperands() == 1, "fpmath takes one operand!", &I); 3811 if (ConstantFP *CFP0 = 3812 mdconst::dyn_extract_or_null<ConstantFP>(MD->getOperand(0))) { 3813 const APFloat &Accuracy = CFP0->getValueAPF(); 3814 Assert(&Accuracy.getSemantics() == &APFloat::IEEEsingle(), 3815 "fpmath accuracy must have float type", &I); 3816 Assert(Accuracy.isFiniteNonZero() && !Accuracy.isNegative(), 3817 "fpmath accuracy not a positive number!", &I); 3818 } else { 3819 Assert(false, "invalid fpmath accuracy!", &I); 3820 } 3821 } 3822 3823 if (MDNode *Range = I.getMetadata(LLVMContext::MD_range)) { 3824 Assert(isa<LoadInst>(I) || isa<CallInst>(I) || isa<InvokeInst>(I), 3825 "Ranges are only for loads, calls and invokes!", &I); 3826 visitRangeMetadata(I, Range, I.getType()); 3827 } 3828 3829 if (I.getMetadata(LLVMContext::MD_nonnull)) { 3830 Assert(I.getType()->isPointerTy(), "nonnull applies only to pointer types", 3831 &I); 3832 Assert(isa<LoadInst>(I), 3833 "nonnull applies only to load instructions, use attributes" 3834 " for calls or invokes", 3835 &I); 3836 } 3837 3838 if (MDNode *MD = I.getMetadata(LLVMContext::MD_dereferenceable)) 3839 visitDereferenceableMetadata(I, MD); 3840 3841 if (MDNode *MD = I.getMetadata(LLVMContext::MD_dereferenceable_or_null)) 3842 visitDereferenceableMetadata(I, MD); 3843 3844 if (MDNode *TBAA = I.getMetadata(LLVMContext::MD_tbaa)) 3845 TBAAVerifyHelper.visitTBAAMetadata(I, TBAA); 3846 3847 if (MDNode *AlignMD = I.getMetadata(LLVMContext::MD_align)) { 3848 Assert(I.getType()->isPointerTy(), "align applies only to pointer types", 3849 &I); 3850 Assert(isa<LoadInst>(I), "align applies only to load instructions, " 3851 "use attributes for calls or invokes", &I); 3852 Assert(AlignMD->getNumOperands() == 1, "align takes one operand!", &I); 3853 ConstantInt *CI = mdconst::dyn_extract<ConstantInt>(AlignMD->getOperand(0)); 3854 Assert(CI && CI->getType()->isIntegerTy(64), 3855 "align metadata value must be an i64!", &I); 3856 uint64_t Align = CI->getZExtValue(); 3857 Assert(isPowerOf2_64(Align), 3858 "align metadata value must be a power of 2!", &I); 3859 Assert(Align <= Value::MaximumAlignment, 3860 "alignment is larger that implementation defined limit", &I); 3861 } 3862 3863 if (MDNode *N = I.getDebugLoc().getAsMDNode()) { 3864 AssertDI(isa<DILocation>(N), "invalid !dbg metadata attachment", &I, N); 3865 visitMDNode(*N); 3866 } 3867 3868 if (auto *DII = dyn_cast<DbgInfoIntrinsic>(&I)) 3869 verifyFragmentExpression(*DII); 3870 3871 InstsInThisBlock.insert(&I); 3872 } 3873 3874 /// Allow intrinsics to be verified in different ways. 3875 void Verifier::visitIntrinsicCallSite(Intrinsic::ID ID, CallSite CS) { 3876 Function *IF = CS.getCalledFunction(); 3877 Assert(IF->isDeclaration(), "Intrinsic functions should never be defined!", 3878 IF); 3879 3880 // Verify that the intrinsic prototype lines up with what the .td files 3881 // describe. 3882 FunctionType *IFTy = IF->getFunctionType(); 3883 bool IsVarArg = IFTy->isVarArg(); 3884 3885 SmallVector<Intrinsic::IITDescriptor, 8> Table; 3886 getIntrinsicInfoTableEntries(ID, Table); 3887 ArrayRef<Intrinsic::IITDescriptor> TableRef = Table; 3888 3889 SmallVector<Type *, 4> ArgTys; 3890 Assert(!Intrinsic::matchIntrinsicType(IFTy->getReturnType(), 3891 TableRef, ArgTys), 3892 "Intrinsic has incorrect return type!", IF); 3893 for (unsigned i = 0, e = IFTy->getNumParams(); i != e; ++i) 3894 Assert(!Intrinsic::matchIntrinsicType(IFTy->getParamType(i), 3895 TableRef, ArgTys), 3896 "Intrinsic has incorrect argument type!", IF); 3897 3898 // Verify if the intrinsic call matches the vararg property. 3899 if (IsVarArg) 3900 Assert(!Intrinsic::matchIntrinsicVarArg(IsVarArg, TableRef), 3901 "Intrinsic was not defined with variable arguments!", IF); 3902 else 3903 Assert(!Intrinsic::matchIntrinsicVarArg(IsVarArg, TableRef), 3904 "Callsite was not defined with variable arguments!", IF); 3905 3906 // All descriptors should be absorbed by now. 3907 Assert(TableRef.empty(), "Intrinsic has too few arguments!", IF); 3908 3909 // Now that we have the intrinsic ID and the actual argument types (and we 3910 // know they are legal for the intrinsic!) get the intrinsic name through the 3911 // usual means. This allows us to verify the mangling of argument types into 3912 // the name. 3913 const std::string ExpectedName = Intrinsic::getName(ID, ArgTys); 3914 Assert(ExpectedName == IF->getName(), 3915 "Intrinsic name not mangled correctly for type arguments! " 3916 "Should be: " + 3917 ExpectedName, 3918 IF); 3919 3920 // If the intrinsic takes MDNode arguments, verify that they are either global 3921 // or are local to *this* function. 3922 for (Value *V : CS.args()) 3923 if (auto *MD = dyn_cast<MetadataAsValue>(V)) 3924 visitMetadataAsValue(*MD, CS.getCaller()); 3925 3926 switch (ID) { 3927 default: 3928 break; 3929 case Intrinsic::coro_id: { 3930 auto *InfoArg = CS.getArgOperand(3)->stripPointerCasts(); 3931 if (isa<ConstantPointerNull>(InfoArg)) 3932 break; 3933 auto *GV = dyn_cast<GlobalVariable>(InfoArg); 3934 Assert(GV && GV->isConstant() && GV->hasDefinitiveInitializer(), 3935 "info argument of llvm.coro.begin must refer to an initialized " 3936 "constant"); 3937 Constant *Init = GV->getInitializer(); 3938 Assert(isa<ConstantStruct>(Init) || isa<ConstantArray>(Init), 3939 "info argument of llvm.coro.begin must refer to either a struct or " 3940 "an array"); 3941 break; 3942 } 3943 case Intrinsic::ctlz: // llvm.ctlz 3944 case Intrinsic::cttz: // llvm.cttz 3945 Assert(isa<ConstantInt>(CS.getArgOperand(1)), 3946 "is_zero_undef argument of bit counting intrinsics must be a " 3947 "constant int", 3948 CS); 3949 break; 3950 case Intrinsic::experimental_constrained_fadd: 3951 case Intrinsic::experimental_constrained_fsub: 3952 case Intrinsic::experimental_constrained_fmul: 3953 case Intrinsic::experimental_constrained_fdiv: 3954 case Intrinsic::experimental_constrained_frem: 3955 visitConstrainedFPIntrinsic( 3956 cast<ConstrainedFPIntrinsic>(*CS.getInstruction())); 3957 break; 3958 case Intrinsic::dbg_declare: // llvm.dbg.declare 3959 Assert(isa<MetadataAsValue>(CS.getArgOperand(0)), 3960 "invalid llvm.dbg.declare intrinsic call 1", CS); 3961 visitDbgIntrinsic("declare", cast<DbgDeclareInst>(*CS.getInstruction())); 3962 break; 3963 case Intrinsic::dbg_value: // llvm.dbg.value 3964 visitDbgIntrinsic("value", cast<DbgValueInst>(*CS.getInstruction())); 3965 break; 3966 case Intrinsic::memcpy: 3967 case Intrinsic::memmove: 3968 case Intrinsic::memset: { 3969 ConstantInt *AlignCI = dyn_cast<ConstantInt>(CS.getArgOperand(3)); 3970 Assert(AlignCI, 3971 "alignment argument of memory intrinsics must be a constant int", 3972 CS); 3973 const APInt &AlignVal = AlignCI->getValue(); 3974 Assert(AlignCI->isZero() || AlignVal.isPowerOf2(), 3975 "alignment argument of memory intrinsics must be a power of 2", CS); 3976 Assert(isa<ConstantInt>(CS.getArgOperand(4)), 3977 "isvolatile argument of memory intrinsics must be a constant int", 3978 CS); 3979 break; 3980 } 3981 case Intrinsic::memcpy_element_atomic: { 3982 ConstantInt *ElementSizeCI = dyn_cast<ConstantInt>(CS.getArgOperand(3)); 3983 Assert(ElementSizeCI, "element size of the element-wise atomic memory " 3984 "intrinsic must be a constant int", 3985 CS); 3986 const APInt &ElementSizeVal = ElementSizeCI->getValue(); 3987 Assert(ElementSizeVal.isPowerOf2(), 3988 "element size of the element-wise atomic memory intrinsic " 3989 "must be a power of 2", 3990 CS); 3991 3992 auto IsValidAlignment = [&](uint64_t Alignment) { 3993 return isPowerOf2_64(Alignment) && ElementSizeVal.ule(Alignment); 3994 }; 3995 3996 uint64_t DstAlignment = CS.getParamAlignment(0), 3997 SrcAlignment = CS.getParamAlignment(1); 3998 3999 Assert(IsValidAlignment(DstAlignment), 4000 "incorrect alignment of the destination argument", 4001 CS); 4002 Assert(IsValidAlignment(SrcAlignment), 4003 "incorrect alignment of the source argument", 4004 CS); 4005 break; 4006 } 4007 case Intrinsic::gcroot: 4008 case Intrinsic::gcwrite: 4009 case Intrinsic::gcread: 4010 if (ID == Intrinsic::gcroot) { 4011 AllocaInst *AI = 4012 dyn_cast<AllocaInst>(CS.getArgOperand(0)->stripPointerCasts()); 4013 Assert(AI, "llvm.gcroot parameter #1 must be an alloca.", CS); 4014 Assert(isa<Constant>(CS.getArgOperand(1)), 4015 "llvm.gcroot parameter #2 must be a constant.", CS); 4016 if (!AI->getAllocatedType()->isPointerTy()) { 4017 Assert(!isa<ConstantPointerNull>(CS.getArgOperand(1)), 4018 "llvm.gcroot parameter #1 must either be a pointer alloca, " 4019 "or argument #2 must be a non-null constant.", 4020 CS); 4021 } 4022 } 4023 4024 Assert(CS.getParent()->getParent()->hasGC(), 4025 "Enclosing function does not use GC.", CS); 4026 break; 4027 case Intrinsic::init_trampoline: 4028 Assert(isa<Function>(CS.getArgOperand(1)->stripPointerCasts()), 4029 "llvm.init_trampoline parameter #2 must resolve to a function.", 4030 CS); 4031 break; 4032 case Intrinsic::prefetch: 4033 Assert(isa<ConstantInt>(CS.getArgOperand(1)) && 4034 isa<ConstantInt>(CS.getArgOperand(2)) && 4035 cast<ConstantInt>(CS.getArgOperand(1))->getZExtValue() < 2 && 4036 cast<ConstantInt>(CS.getArgOperand(2))->getZExtValue() < 4, 4037 "invalid arguments to llvm.prefetch", CS); 4038 break; 4039 case Intrinsic::stackprotector: 4040 Assert(isa<AllocaInst>(CS.getArgOperand(1)->stripPointerCasts()), 4041 "llvm.stackprotector parameter #2 must resolve to an alloca.", CS); 4042 break; 4043 case Intrinsic::lifetime_start: 4044 case Intrinsic::lifetime_end: 4045 case Intrinsic::invariant_start: 4046 Assert(isa<ConstantInt>(CS.getArgOperand(0)), 4047 "size argument of memory use markers must be a constant integer", 4048 CS); 4049 break; 4050 case Intrinsic::invariant_end: 4051 Assert(isa<ConstantInt>(CS.getArgOperand(1)), 4052 "llvm.invariant.end parameter #2 must be a constant integer", CS); 4053 break; 4054 4055 case Intrinsic::localescape: { 4056 BasicBlock *BB = CS.getParent(); 4057 Assert(BB == &BB->getParent()->front(), 4058 "llvm.localescape used outside of entry block", CS); 4059 Assert(!SawFrameEscape, 4060 "multiple calls to llvm.localescape in one function", CS); 4061 for (Value *Arg : CS.args()) { 4062 if (isa<ConstantPointerNull>(Arg)) 4063 continue; // Null values are allowed as placeholders. 4064 auto *AI = dyn_cast<AllocaInst>(Arg->stripPointerCasts()); 4065 Assert(AI && AI->isStaticAlloca(), 4066 "llvm.localescape only accepts static allocas", CS); 4067 } 4068 FrameEscapeInfo[BB->getParent()].first = CS.getNumArgOperands(); 4069 SawFrameEscape = true; 4070 break; 4071 } 4072 case Intrinsic::localrecover: { 4073 Value *FnArg = CS.getArgOperand(0)->stripPointerCasts(); 4074 Function *Fn = dyn_cast<Function>(FnArg); 4075 Assert(Fn && !Fn->isDeclaration(), 4076 "llvm.localrecover first " 4077 "argument must be function defined in this module", 4078 CS); 4079 auto *IdxArg = dyn_cast<ConstantInt>(CS.getArgOperand(2)); 4080 Assert(IdxArg, "idx argument of llvm.localrecover must be a constant int", 4081 CS); 4082 auto &Entry = FrameEscapeInfo[Fn]; 4083 Entry.second = unsigned( 4084 std::max(uint64_t(Entry.second), IdxArg->getLimitedValue(~0U) + 1)); 4085 break; 4086 } 4087 4088 case Intrinsic::experimental_gc_statepoint: 4089 Assert(!CS.isInlineAsm(), 4090 "gc.statepoint support for inline assembly unimplemented", CS); 4091 Assert(CS.getParent()->getParent()->hasGC(), 4092 "Enclosing function does not use GC.", CS); 4093 4094 verifyStatepoint(CS); 4095 break; 4096 case Intrinsic::experimental_gc_result: { 4097 Assert(CS.getParent()->getParent()->hasGC(), 4098 "Enclosing function does not use GC.", CS); 4099 // Are we tied to a statepoint properly? 4100 CallSite StatepointCS(CS.getArgOperand(0)); 4101 const Function *StatepointFn = 4102 StatepointCS.getInstruction() ? StatepointCS.getCalledFunction() : nullptr; 4103 Assert(StatepointFn && StatepointFn->isDeclaration() && 4104 StatepointFn->getIntrinsicID() == 4105 Intrinsic::experimental_gc_statepoint, 4106 "gc.result operand #1 must be from a statepoint", CS, 4107 CS.getArgOperand(0)); 4108 4109 // Assert that result type matches wrapped callee. 4110 const Value *Target = StatepointCS.getArgument(2); 4111 auto *PT = cast<PointerType>(Target->getType()); 4112 auto *TargetFuncType = cast<FunctionType>(PT->getElementType()); 4113 Assert(CS.getType() == TargetFuncType->getReturnType(), 4114 "gc.result result type does not match wrapped callee", CS); 4115 break; 4116 } 4117 case Intrinsic::experimental_gc_relocate: { 4118 Assert(CS.getNumArgOperands() == 3, "wrong number of arguments", CS); 4119 4120 Assert(isa<PointerType>(CS.getType()->getScalarType()), 4121 "gc.relocate must return a pointer or a vector of pointers", CS); 4122 4123 // Check that this relocate is correctly tied to the statepoint 4124 4125 // This is case for relocate on the unwinding path of an invoke statepoint 4126 if (LandingPadInst *LandingPad = 4127 dyn_cast<LandingPadInst>(CS.getArgOperand(0))) { 4128 4129 const BasicBlock *InvokeBB = 4130 LandingPad->getParent()->getUniquePredecessor(); 4131 4132 // Landingpad relocates should have only one predecessor with invoke 4133 // statepoint terminator 4134 Assert(InvokeBB, "safepoints should have unique landingpads", 4135 LandingPad->getParent()); 4136 Assert(InvokeBB->getTerminator(), "safepoint block should be well formed", 4137 InvokeBB); 4138 Assert(isStatepoint(InvokeBB->getTerminator()), 4139 "gc relocate should be linked to a statepoint", InvokeBB); 4140 } 4141 else { 4142 // In all other cases relocate should be tied to the statepoint directly. 4143 // This covers relocates on a normal return path of invoke statepoint and 4144 // relocates of a call statepoint. 4145 auto Token = CS.getArgOperand(0); 4146 Assert(isa<Instruction>(Token) && isStatepoint(cast<Instruction>(Token)), 4147 "gc relocate is incorrectly tied to the statepoint", CS, Token); 4148 } 4149 4150 // Verify rest of the relocate arguments. 4151 4152 ImmutableCallSite StatepointCS( 4153 cast<GCRelocateInst>(*CS.getInstruction()).getStatepoint()); 4154 4155 // Both the base and derived must be piped through the safepoint. 4156 Value* Base = CS.getArgOperand(1); 4157 Assert(isa<ConstantInt>(Base), 4158 "gc.relocate operand #2 must be integer offset", CS); 4159 4160 Value* Derived = CS.getArgOperand(2); 4161 Assert(isa<ConstantInt>(Derived), 4162 "gc.relocate operand #3 must be integer offset", CS); 4163 4164 const int BaseIndex = cast<ConstantInt>(Base)->getZExtValue(); 4165 const int DerivedIndex = cast<ConstantInt>(Derived)->getZExtValue(); 4166 // Check the bounds 4167 Assert(0 <= BaseIndex && BaseIndex < (int)StatepointCS.arg_size(), 4168 "gc.relocate: statepoint base index out of bounds", CS); 4169 Assert(0 <= DerivedIndex && DerivedIndex < (int)StatepointCS.arg_size(), 4170 "gc.relocate: statepoint derived index out of bounds", CS); 4171 4172 // Check that BaseIndex and DerivedIndex fall within the 'gc parameters' 4173 // section of the statepoint's argument. 4174 Assert(StatepointCS.arg_size() > 0, 4175 "gc.statepoint: insufficient arguments"); 4176 Assert(isa<ConstantInt>(StatepointCS.getArgument(3)), 4177 "gc.statement: number of call arguments must be constant integer"); 4178 const unsigned NumCallArgs = 4179 cast<ConstantInt>(StatepointCS.getArgument(3))->getZExtValue(); 4180 Assert(StatepointCS.arg_size() > NumCallArgs + 5, 4181 "gc.statepoint: mismatch in number of call arguments"); 4182 Assert(isa<ConstantInt>(StatepointCS.getArgument(NumCallArgs + 5)), 4183 "gc.statepoint: number of transition arguments must be " 4184 "a constant integer"); 4185 const int NumTransitionArgs = 4186 cast<ConstantInt>(StatepointCS.getArgument(NumCallArgs + 5)) 4187 ->getZExtValue(); 4188 const int DeoptArgsStart = 4 + NumCallArgs + 1 + NumTransitionArgs + 1; 4189 Assert(isa<ConstantInt>(StatepointCS.getArgument(DeoptArgsStart)), 4190 "gc.statepoint: number of deoptimization arguments must be " 4191 "a constant integer"); 4192 const int NumDeoptArgs = 4193 cast<ConstantInt>(StatepointCS.getArgument(DeoptArgsStart)) 4194 ->getZExtValue(); 4195 const int GCParamArgsStart = DeoptArgsStart + 1 + NumDeoptArgs; 4196 const int GCParamArgsEnd = StatepointCS.arg_size(); 4197 Assert(GCParamArgsStart <= BaseIndex && BaseIndex < GCParamArgsEnd, 4198 "gc.relocate: statepoint base index doesn't fall within the " 4199 "'gc parameters' section of the statepoint call", 4200 CS); 4201 Assert(GCParamArgsStart <= DerivedIndex && DerivedIndex < GCParamArgsEnd, 4202 "gc.relocate: statepoint derived index doesn't fall within the " 4203 "'gc parameters' section of the statepoint call", 4204 CS); 4205 4206 // Relocated value must be either a pointer type or vector-of-pointer type, 4207 // but gc_relocate does not need to return the same pointer type as the 4208 // relocated pointer. It can be casted to the correct type later if it's 4209 // desired. However, they must have the same address space and 'vectorness' 4210 GCRelocateInst &Relocate = cast<GCRelocateInst>(*CS.getInstruction()); 4211 Assert(Relocate.getDerivedPtr()->getType()->getScalarType()->isPointerTy(), 4212 "gc.relocate: relocated value must be a gc pointer", CS); 4213 4214 auto ResultType = CS.getType(); 4215 auto DerivedType = Relocate.getDerivedPtr()->getType(); 4216 Assert(ResultType->isVectorTy() == DerivedType->isVectorTy(), 4217 "gc.relocate: vector relocates to vector and pointer to pointer", 4218 CS); 4219 Assert( 4220 ResultType->getPointerAddressSpace() == 4221 DerivedType->getPointerAddressSpace(), 4222 "gc.relocate: relocating a pointer shouldn't change its address space", 4223 CS); 4224 break; 4225 } 4226 case Intrinsic::eh_exceptioncode: 4227 case Intrinsic::eh_exceptionpointer: { 4228 Assert(isa<CatchPadInst>(CS.getArgOperand(0)), 4229 "eh.exceptionpointer argument must be a catchpad", CS); 4230 break; 4231 } 4232 case Intrinsic::masked_load: { 4233 Assert(CS.getType()->isVectorTy(), "masked_load: must return a vector", CS); 4234 4235 Value *Ptr = CS.getArgOperand(0); 4236 //Value *Alignment = CS.getArgOperand(1); 4237 Value *Mask = CS.getArgOperand(2); 4238 Value *PassThru = CS.getArgOperand(3); 4239 Assert(Mask->getType()->isVectorTy(), 4240 "masked_load: mask must be vector", CS); 4241 4242 // DataTy is the overloaded type 4243 Type *DataTy = cast<PointerType>(Ptr->getType())->getElementType(); 4244 Assert(DataTy == CS.getType(), 4245 "masked_load: return must match pointer type", CS); 4246 Assert(PassThru->getType() == DataTy, 4247 "masked_load: pass through and data type must match", CS); 4248 Assert(Mask->getType()->getVectorNumElements() == 4249 DataTy->getVectorNumElements(), 4250 "masked_load: vector mask must be same length as data", CS); 4251 break; 4252 } 4253 case Intrinsic::masked_store: { 4254 Value *Val = CS.getArgOperand(0); 4255 Value *Ptr = CS.getArgOperand(1); 4256 //Value *Alignment = CS.getArgOperand(2); 4257 Value *Mask = CS.getArgOperand(3); 4258 Assert(Mask->getType()->isVectorTy(), 4259 "masked_store: mask must be vector", CS); 4260 4261 // DataTy is the overloaded type 4262 Type *DataTy = cast<PointerType>(Ptr->getType())->getElementType(); 4263 Assert(DataTy == Val->getType(), 4264 "masked_store: storee must match pointer type", CS); 4265 Assert(Mask->getType()->getVectorNumElements() == 4266 DataTy->getVectorNumElements(), 4267 "masked_store: vector mask must be same length as data", CS); 4268 break; 4269 } 4270 4271 case Intrinsic::experimental_guard: { 4272 Assert(CS.isCall(), "experimental_guard cannot be invoked", CS); 4273 Assert(CS.countOperandBundlesOfType(LLVMContext::OB_deopt) == 1, 4274 "experimental_guard must have exactly one " 4275 "\"deopt\" operand bundle"); 4276 break; 4277 } 4278 4279 case Intrinsic::experimental_deoptimize: { 4280 Assert(CS.isCall(), "experimental_deoptimize cannot be invoked", CS); 4281 Assert(CS.countOperandBundlesOfType(LLVMContext::OB_deopt) == 1, 4282 "experimental_deoptimize must have exactly one " 4283 "\"deopt\" operand bundle"); 4284 Assert(CS.getType() == CS.getInstruction()->getFunction()->getReturnType(), 4285 "experimental_deoptimize return type must match caller return type"); 4286 4287 if (CS.isCall()) { 4288 auto *DeoptCI = CS.getInstruction(); 4289 auto *RI = dyn_cast<ReturnInst>(DeoptCI->getNextNode()); 4290 Assert(RI, 4291 "calls to experimental_deoptimize must be followed by a return"); 4292 4293 if (!CS.getType()->isVoidTy() && RI) 4294 Assert(RI->getReturnValue() == DeoptCI, 4295 "calls to experimental_deoptimize must be followed by a return " 4296 "of the value computed by experimental_deoptimize"); 4297 } 4298 4299 break; 4300 } 4301 }; 4302 } 4303 4304 /// \brief Carefully grab the subprogram from a local scope. 4305 /// 4306 /// This carefully grabs the subprogram from a local scope, avoiding the 4307 /// built-in assertions that would typically fire. 4308 static DISubprogram *getSubprogram(Metadata *LocalScope) { 4309 if (!LocalScope) 4310 return nullptr; 4311 4312 if (auto *SP = dyn_cast<DISubprogram>(LocalScope)) 4313 return SP; 4314 4315 if (auto *LB = dyn_cast<DILexicalBlockBase>(LocalScope)) 4316 return getSubprogram(LB->getRawScope()); 4317 4318 // Just return null; broken scope chains are checked elsewhere. 4319 assert(!isa<DILocalScope>(LocalScope) && "Unknown type of local scope"); 4320 return nullptr; 4321 } 4322 4323 void Verifier::visitConstrainedFPIntrinsic(ConstrainedFPIntrinsic &FPI) { 4324 Assert(isa<MetadataAsValue>(FPI.getOperand(2)), 4325 "invalid rounding mode argument", &FPI); 4326 Assert(FPI.getRoundingMode() != ConstrainedFPIntrinsic::rmInvalid, 4327 "invalid rounding mode argument", &FPI); 4328 Assert(FPI.getExceptionBehavior() != ConstrainedFPIntrinsic::ebInvalid, 4329 "invalid exception behavior argument", &FPI); 4330 } 4331 4332 template <class DbgIntrinsicTy> 4333 void Verifier::visitDbgIntrinsic(StringRef Kind, DbgIntrinsicTy &DII) { 4334 auto *MD = cast<MetadataAsValue>(DII.getArgOperand(0))->getMetadata(); 4335 AssertDI(isa<ValueAsMetadata>(MD) || 4336 (isa<MDNode>(MD) && !cast<MDNode>(MD)->getNumOperands()), 4337 "invalid llvm.dbg." + Kind + " intrinsic address/value", &DII, MD); 4338 AssertDI(isa<DILocalVariable>(DII.getRawVariable()), 4339 "invalid llvm.dbg." + Kind + " intrinsic variable", &DII, 4340 DII.getRawVariable()); 4341 AssertDI(isa<DIExpression>(DII.getRawExpression()), 4342 "invalid llvm.dbg." + Kind + " intrinsic expression", &DII, 4343 DII.getRawExpression()); 4344 4345 // Ignore broken !dbg attachments; they're checked elsewhere. 4346 if (MDNode *N = DII.getDebugLoc().getAsMDNode()) 4347 if (!isa<DILocation>(N)) 4348 return; 4349 4350 BasicBlock *BB = DII.getParent(); 4351 Function *F = BB ? BB->getParent() : nullptr; 4352 4353 // The scopes for variables and !dbg attachments must agree. 4354 DILocalVariable *Var = DII.getVariable(); 4355 DILocation *Loc = DII.getDebugLoc(); 4356 Assert(Loc, "llvm.dbg." + Kind + " intrinsic requires a !dbg attachment", 4357 &DII, BB, F); 4358 4359 DISubprogram *VarSP = getSubprogram(Var->getRawScope()); 4360 DISubprogram *LocSP = getSubprogram(Loc->getRawScope()); 4361 if (!VarSP || !LocSP) 4362 return; // Broken scope chains are checked elsewhere. 4363 4364 AssertDI(VarSP == LocSP, "mismatched subprogram between llvm.dbg." + Kind + 4365 " variable and !dbg attachment", 4366 &DII, BB, F, Var, Var->getScope()->getSubprogram(), Loc, 4367 Loc->getScope()->getSubprogram()); 4368 4369 verifyFnArgs(DII); 4370 } 4371 4372 static uint64_t getVariableSize(const DILocalVariable &V) { 4373 // Be careful of broken types (checked elsewhere). 4374 const Metadata *RawType = V.getRawType(); 4375 while (RawType) { 4376 // Try to get the size directly. 4377 if (auto *T = dyn_cast<DIType>(RawType)) 4378 if (uint64_t Size = T->getSizeInBits()) 4379 return Size; 4380 4381 if (auto *DT = dyn_cast<DIDerivedType>(RawType)) { 4382 // Look at the base type. 4383 RawType = DT->getRawBaseType(); 4384 continue; 4385 } 4386 4387 // Missing type or size. 4388 break; 4389 } 4390 4391 // Fail gracefully. 4392 return 0; 4393 } 4394 4395 void Verifier::verifyFragmentExpression(const DbgInfoIntrinsic &I) { 4396 DILocalVariable *V; 4397 DIExpression *E; 4398 if (auto *DVI = dyn_cast<DbgValueInst>(&I)) { 4399 V = dyn_cast_or_null<DILocalVariable>(DVI->getRawVariable()); 4400 E = dyn_cast_or_null<DIExpression>(DVI->getRawExpression()); 4401 } else { 4402 auto *DDI = cast<DbgDeclareInst>(&I); 4403 V = dyn_cast_or_null<DILocalVariable>(DDI->getRawVariable()); 4404 E = dyn_cast_or_null<DIExpression>(DDI->getRawExpression()); 4405 } 4406 4407 // We don't know whether this intrinsic verified correctly. 4408 if (!V || !E || !E->isValid()) 4409 return; 4410 4411 // Nothing to do if this isn't a bit piece expression. 4412 auto Fragment = E->getFragmentInfo(); 4413 if (!Fragment) 4414 return; 4415 4416 // The frontend helps out GDB by emitting the members of local anonymous 4417 // unions as artificial local variables with shared storage. When SROA splits 4418 // the storage for artificial local variables that are smaller than the entire 4419 // union, the overhang piece will be outside of the allotted space for the 4420 // variable and this check fails. 4421 // FIXME: Remove this check as soon as clang stops doing this; it hides bugs. 4422 if (V->isArtificial()) 4423 return; 4424 4425 // If there's no size, the type is broken, but that should be checked 4426 // elsewhere. 4427 uint64_t VarSize = getVariableSize(*V); 4428 if (!VarSize) 4429 return; 4430 4431 unsigned FragSize = Fragment->SizeInBits; 4432 unsigned FragOffset = Fragment->OffsetInBits; 4433 AssertDI(FragSize + FragOffset <= VarSize, 4434 "fragment is larger than or outside of variable", &I, V, E); 4435 AssertDI(FragSize != VarSize, "fragment covers entire variable", &I, V, E); 4436 } 4437 4438 void Verifier::verifyFnArgs(const DbgInfoIntrinsic &I) { 4439 // This function does not take the scope of noninlined function arguments into 4440 // account. Don't run it if current function is nodebug, because it may 4441 // contain inlined debug intrinsics. 4442 if (!HasDebugInfo) 4443 return; 4444 4445 DILocalVariable *Var; 4446 if (auto *DV = dyn_cast<DbgValueInst>(&I)) { 4447 // For performance reasons only check non-inlined ones. 4448 if (DV->getDebugLoc()->getInlinedAt()) 4449 return; 4450 Var = DV->getVariable(); 4451 } else { 4452 auto *DD = cast<DbgDeclareInst>(&I); 4453 if (DD->getDebugLoc()->getInlinedAt()) 4454 return; 4455 Var = DD->getVariable(); 4456 } 4457 AssertDI(Var, "dbg intrinsic without variable"); 4458 4459 unsigned ArgNo = Var->getArg(); 4460 if (!ArgNo) 4461 return; 4462 4463 // Verify there are no duplicate function argument debug info entries. 4464 // These will cause hard-to-debug assertions in the DWARF backend. 4465 if (DebugFnArgs.size() < ArgNo) 4466 DebugFnArgs.resize(ArgNo, nullptr); 4467 4468 auto *Prev = DebugFnArgs[ArgNo - 1]; 4469 DebugFnArgs[ArgNo - 1] = Var; 4470 AssertDI(!Prev || (Prev == Var), "conflicting debug info for argument", &I, 4471 Prev, Var); 4472 } 4473 4474 void Verifier::verifyCompileUnits() { 4475 auto *CUs = M.getNamedMetadata("llvm.dbg.cu"); 4476 SmallPtrSet<const Metadata *, 2> Listed; 4477 if (CUs) 4478 Listed.insert(CUs->op_begin(), CUs->op_end()); 4479 for (auto *CU : CUVisited) 4480 AssertDI(Listed.count(CU), "DICompileUnit not listed in llvm.dbg.cu", CU); 4481 CUVisited.clear(); 4482 } 4483 4484 void Verifier::verifyDeoptimizeCallingConvs() { 4485 if (DeoptimizeDeclarations.empty()) 4486 return; 4487 4488 const Function *First = DeoptimizeDeclarations[0]; 4489 for (auto *F : makeArrayRef(DeoptimizeDeclarations).slice(1)) { 4490 Assert(First->getCallingConv() == F->getCallingConv(), 4491 "All llvm.experimental.deoptimize declarations must have the same " 4492 "calling convention", 4493 First, F); 4494 } 4495 } 4496 4497 //===----------------------------------------------------------------------===// 4498 // Implement the public interfaces to this file... 4499 //===----------------------------------------------------------------------===// 4500 4501 bool llvm::verifyFunction(const Function &f, raw_ostream *OS) { 4502 Function &F = const_cast<Function &>(f); 4503 4504 // Don't use a raw_null_ostream. Printing IR is expensive. 4505 Verifier V(OS, /*ShouldTreatBrokenDebugInfoAsError=*/true, *f.getParent()); 4506 4507 // Note that this function's return value is inverted from what you would 4508 // expect of a function called "verify". 4509 return !V.verify(F); 4510 } 4511 4512 bool llvm::verifyModule(const Module &M, raw_ostream *OS, 4513 bool *BrokenDebugInfo) { 4514 // Don't use a raw_null_ostream. Printing IR is expensive. 4515 Verifier V(OS, /*ShouldTreatBrokenDebugInfoAsError=*/!BrokenDebugInfo, M); 4516 4517 bool Broken = false; 4518 for (const Function &F : M) 4519 Broken |= !V.verify(F); 4520 4521 Broken |= !V.verify(); 4522 if (BrokenDebugInfo) 4523 *BrokenDebugInfo = V.hasBrokenDebugInfo(); 4524 // Note that this function's return value is inverted from what you would 4525 // expect of a function called "verify". 4526 return Broken; 4527 } 4528 4529 namespace { 4530 4531 struct VerifierLegacyPass : public FunctionPass { 4532 static char ID; 4533 4534 std::unique_ptr<Verifier> V; 4535 bool FatalErrors = true; 4536 4537 VerifierLegacyPass() : FunctionPass(ID) { 4538 initializeVerifierLegacyPassPass(*PassRegistry::getPassRegistry()); 4539 } 4540 explicit VerifierLegacyPass(bool FatalErrors) 4541 : FunctionPass(ID), 4542 FatalErrors(FatalErrors) { 4543 initializeVerifierLegacyPassPass(*PassRegistry::getPassRegistry()); 4544 } 4545 4546 bool doInitialization(Module &M) override { 4547 V = llvm::make_unique<Verifier>( 4548 &dbgs(), /*ShouldTreatBrokenDebugInfoAsError=*/false, M); 4549 return false; 4550 } 4551 4552 bool runOnFunction(Function &F) override { 4553 if (!V->verify(F) && FatalErrors) 4554 report_fatal_error("Broken function found, compilation aborted!"); 4555 4556 return false; 4557 } 4558 4559 bool doFinalization(Module &M) override { 4560 bool HasErrors = false; 4561 for (Function &F : M) 4562 if (F.isDeclaration()) 4563 HasErrors |= !V->verify(F); 4564 4565 HasErrors |= !V->verify(); 4566 if (FatalErrors) { 4567 if (HasErrors) 4568 report_fatal_error("Broken module found, compilation aborted!"); 4569 assert(!V->hasBrokenDebugInfo() && "Module contains invalid debug info"); 4570 } 4571 4572 // Strip broken debug info. 4573 if (V->hasBrokenDebugInfo()) { 4574 DiagnosticInfoIgnoringInvalidDebugMetadata DiagInvalid(M); 4575 M.getContext().diagnose(DiagInvalid); 4576 if (!StripDebugInfo(M)) 4577 report_fatal_error("Failed to strip malformed debug info"); 4578 } 4579 return false; 4580 } 4581 4582 void getAnalysisUsage(AnalysisUsage &AU) const override { 4583 AU.setPreservesAll(); 4584 } 4585 }; 4586 4587 } // end anonymous namespace 4588 4589 /// Helper to issue failure from the TBAA verification 4590 template <typename... Tys> void TBAAVerifier::CheckFailed(Tys &&... Args) { 4591 if (Diagnostic) 4592 return Diagnostic->CheckFailed(Args...); 4593 } 4594 4595 #define AssertTBAA(C, ...) \ 4596 do { \ 4597 if (!(C)) { \ 4598 CheckFailed(__VA_ARGS__); \ 4599 return false; \ 4600 } \ 4601 } while (false) 4602 4603 /// Verify that \p BaseNode can be used as the "base type" in the struct-path 4604 /// TBAA scheme. This means \p BaseNode is either a scalar node, or a 4605 /// struct-type node describing an aggregate data structure (like a struct). 4606 TBAAVerifier::TBAABaseNodeSummary 4607 TBAAVerifier::verifyTBAABaseNode(Instruction &I, const MDNode *BaseNode) { 4608 if (BaseNode->getNumOperands() < 2) { 4609 CheckFailed("Base nodes must have at least two operands", &I, BaseNode); 4610 return {true, ~0u}; 4611 } 4612 4613 auto Itr = TBAABaseNodes.find(BaseNode); 4614 if (Itr != TBAABaseNodes.end()) 4615 return Itr->second; 4616 4617 auto Result = verifyTBAABaseNodeImpl(I, BaseNode); 4618 auto InsertResult = TBAABaseNodes.insert({BaseNode, Result}); 4619 (void)InsertResult; 4620 assert(InsertResult.second && "We just checked!"); 4621 return Result; 4622 } 4623 4624 TBAAVerifier::TBAABaseNodeSummary 4625 TBAAVerifier::verifyTBAABaseNodeImpl(Instruction &I, const MDNode *BaseNode) { 4626 const TBAAVerifier::TBAABaseNodeSummary InvalidNode = {true, ~0u}; 4627 4628 if (BaseNode->getNumOperands() == 2) { 4629 // Scalar nodes can only be accessed at offset 0. 4630 return isValidScalarTBAANode(BaseNode) 4631 ? TBAAVerifier::TBAABaseNodeSummary({false, 0}) 4632 : InvalidNode; 4633 } 4634 4635 if (BaseNode->getNumOperands() % 2 != 1) { 4636 CheckFailed("Struct tag nodes must have an odd number of operands!", 4637 BaseNode); 4638 return InvalidNode; 4639 } 4640 4641 if (!isa<MDString>(BaseNode->getOperand(0))) { 4642 CheckFailed("Struct tag nodes have a string as their first operand", 4643 BaseNode); 4644 return InvalidNode; 4645 } 4646 4647 bool Failed = false; 4648 4649 Optional<APInt> PrevOffset; 4650 unsigned BitWidth = ~0u; 4651 4652 // We've already checked that BaseNode is not a degenerate root node with one 4653 // operand in \c verifyTBAABaseNode, so this loop should run at least once. 4654 for (unsigned Idx = 1; Idx < BaseNode->getNumOperands(); Idx += 2) { 4655 const MDOperand &FieldTy = BaseNode->getOperand(Idx); 4656 const MDOperand &FieldOffset = BaseNode->getOperand(Idx + 1); 4657 if (!isa<MDNode>(FieldTy)) { 4658 CheckFailed("Incorrect field entry in struct type node!", &I, BaseNode); 4659 Failed = true; 4660 continue; 4661 } 4662 4663 auto *OffsetEntryCI = 4664 mdconst::dyn_extract_or_null<ConstantInt>(FieldOffset); 4665 if (!OffsetEntryCI) { 4666 CheckFailed("Offset entries must be constants!", &I, BaseNode); 4667 Failed = true; 4668 continue; 4669 } 4670 4671 if (BitWidth == ~0u) 4672 BitWidth = OffsetEntryCI->getBitWidth(); 4673 4674 if (OffsetEntryCI->getBitWidth() != BitWidth) { 4675 CheckFailed( 4676 "Bitwidth between the offsets and struct type entries must match", &I, 4677 BaseNode); 4678 Failed = true; 4679 continue; 4680 } 4681 4682 // NB! As far as I can tell, we generate a non-strictly increasing offset 4683 // sequence only from structs that have zero size bit fields. When 4684 // recursing into a contained struct in \c getFieldNodeFromTBAABaseNode we 4685 // pick the field lexically the latest in struct type metadata node. This 4686 // mirrors the actual behavior of the alias analysis implementation. 4687 bool IsAscending = 4688 !PrevOffset || PrevOffset->ule(OffsetEntryCI->getValue()); 4689 4690 if (!IsAscending) { 4691 CheckFailed("Offsets must be increasing!", &I, BaseNode); 4692 Failed = true; 4693 } 4694 4695 PrevOffset = OffsetEntryCI->getValue(); 4696 } 4697 4698 return Failed ? InvalidNode 4699 : TBAAVerifier::TBAABaseNodeSummary(false, BitWidth); 4700 } 4701 4702 static bool IsRootTBAANode(const MDNode *MD) { 4703 return MD->getNumOperands() < 2; 4704 } 4705 4706 static bool IsScalarTBAANodeImpl(const MDNode *MD, 4707 SmallPtrSetImpl<const MDNode *> &Visited) { 4708 if (MD->getNumOperands() != 2 && MD->getNumOperands() != 3) 4709 return false; 4710 4711 if (!isa<MDString>(MD->getOperand(0))) 4712 return false; 4713 4714 if (MD->getNumOperands() == 3) { 4715 auto *Offset = mdconst::dyn_extract<ConstantInt>(MD->getOperand(2)); 4716 if (!(Offset && Offset->isZero() && isa<MDString>(MD->getOperand(0)))) 4717 return false; 4718 } 4719 4720 auto *Parent = dyn_cast_or_null<MDNode>(MD->getOperand(1)); 4721 return Parent && Visited.insert(Parent).second && 4722 (IsRootTBAANode(Parent) || IsScalarTBAANodeImpl(Parent, Visited)); 4723 } 4724 4725 bool TBAAVerifier::isValidScalarTBAANode(const MDNode *MD) { 4726 auto ResultIt = TBAAScalarNodes.find(MD); 4727 if (ResultIt != TBAAScalarNodes.end()) 4728 return ResultIt->second; 4729 4730 SmallPtrSet<const MDNode *, 4> Visited; 4731 bool Result = IsScalarTBAANodeImpl(MD, Visited); 4732 auto InsertResult = TBAAScalarNodes.insert({MD, Result}); 4733 (void)InsertResult; 4734 assert(InsertResult.second && "Just checked!"); 4735 4736 return Result; 4737 } 4738 4739 /// Returns the field node at the offset \p Offset in \p BaseNode. Update \p 4740 /// Offset in place to be the offset within the field node returned. 4741 /// 4742 /// We assume we've okayed \p BaseNode via \c verifyTBAABaseNode. 4743 MDNode *TBAAVerifier::getFieldNodeFromTBAABaseNode(Instruction &I, 4744 const MDNode *BaseNode, 4745 APInt &Offset) { 4746 assert(BaseNode->getNumOperands() >= 2 && "Invalid base node!"); 4747 4748 // Scalar nodes have only one possible "field" -- their parent in the access 4749 // hierarchy. Offset must be zero at this point, but our caller is supposed 4750 // to Assert that. 4751 if (BaseNode->getNumOperands() == 2) 4752 return cast<MDNode>(BaseNode->getOperand(1)); 4753 4754 for (unsigned Idx = 1; Idx < BaseNode->getNumOperands(); Idx += 2) { 4755 auto *OffsetEntryCI = 4756 mdconst::extract<ConstantInt>(BaseNode->getOperand(Idx + 1)); 4757 if (OffsetEntryCI->getValue().ugt(Offset)) { 4758 if (Idx == 1) { 4759 CheckFailed("Could not find TBAA parent in struct type node", &I, 4760 BaseNode, &Offset); 4761 return nullptr; 4762 } 4763 4764 auto *PrevOffsetEntryCI = 4765 mdconst::extract<ConstantInt>(BaseNode->getOperand(Idx - 1)); 4766 Offset -= PrevOffsetEntryCI->getValue(); 4767 return cast<MDNode>(BaseNode->getOperand(Idx - 2)); 4768 } 4769 } 4770 4771 auto *LastOffsetEntryCI = mdconst::extract<ConstantInt>( 4772 BaseNode->getOperand(BaseNode->getNumOperands() - 1)); 4773 4774 Offset -= LastOffsetEntryCI->getValue(); 4775 return cast<MDNode>(BaseNode->getOperand(BaseNode->getNumOperands() - 2)); 4776 } 4777 4778 bool TBAAVerifier::visitTBAAMetadata(Instruction &I, const MDNode *MD) { 4779 AssertTBAA(isa<LoadInst>(I) || isa<StoreInst>(I) || isa<CallInst>(I) || 4780 isa<VAArgInst>(I) || isa<AtomicRMWInst>(I) || 4781 isa<AtomicCmpXchgInst>(I), 4782 "TBAA is only for loads, stores and calls!", &I); 4783 4784 bool IsStructPathTBAA = 4785 isa<MDNode>(MD->getOperand(0)) && MD->getNumOperands() >= 3; 4786 4787 AssertTBAA( 4788 IsStructPathTBAA, 4789 "Old-style TBAA is no longer allowed, use struct-path TBAA instead", &I); 4790 4791 AssertTBAA(MD->getNumOperands() < 5, 4792 "Struct tag metadata must have either 3 or 4 operands", &I, MD); 4793 4794 MDNode *BaseNode = dyn_cast_or_null<MDNode>(MD->getOperand(0)); 4795 MDNode *AccessType = dyn_cast_or_null<MDNode>(MD->getOperand(1)); 4796 4797 if (MD->getNumOperands() == 4) { 4798 auto *IsImmutableCI = 4799 mdconst::dyn_extract_or_null<ConstantInt>(MD->getOperand(3)); 4800 AssertTBAA(IsImmutableCI, 4801 "Immutability tag on struct tag metadata must be a constant", &I, 4802 MD); 4803 AssertTBAA( 4804 IsImmutableCI->isZero() || IsImmutableCI->isOne(), 4805 "Immutability part of the struct tag metadata must be either 0 or 1", 4806 &I, MD); 4807 } 4808 4809 AssertTBAA(BaseNode && AccessType, 4810 "Malformed struct tag metadata: base and access-type " 4811 "should be non-null and point to Metadata nodes", 4812 &I, MD, BaseNode, AccessType); 4813 4814 AssertTBAA(isValidScalarTBAANode(AccessType), 4815 "Access type node must be a valid scalar type", &I, MD, 4816 AccessType); 4817 4818 auto *OffsetCI = mdconst::dyn_extract_or_null<ConstantInt>(MD->getOperand(2)); 4819 AssertTBAA(OffsetCI, "Offset must be constant integer", &I, MD); 4820 4821 APInt Offset = OffsetCI->getValue(); 4822 bool SeenAccessTypeInPath = false; 4823 4824 SmallPtrSet<MDNode *, 4> StructPath; 4825 4826 for (/* empty */; BaseNode && !IsRootTBAANode(BaseNode); 4827 BaseNode = getFieldNodeFromTBAABaseNode(I, BaseNode, Offset)) { 4828 if (!StructPath.insert(BaseNode).second) { 4829 CheckFailed("Cycle detected in struct path", &I, MD); 4830 return false; 4831 } 4832 4833 bool Invalid; 4834 unsigned BaseNodeBitWidth; 4835 std::tie(Invalid, BaseNodeBitWidth) = verifyTBAABaseNode(I, BaseNode); 4836 4837 // If the base node is invalid in itself, then we've already printed all the 4838 // errors we wanted to print. 4839 if (Invalid) 4840 return false; 4841 4842 SeenAccessTypeInPath |= BaseNode == AccessType; 4843 4844 if (isValidScalarTBAANode(BaseNode) || BaseNode == AccessType) 4845 AssertTBAA(Offset == 0, "Offset not zero at the point of scalar access", 4846 &I, MD, &Offset); 4847 4848 AssertTBAA(BaseNodeBitWidth == Offset.getBitWidth() || 4849 (BaseNodeBitWidth == 0 && Offset == 0), 4850 "Access bit-width not the same as description bit-width", &I, MD, 4851 BaseNodeBitWidth, Offset.getBitWidth()); 4852 } 4853 4854 AssertTBAA(SeenAccessTypeInPath, "Did not see access type in access path!", 4855 &I, MD); 4856 return true; 4857 } 4858 4859 char VerifierLegacyPass::ID = 0; 4860 INITIALIZE_PASS(VerifierLegacyPass, "verify", "Module Verifier", false, false) 4861 4862 FunctionPass *llvm::createVerifierPass(bool FatalErrors) { 4863 return new VerifierLegacyPass(FatalErrors); 4864 } 4865 4866 AnalysisKey VerifierAnalysis::Key; 4867 VerifierAnalysis::Result VerifierAnalysis::run(Module &M, 4868 ModuleAnalysisManager &) { 4869 Result Res; 4870 Res.IRBroken = llvm::verifyModule(M, &dbgs(), &Res.DebugInfoBroken); 4871 return Res; 4872 } 4873 4874 VerifierAnalysis::Result VerifierAnalysis::run(Function &F, 4875 FunctionAnalysisManager &) { 4876 return { llvm::verifyFunction(F, &dbgs()), false }; 4877 } 4878 4879 PreservedAnalyses VerifierPass::run(Module &M, ModuleAnalysisManager &AM) { 4880 auto Res = AM.getResult<VerifierAnalysis>(M); 4881 if (FatalErrors) { 4882 if (Res.IRBroken) 4883 report_fatal_error("Broken module found, compilation aborted!"); 4884 assert(!Res.DebugInfoBroken && "Module contains invalid debug info"); 4885 } 4886 4887 // Strip broken debug info. 4888 if (Res.DebugInfoBroken) { 4889 DiagnosticInfoIgnoringInvalidDebugMetadata DiagInvalid(M); 4890 M.getContext().diagnose(DiagInvalid); 4891 if (!StripDebugInfo(M)) 4892 report_fatal_error("Failed to strip malformed debug info"); 4893 } 4894 return PreservedAnalyses::all(); 4895 } 4896 4897 PreservedAnalyses VerifierPass::run(Function &F, FunctionAnalysisManager &AM) { 4898 auto res = AM.getResult<VerifierAnalysis>(F); 4899 if (res.IRBroken && FatalErrors) 4900 report_fatal_error("Broken function found, compilation aborted!"); 4901 4902 return PreservedAnalyses::all(); 4903 } 4904