BugReporter.cpp revision 3a46f5fd1709f6df03bbb8b0abf84052dc0f39ff
1// BugReporter.cpp - Generate PathDiagnostics for Bugs ------------*- C++ -*--// 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 BugReporter, a utility class for generating 11// PathDiagnostics. 12// 13//===----------------------------------------------------------------------===// 14 15#include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h" 16#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h" 17#include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h" 18#include "clang/AST/ASTContext.h" 19#include "clang/Analysis/CFG.h" 20#include "clang/AST/DeclObjC.h" 21#include "clang/AST/Expr.h" 22#include "clang/AST/ParentMap.h" 23#include "clang/AST/StmtObjC.h" 24#include "clang/Basic/SourceManager.h" 25#include "clang/Analysis/ProgramPoint.h" 26#include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h" 27#include "llvm/Support/raw_ostream.h" 28#include "llvm/ADT/DenseMap.h" 29#include "llvm/ADT/SmallString.h" 30#include "llvm/ADT/STLExtras.h" 31#include "llvm/ADT/OwningPtr.h" 32#include "llvm/ADT/IntrusiveRefCntPtr.h" 33#include <queue> 34 35using namespace clang; 36using namespace ento; 37 38BugReporterVisitor::~BugReporterVisitor() {} 39 40void BugReporterContext::anchor() {} 41 42//===----------------------------------------------------------------------===// 43// Helper routines for walking the ExplodedGraph and fetching statements. 44//===----------------------------------------------------------------------===// 45 46static inline const Stmt *GetStmt(const ProgramPoint &P) { 47 if (const StmtPoint* SP = dyn_cast<StmtPoint>(&P)) 48 return SP->getStmt(); 49 else if (const BlockEdge *BE = dyn_cast<BlockEdge>(&P)) 50 return BE->getSrc()->getTerminator(); 51 else if (const CallEnter *CE = dyn_cast<CallEnter>(&P)) 52 return CE->getCallExpr(); 53 else if (const CallExitEnd *CEE = dyn_cast<CallExitEnd>(&P)) 54 return CEE->getCalleeContext()->getCallSite(); 55 56 return 0; 57} 58 59static inline const ExplodedNode* 60GetPredecessorNode(const ExplodedNode *N) { 61 return N->pred_empty() ? NULL : *(N->pred_begin()); 62} 63 64static inline const ExplodedNode* 65GetSuccessorNode(const ExplodedNode *N) { 66 return N->succ_empty() ? NULL : *(N->succ_begin()); 67} 68 69static const Stmt *GetPreviousStmt(const ExplodedNode *N) { 70 for (N = GetPredecessorNode(N); N; N = GetPredecessorNode(N)) 71 if (const Stmt *S = GetStmt(N->getLocation())) 72 return S; 73 74 return 0; 75} 76 77static const Stmt *GetNextStmt(const ExplodedNode *N) { 78 for (N = GetSuccessorNode(N); N; N = GetSuccessorNode(N)) 79 if (const Stmt *S = GetStmt(N->getLocation())) { 80 // Check if the statement is '?' or '&&'/'||'. These are "merges", 81 // not actual statement points. 82 switch (S->getStmtClass()) { 83 case Stmt::ChooseExprClass: 84 case Stmt::BinaryConditionalOperatorClass: continue; 85 case Stmt::ConditionalOperatorClass: continue; 86 case Stmt::BinaryOperatorClass: { 87 BinaryOperatorKind Op = cast<BinaryOperator>(S)->getOpcode(); 88 if (Op == BO_LAnd || Op == BO_LOr) 89 continue; 90 break; 91 } 92 default: 93 break; 94 } 95 return S; 96 } 97 98 return 0; 99} 100 101static inline const Stmt* 102GetCurrentOrPreviousStmt(const ExplodedNode *N) { 103 if (const Stmt *S = GetStmt(N->getLocation())) 104 return S; 105 106 return GetPreviousStmt(N); 107} 108 109static inline const Stmt* 110GetCurrentOrNextStmt(const ExplodedNode *N) { 111 if (const Stmt *S = GetStmt(N->getLocation())) 112 return S; 113 114 return GetNextStmt(N); 115} 116 117//===----------------------------------------------------------------------===// 118// Diagnostic cleanup. 119//===----------------------------------------------------------------------===// 120 121/// Recursively scan through a path and prune out calls and macros pieces 122/// that aren't needed. Return true if afterwards the path contains 123/// "interesting stuff" which means it should be pruned from the parent path. 124bool BugReporter::RemoveUneededCalls(PathPieces &pieces, BugReport *R) { 125 bool containsSomethingInteresting = false; 126 const unsigned N = pieces.size(); 127 128 for (unsigned i = 0 ; i < N ; ++i) { 129 // Remove the front piece from the path. If it is still something we 130 // want to keep once we are done, we will push it back on the end. 131 IntrusiveRefCntPtr<PathDiagnosticPiece> piece(pieces.front()); 132 pieces.pop_front(); 133 134 switch (piece->getKind()) { 135 case PathDiagnosticPiece::Call: { 136 PathDiagnosticCallPiece *call = cast<PathDiagnosticCallPiece>(piece); 137 // Check if the location context is interesting. 138 assert(LocationContextMap.count(call)); 139 if (R->isInteresting(LocationContextMap[call])) { 140 containsSomethingInteresting = true; 141 break; 142 } 143 // Recursively clean out the subclass. Keep this call around if 144 // it contains any informative diagnostics. 145 if (!RemoveUneededCalls(call->path, R)) 146 continue; 147 containsSomethingInteresting = true; 148 break; 149 } 150 case PathDiagnosticPiece::Macro: { 151 PathDiagnosticMacroPiece *macro = cast<PathDiagnosticMacroPiece>(piece); 152 if (!RemoveUneededCalls(macro->subPieces, R)) 153 continue; 154 containsSomethingInteresting = true; 155 break; 156 } 157 case PathDiagnosticPiece::Event: { 158 PathDiagnosticEventPiece *event = cast<PathDiagnosticEventPiece>(piece); 159 // We never throw away an event, but we do throw it away wholesale 160 // as part of a path if we throw the entire path away. 161 if (event->isPrunable()) 162 continue; 163 containsSomethingInteresting = true; 164 break; 165 } 166 case PathDiagnosticPiece::ControlFlow: 167 break; 168 } 169 170 pieces.push_back(piece); 171 } 172 173 return containsSomethingInteresting; 174} 175 176//===----------------------------------------------------------------------===// 177// PathDiagnosticBuilder and its associated routines and helper objects. 178//===----------------------------------------------------------------------===// 179 180typedef llvm::DenseMap<const ExplodedNode*, 181const ExplodedNode*> NodeBackMap; 182 183namespace { 184class NodeMapClosure : public BugReport::NodeResolver { 185 NodeBackMap& M; 186public: 187 NodeMapClosure(NodeBackMap *m) : M(*m) {} 188 ~NodeMapClosure() {} 189 190 const ExplodedNode *getOriginalNode(const ExplodedNode *N) { 191 NodeBackMap::iterator I = M.find(N); 192 return I == M.end() ? 0 : I->second; 193 } 194}; 195 196class PathDiagnosticBuilder : public BugReporterContext { 197 BugReport *R; 198 PathDiagnosticConsumer *PDC; 199 OwningPtr<ParentMap> PM; 200 NodeMapClosure NMC; 201public: 202 const LocationContext *LC; 203 204 PathDiagnosticBuilder(GRBugReporter &br, 205 BugReport *r, NodeBackMap *Backmap, 206 PathDiagnosticConsumer *pdc) 207 : BugReporterContext(br), 208 R(r), PDC(pdc), NMC(Backmap), LC(r->getErrorNode()->getLocationContext()) 209 {} 210 211 PathDiagnosticLocation ExecutionContinues(const ExplodedNode *N); 212 213 PathDiagnosticLocation ExecutionContinues(llvm::raw_string_ostream &os, 214 const ExplodedNode *N); 215 216 BugReport *getBugReport() { return R; } 217 218 Decl const &getCodeDecl() { return R->getErrorNode()->getCodeDecl(); } 219 220 ParentMap& getParentMap() { return LC->getParentMap(); } 221 222 const Stmt *getParent(const Stmt *S) { 223 return getParentMap().getParent(S); 224 } 225 226 virtual NodeMapClosure& getNodeResolver() { return NMC; } 227 228 PathDiagnosticLocation getEnclosingStmtLocation(const Stmt *S); 229 230 PathDiagnosticConsumer::PathGenerationScheme getGenerationScheme() const { 231 return PDC ? PDC->getGenerationScheme() : PathDiagnosticConsumer::Extensive; 232 } 233 234 bool supportsLogicalOpControlFlow() const { 235 return PDC ? PDC->supportsLogicalOpControlFlow() : true; 236 } 237}; 238} // end anonymous namespace 239 240PathDiagnosticLocation 241PathDiagnosticBuilder::ExecutionContinues(const ExplodedNode *N) { 242 if (const Stmt *S = GetNextStmt(N)) 243 return PathDiagnosticLocation(S, getSourceManager(), LC); 244 245 return PathDiagnosticLocation::createDeclEnd(N->getLocationContext(), 246 getSourceManager()); 247} 248 249PathDiagnosticLocation 250PathDiagnosticBuilder::ExecutionContinues(llvm::raw_string_ostream &os, 251 const ExplodedNode *N) { 252 253 // Slow, but probably doesn't matter. 254 if (os.str().empty()) 255 os << ' '; 256 257 const PathDiagnosticLocation &Loc = ExecutionContinues(N); 258 259 if (Loc.asStmt()) 260 os << "Execution continues on line " 261 << getSourceManager().getExpansionLineNumber(Loc.asLocation()) 262 << '.'; 263 else { 264 os << "Execution jumps to the end of the "; 265 const Decl *D = N->getLocationContext()->getDecl(); 266 if (isa<ObjCMethodDecl>(D)) 267 os << "method"; 268 else if (isa<FunctionDecl>(D)) 269 os << "function"; 270 else { 271 assert(isa<BlockDecl>(D)); 272 os << "anonymous block"; 273 } 274 os << '.'; 275 } 276 277 return Loc; 278} 279 280static bool IsNested(const Stmt *S, ParentMap &PM) { 281 if (isa<Expr>(S) && PM.isConsumedExpr(cast<Expr>(S))) 282 return true; 283 284 const Stmt *Parent = PM.getParentIgnoreParens(S); 285 286 if (Parent) 287 switch (Parent->getStmtClass()) { 288 case Stmt::ForStmtClass: 289 case Stmt::DoStmtClass: 290 case Stmt::WhileStmtClass: 291 return true; 292 default: 293 break; 294 } 295 296 return false; 297} 298 299PathDiagnosticLocation 300PathDiagnosticBuilder::getEnclosingStmtLocation(const Stmt *S) { 301 assert(S && "Null Stmt *passed to getEnclosingStmtLocation"); 302 ParentMap &P = getParentMap(); 303 SourceManager &SMgr = getSourceManager(); 304 305 while (IsNested(S, P)) { 306 const Stmt *Parent = P.getParentIgnoreParens(S); 307 308 if (!Parent) 309 break; 310 311 switch (Parent->getStmtClass()) { 312 case Stmt::BinaryOperatorClass: { 313 const BinaryOperator *B = cast<BinaryOperator>(Parent); 314 if (B->isLogicalOp()) 315 return PathDiagnosticLocation(S, SMgr, LC); 316 break; 317 } 318 case Stmt::CompoundStmtClass: 319 case Stmt::StmtExprClass: 320 return PathDiagnosticLocation(S, SMgr, LC); 321 case Stmt::ChooseExprClass: 322 // Similar to '?' if we are referring to condition, just have the edge 323 // point to the entire choose expression. 324 if (cast<ChooseExpr>(Parent)->getCond() == S) 325 return PathDiagnosticLocation(Parent, SMgr, LC); 326 else 327 return PathDiagnosticLocation(S, SMgr, LC); 328 case Stmt::BinaryConditionalOperatorClass: 329 case Stmt::ConditionalOperatorClass: 330 // For '?', if we are referring to condition, just have the edge point 331 // to the entire '?' expression. 332 if (cast<AbstractConditionalOperator>(Parent)->getCond() == S) 333 return PathDiagnosticLocation(Parent, SMgr, LC); 334 else 335 return PathDiagnosticLocation(S, SMgr, LC); 336 case Stmt::DoStmtClass: 337 return PathDiagnosticLocation(S, SMgr, LC); 338 case Stmt::ForStmtClass: 339 if (cast<ForStmt>(Parent)->getBody() == S) 340 return PathDiagnosticLocation(S, SMgr, LC); 341 break; 342 case Stmt::IfStmtClass: 343 if (cast<IfStmt>(Parent)->getCond() != S) 344 return PathDiagnosticLocation(S, SMgr, LC); 345 break; 346 case Stmt::ObjCForCollectionStmtClass: 347 if (cast<ObjCForCollectionStmt>(Parent)->getBody() == S) 348 return PathDiagnosticLocation(S, SMgr, LC); 349 break; 350 case Stmt::WhileStmtClass: 351 if (cast<WhileStmt>(Parent)->getCond() != S) 352 return PathDiagnosticLocation(S, SMgr, LC); 353 break; 354 default: 355 break; 356 } 357 358 S = Parent; 359 } 360 361 assert(S && "Cannot have null Stmt for PathDiagnosticLocation"); 362 363 // Special case: DeclStmts can appear in for statement declarations, in which 364 // case the ForStmt is the context. 365 if (isa<DeclStmt>(S)) { 366 if (const Stmt *Parent = P.getParent(S)) { 367 switch (Parent->getStmtClass()) { 368 case Stmt::ForStmtClass: 369 case Stmt::ObjCForCollectionStmtClass: 370 return PathDiagnosticLocation(Parent, SMgr, LC); 371 default: 372 break; 373 } 374 } 375 } 376 else if (isa<BinaryOperator>(S)) { 377 // Special case: the binary operator represents the initialization 378 // code in a for statement (this can happen when the variable being 379 // initialized is an old variable. 380 if (const ForStmt *FS = 381 dyn_cast_or_null<ForStmt>(P.getParentIgnoreParens(S))) { 382 if (FS->getInit() == S) 383 return PathDiagnosticLocation(FS, SMgr, LC); 384 } 385 } 386 387 return PathDiagnosticLocation(S, SMgr, LC); 388} 389 390//===----------------------------------------------------------------------===// 391// "Minimal" path diagnostic generation algorithm. 392//===----------------------------------------------------------------------===// 393typedef std::pair<PathDiagnosticCallPiece*, const ExplodedNode*> StackDiagPair; 394typedef SmallVector<StackDiagPair, 6> StackDiagVector; 395 396static void updateStackPiecesWithMessage(PathDiagnosticPiece *P, 397 StackDiagVector &CallStack) { 398 // If the piece contains a special message, add it to all the call 399 // pieces on the active stack. 400 if (PathDiagnosticEventPiece *ep = 401 dyn_cast<PathDiagnosticEventPiece>(P)) { 402 403 if (ep->hasCallStackHint()) 404 for (StackDiagVector::iterator I = CallStack.begin(), 405 E = CallStack.end(); I != E; ++I) { 406 PathDiagnosticCallPiece *CP = I->first; 407 const ExplodedNode *N = I->second; 408 std::string stackMsg = ep->getCallStackMessage(N); 409 410 // The last message on the path to final bug is the most important 411 // one. Since we traverse the path backwards, do not add the message 412 // if one has been previously added. 413 if (!CP->hasCallStackMessage()) 414 CP->setCallStackMessage(stackMsg); 415 } 416 } 417} 418 419static void CompactPathDiagnostic(PathPieces &path, const SourceManager& SM); 420 421static void GenerateMinimalPathDiagnostic(PathDiagnostic& PD, 422 PathDiagnosticBuilder &PDB, 423 const ExplodedNode *N, 424 ArrayRef<BugReporterVisitor *> visitors) { 425 426 SourceManager& SMgr = PDB.getSourceManager(); 427 const LocationContext *LC = PDB.LC; 428 const ExplodedNode *NextNode = N->pred_empty() 429 ? NULL : *(N->pred_begin()); 430 431 StackDiagVector CallStack; 432 433 while (NextNode) { 434 N = NextNode; 435 PDB.LC = N->getLocationContext(); 436 NextNode = GetPredecessorNode(N); 437 438 ProgramPoint P = N->getLocation(); 439 440 do { 441 if (const CallExitEnd *CE = dyn_cast<CallExitEnd>(&P)) { 442 PathDiagnosticCallPiece *C = 443 PathDiagnosticCallPiece::construct(N, *CE, SMgr); 444 GRBugReporter& BR = PDB.getBugReporter(); 445 BR.addCallPieceLocationContextPair(C, CE->getCalleeContext()); 446 PD.getActivePath().push_front(C); 447 PD.pushActivePath(&C->path); 448 CallStack.push_back(StackDiagPair(C, N)); 449 break; 450 } 451 452 if (const CallEnter *CE = dyn_cast<CallEnter>(&P)) { 453 // Flush all locations, and pop the active path. 454 bool VisitedEntireCall = PD.isWithinCall(); 455 PD.popActivePath(); 456 457 // Either we just added a bunch of stuff to the top-level path, or 458 // we have a previous CallExitEnd. If the former, it means that the 459 // path terminated within a function call. We must then take the 460 // current contents of the active path and place it within 461 // a new PathDiagnosticCallPiece. 462 PathDiagnosticCallPiece *C; 463 if (VisitedEntireCall) { 464 C = cast<PathDiagnosticCallPiece>(PD.getActivePath().front()); 465 } else { 466 const Decl *Caller = CE->getLocationContext()->getDecl(); 467 C = PathDiagnosticCallPiece::construct(PD.getActivePath(), Caller); 468 GRBugReporter& BR = PDB.getBugReporter(); 469 BR.addCallPieceLocationContextPair(C, CE->getCalleeContext()); 470 } 471 472 C->setCallee(*CE, SMgr); 473 if (!CallStack.empty()) { 474 assert(CallStack.back().first == C); 475 CallStack.pop_back(); 476 } 477 break; 478 } 479 480 if (const BlockEdge *BE = dyn_cast<BlockEdge>(&P)) { 481 const CFGBlock *Src = BE->getSrc(); 482 const CFGBlock *Dst = BE->getDst(); 483 const Stmt *T = Src->getTerminator(); 484 485 if (!T) 486 break; 487 488 PathDiagnosticLocation Start = 489 PathDiagnosticLocation::createBegin(T, SMgr, 490 N->getLocationContext()); 491 492 switch (T->getStmtClass()) { 493 default: 494 break; 495 496 case Stmt::GotoStmtClass: 497 case Stmt::IndirectGotoStmtClass: { 498 const Stmt *S = GetNextStmt(N); 499 500 if (!S) 501 break; 502 503 std::string sbuf; 504 llvm::raw_string_ostream os(sbuf); 505 const PathDiagnosticLocation &End = PDB.getEnclosingStmtLocation(S); 506 507 os << "Control jumps to line " 508 << End.asLocation().getExpansionLineNumber(); 509 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece( 510 Start, End, os.str())); 511 break; 512 } 513 514 case Stmt::SwitchStmtClass: { 515 // Figure out what case arm we took. 516 std::string sbuf; 517 llvm::raw_string_ostream os(sbuf); 518 519 if (const Stmt *S = Dst->getLabel()) { 520 PathDiagnosticLocation End(S, SMgr, LC); 521 522 switch (S->getStmtClass()) { 523 default: 524 os << "No cases match in the switch statement. " 525 "Control jumps to line " 526 << End.asLocation().getExpansionLineNumber(); 527 break; 528 case Stmt::DefaultStmtClass: 529 os << "Control jumps to the 'default' case at line " 530 << End.asLocation().getExpansionLineNumber(); 531 break; 532 533 case Stmt::CaseStmtClass: { 534 os << "Control jumps to 'case "; 535 const CaseStmt *Case = cast<CaseStmt>(S); 536 const Expr *LHS = Case->getLHS()->IgnoreParenCasts(); 537 538 // Determine if it is an enum. 539 bool GetRawInt = true; 540 541 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(LHS)) { 542 // FIXME: Maybe this should be an assertion. Are there cases 543 // were it is not an EnumConstantDecl? 544 const EnumConstantDecl *D = 545 dyn_cast<EnumConstantDecl>(DR->getDecl()); 546 547 if (D) { 548 GetRawInt = false; 549 os << *D; 550 } 551 } 552 553 if (GetRawInt) 554 os << LHS->EvaluateKnownConstInt(PDB.getASTContext()); 555 556 os << ":' at line " 557 << End.asLocation().getExpansionLineNumber(); 558 break; 559 } 560 } 561 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece( 562 Start, End, os.str())); 563 } 564 else { 565 os << "'Default' branch taken. "; 566 const PathDiagnosticLocation &End = PDB.ExecutionContinues(os, N); 567 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece( 568 Start, End, os.str())); 569 } 570 571 break; 572 } 573 574 case Stmt::BreakStmtClass: 575 case Stmt::ContinueStmtClass: { 576 std::string sbuf; 577 llvm::raw_string_ostream os(sbuf); 578 PathDiagnosticLocation End = PDB.ExecutionContinues(os, N); 579 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece( 580 Start, End, os.str())); 581 break; 582 } 583 584 // Determine control-flow for ternary '?'. 585 case Stmt::BinaryConditionalOperatorClass: 586 case Stmt::ConditionalOperatorClass: { 587 std::string sbuf; 588 llvm::raw_string_ostream os(sbuf); 589 os << "'?' condition is "; 590 591 if (*(Src->succ_begin()+1) == Dst) 592 os << "false"; 593 else 594 os << "true"; 595 596 PathDiagnosticLocation End = PDB.ExecutionContinues(N); 597 598 if (const Stmt *S = End.asStmt()) 599 End = PDB.getEnclosingStmtLocation(S); 600 601 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece( 602 Start, End, os.str())); 603 break; 604 } 605 606 // Determine control-flow for short-circuited '&&' and '||'. 607 case Stmt::BinaryOperatorClass: { 608 if (!PDB.supportsLogicalOpControlFlow()) 609 break; 610 611 const BinaryOperator *B = cast<BinaryOperator>(T); 612 std::string sbuf; 613 llvm::raw_string_ostream os(sbuf); 614 os << "Left side of '"; 615 616 if (B->getOpcode() == BO_LAnd) { 617 os << "&&" << "' is "; 618 619 if (*(Src->succ_begin()+1) == Dst) { 620 os << "false"; 621 PathDiagnosticLocation End(B->getLHS(), SMgr, LC); 622 PathDiagnosticLocation Start = 623 PathDiagnosticLocation::createOperatorLoc(B, SMgr); 624 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece( 625 Start, End, os.str())); 626 } 627 else { 628 os << "true"; 629 PathDiagnosticLocation Start(B->getLHS(), SMgr, LC); 630 PathDiagnosticLocation End = PDB.ExecutionContinues(N); 631 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece( 632 Start, End, os.str())); 633 } 634 } 635 else { 636 assert(B->getOpcode() == BO_LOr); 637 os << "||" << "' is "; 638 639 if (*(Src->succ_begin()+1) == Dst) { 640 os << "false"; 641 PathDiagnosticLocation Start(B->getLHS(), SMgr, LC); 642 PathDiagnosticLocation End = PDB.ExecutionContinues(N); 643 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece( 644 Start, End, os.str())); 645 } 646 else { 647 os << "true"; 648 PathDiagnosticLocation End(B->getLHS(), SMgr, LC); 649 PathDiagnosticLocation Start = 650 PathDiagnosticLocation::createOperatorLoc(B, SMgr); 651 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece( 652 Start, End, os.str())); 653 } 654 } 655 656 break; 657 } 658 659 case Stmt::DoStmtClass: { 660 if (*(Src->succ_begin()) == Dst) { 661 std::string sbuf; 662 llvm::raw_string_ostream os(sbuf); 663 664 os << "Loop condition is true. "; 665 PathDiagnosticLocation End = PDB.ExecutionContinues(os, N); 666 667 if (const Stmt *S = End.asStmt()) 668 End = PDB.getEnclosingStmtLocation(S); 669 670 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece( 671 Start, End, os.str())); 672 } 673 else { 674 PathDiagnosticLocation End = PDB.ExecutionContinues(N); 675 676 if (const Stmt *S = End.asStmt()) 677 End = PDB.getEnclosingStmtLocation(S); 678 679 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece( 680 Start, End, "Loop condition is false. Exiting loop")); 681 } 682 683 break; 684 } 685 686 case Stmt::WhileStmtClass: 687 case Stmt::ForStmtClass: { 688 if (*(Src->succ_begin()+1) == Dst) { 689 std::string sbuf; 690 llvm::raw_string_ostream os(sbuf); 691 692 os << "Loop condition is false. "; 693 PathDiagnosticLocation End = PDB.ExecutionContinues(os, N); 694 if (const Stmt *S = End.asStmt()) 695 End = PDB.getEnclosingStmtLocation(S); 696 697 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece( 698 Start, End, os.str())); 699 } 700 else { 701 PathDiagnosticLocation End = PDB.ExecutionContinues(N); 702 if (const Stmt *S = End.asStmt()) 703 End = PDB.getEnclosingStmtLocation(S); 704 705 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece( 706 Start, End, "Loop condition is true. Entering loop body")); 707 } 708 709 break; 710 } 711 712 case Stmt::IfStmtClass: { 713 PathDiagnosticLocation End = PDB.ExecutionContinues(N); 714 715 if (const Stmt *S = End.asStmt()) 716 End = PDB.getEnclosingStmtLocation(S); 717 718 if (*(Src->succ_begin()+1) == Dst) 719 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece( 720 Start, End, "Taking false branch")); 721 else 722 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece( 723 Start, End, "Taking true branch")); 724 725 break; 726 } 727 } 728 } 729 } while(0); 730 731 if (NextNode) { 732 // Add diagnostic pieces from custom visitors. 733 BugReport *R = PDB.getBugReport(); 734 for (ArrayRef<BugReporterVisitor *>::iterator I = visitors.begin(), 735 E = visitors.end(); 736 I != E; ++I) { 737 if (PathDiagnosticPiece *p = (*I)->VisitNode(N, NextNode, PDB, *R)) { 738 PD.getActivePath().push_front(p); 739 updateStackPiecesWithMessage(p, CallStack); 740 } 741 } 742 } 743 } 744 745 // After constructing the full PathDiagnostic, do a pass over it to compact 746 // PathDiagnosticPieces that occur within a macro. 747 CompactPathDiagnostic(PD.getMutablePieces(), PDB.getSourceManager()); 748} 749 750//===----------------------------------------------------------------------===// 751// "Extensive" PathDiagnostic generation. 752//===----------------------------------------------------------------------===// 753 754static bool IsControlFlowExpr(const Stmt *S) { 755 const Expr *E = dyn_cast<Expr>(S); 756 757 if (!E) 758 return false; 759 760 E = E->IgnoreParenCasts(); 761 762 if (isa<AbstractConditionalOperator>(E)) 763 return true; 764 765 if (const BinaryOperator *B = dyn_cast<BinaryOperator>(E)) 766 if (B->isLogicalOp()) 767 return true; 768 769 return false; 770} 771 772namespace { 773class ContextLocation : public PathDiagnosticLocation { 774 bool IsDead; 775public: 776 ContextLocation(const PathDiagnosticLocation &L, bool isdead = false) 777 : PathDiagnosticLocation(L), IsDead(isdead) {} 778 779 void markDead() { IsDead = true; } 780 bool isDead() const { return IsDead; } 781}; 782 783class EdgeBuilder { 784 std::vector<ContextLocation> CLocs; 785 typedef std::vector<ContextLocation>::iterator iterator; 786 PathDiagnostic &PD; 787 PathDiagnosticBuilder &PDB; 788 PathDiagnosticLocation PrevLoc; 789 790 bool IsConsumedExpr(const PathDiagnosticLocation &L); 791 792 bool containsLocation(const PathDiagnosticLocation &Container, 793 const PathDiagnosticLocation &Containee); 794 795 PathDiagnosticLocation getContextLocation(const PathDiagnosticLocation &L); 796 797 PathDiagnosticLocation cleanUpLocation(PathDiagnosticLocation L, 798 bool firstCharOnly = false) { 799 if (const Stmt *S = L.asStmt()) { 800 const Stmt *Original = S; 801 while (1) { 802 // Adjust the location for some expressions that are best referenced 803 // by one of their subexpressions. 804 switch (S->getStmtClass()) { 805 default: 806 break; 807 case Stmt::ParenExprClass: 808 case Stmt::GenericSelectionExprClass: 809 S = cast<Expr>(S)->IgnoreParens(); 810 firstCharOnly = true; 811 continue; 812 case Stmt::BinaryConditionalOperatorClass: 813 case Stmt::ConditionalOperatorClass: 814 S = cast<AbstractConditionalOperator>(S)->getCond(); 815 firstCharOnly = true; 816 continue; 817 case Stmt::ChooseExprClass: 818 S = cast<ChooseExpr>(S)->getCond(); 819 firstCharOnly = true; 820 continue; 821 case Stmt::BinaryOperatorClass: 822 S = cast<BinaryOperator>(S)->getLHS(); 823 firstCharOnly = true; 824 continue; 825 } 826 827 break; 828 } 829 830 if (S != Original) 831 L = PathDiagnosticLocation(S, L.getManager(), PDB.LC); 832 } 833 834 if (firstCharOnly) 835 L = PathDiagnosticLocation::createSingleLocation(L); 836 837 return L; 838 } 839 840 void popLocation() { 841 if (!CLocs.back().isDead() && CLocs.back().asLocation().isFileID()) { 842 // For contexts, we only one the first character as the range. 843 rawAddEdge(cleanUpLocation(CLocs.back(), true)); 844 } 845 CLocs.pop_back(); 846 } 847 848public: 849 EdgeBuilder(PathDiagnostic &pd, PathDiagnosticBuilder &pdb) 850 : PD(pd), PDB(pdb) { 851 852 // If the PathDiagnostic already has pieces, add the enclosing statement 853 // of the first piece as a context as well. 854 if (!PD.path.empty()) { 855 PrevLoc = (*PD.path.begin())->getLocation(); 856 857 if (const Stmt *S = PrevLoc.asStmt()) 858 addExtendedContext(PDB.getEnclosingStmtLocation(S).asStmt()); 859 } 860 } 861 862 ~EdgeBuilder() { 863 while (!CLocs.empty()) popLocation(); 864 865 // Finally, add an initial edge from the start location of the first 866 // statement (if it doesn't already exist). 867 PathDiagnosticLocation L = PathDiagnosticLocation::createDeclBegin( 868 PDB.LC, 869 PDB.getSourceManager()); 870 if (L.isValid()) 871 rawAddEdge(L); 872 } 873 874 void flushLocations() { 875 while (!CLocs.empty()) 876 popLocation(); 877 PrevLoc = PathDiagnosticLocation(); 878 } 879 880 void addEdge(PathDiagnosticLocation NewLoc, bool alwaysAdd = false); 881 882 void rawAddEdge(PathDiagnosticLocation NewLoc); 883 884 void addContext(const Stmt *S); 885 void addContext(const PathDiagnosticLocation &L); 886 void addExtendedContext(const Stmt *S); 887}; 888} // end anonymous namespace 889 890 891PathDiagnosticLocation 892EdgeBuilder::getContextLocation(const PathDiagnosticLocation &L) { 893 if (const Stmt *S = L.asStmt()) { 894 if (IsControlFlowExpr(S)) 895 return L; 896 897 return PDB.getEnclosingStmtLocation(S); 898 } 899 900 return L; 901} 902 903bool EdgeBuilder::containsLocation(const PathDiagnosticLocation &Container, 904 const PathDiagnosticLocation &Containee) { 905 906 if (Container == Containee) 907 return true; 908 909 if (Container.asDecl()) 910 return true; 911 912 if (const Stmt *S = Containee.asStmt()) 913 if (const Stmt *ContainerS = Container.asStmt()) { 914 while (S) { 915 if (S == ContainerS) 916 return true; 917 S = PDB.getParent(S); 918 } 919 return false; 920 } 921 922 // Less accurate: compare using source ranges. 923 SourceRange ContainerR = Container.asRange(); 924 SourceRange ContaineeR = Containee.asRange(); 925 926 SourceManager &SM = PDB.getSourceManager(); 927 SourceLocation ContainerRBeg = SM.getExpansionLoc(ContainerR.getBegin()); 928 SourceLocation ContainerREnd = SM.getExpansionLoc(ContainerR.getEnd()); 929 SourceLocation ContaineeRBeg = SM.getExpansionLoc(ContaineeR.getBegin()); 930 SourceLocation ContaineeREnd = SM.getExpansionLoc(ContaineeR.getEnd()); 931 932 unsigned ContainerBegLine = SM.getExpansionLineNumber(ContainerRBeg); 933 unsigned ContainerEndLine = SM.getExpansionLineNumber(ContainerREnd); 934 unsigned ContaineeBegLine = SM.getExpansionLineNumber(ContaineeRBeg); 935 unsigned ContaineeEndLine = SM.getExpansionLineNumber(ContaineeREnd); 936 937 assert(ContainerBegLine <= ContainerEndLine); 938 assert(ContaineeBegLine <= ContaineeEndLine); 939 940 return (ContainerBegLine <= ContaineeBegLine && 941 ContainerEndLine >= ContaineeEndLine && 942 (ContainerBegLine != ContaineeBegLine || 943 SM.getExpansionColumnNumber(ContainerRBeg) <= 944 SM.getExpansionColumnNumber(ContaineeRBeg)) && 945 (ContainerEndLine != ContaineeEndLine || 946 SM.getExpansionColumnNumber(ContainerREnd) >= 947 SM.getExpansionColumnNumber(ContaineeREnd))); 948} 949 950void EdgeBuilder::rawAddEdge(PathDiagnosticLocation NewLoc) { 951 if (!PrevLoc.isValid()) { 952 PrevLoc = NewLoc; 953 return; 954 } 955 956 const PathDiagnosticLocation &NewLocClean = cleanUpLocation(NewLoc); 957 const PathDiagnosticLocation &PrevLocClean = cleanUpLocation(PrevLoc); 958 959 if (NewLocClean.asLocation() == PrevLocClean.asLocation()) 960 return; 961 962 // FIXME: Ignore intra-macro edges for now. 963 if (NewLocClean.asLocation().getExpansionLoc() == 964 PrevLocClean.asLocation().getExpansionLoc()) 965 return; 966 967 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(NewLocClean, PrevLocClean)); 968 PrevLoc = NewLoc; 969} 970 971void EdgeBuilder::addEdge(PathDiagnosticLocation NewLoc, bool alwaysAdd) { 972 973 if (!alwaysAdd && NewLoc.asLocation().isMacroID()) 974 return; 975 976 const PathDiagnosticLocation &CLoc = getContextLocation(NewLoc); 977 978 while (!CLocs.empty()) { 979 ContextLocation &TopContextLoc = CLocs.back(); 980 981 // Is the top location context the same as the one for the new location? 982 if (TopContextLoc == CLoc) { 983 if (alwaysAdd) { 984 if (IsConsumedExpr(TopContextLoc) && 985 !IsControlFlowExpr(TopContextLoc.asStmt())) 986 TopContextLoc.markDead(); 987 988 rawAddEdge(NewLoc); 989 } 990 991 return; 992 } 993 994 if (containsLocation(TopContextLoc, CLoc)) { 995 if (alwaysAdd) { 996 rawAddEdge(NewLoc); 997 998 if (IsConsumedExpr(CLoc) && !IsControlFlowExpr(CLoc.asStmt())) { 999 CLocs.push_back(ContextLocation(CLoc, true)); 1000 return; 1001 } 1002 } 1003 1004 CLocs.push_back(CLoc); 1005 return; 1006 } 1007 1008 // Context does not contain the location. Flush it. 1009 popLocation(); 1010 } 1011 1012 // If we reach here, there is no enclosing context. Just add the edge. 1013 rawAddEdge(NewLoc); 1014} 1015 1016bool EdgeBuilder::IsConsumedExpr(const PathDiagnosticLocation &L) { 1017 if (const Expr *X = dyn_cast_or_null<Expr>(L.asStmt())) 1018 return PDB.getParentMap().isConsumedExpr(X) && !IsControlFlowExpr(X); 1019 1020 return false; 1021} 1022 1023void EdgeBuilder::addExtendedContext(const Stmt *S) { 1024 if (!S) 1025 return; 1026 1027 const Stmt *Parent = PDB.getParent(S); 1028 while (Parent) { 1029 if (isa<CompoundStmt>(Parent)) 1030 Parent = PDB.getParent(Parent); 1031 else 1032 break; 1033 } 1034 1035 if (Parent) { 1036 switch (Parent->getStmtClass()) { 1037 case Stmt::DoStmtClass: 1038 case Stmt::ObjCAtSynchronizedStmtClass: 1039 addContext(Parent); 1040 default: 1041 break; 1042 } 1043 } 1044 1045 addContext(S); 1046} 1047 1048void EdgeBuilder::addContext(const Stmt *S) { 1049 if (!S) 1050 return; 1051 1052 PathDiagnosticLocation L(S, PDB.getSourceManager(), PDB.LC); 1053 addContext(L); 1054} 1055 1056void EdgeBuilder::addContext(const PathDiagnosticLocation &L) { 1057 while (!CLocs.empty()) { 1058 const PathDiagnosticLocation &TopContextLoc = CLocs.back(); 1059 1060 // Is the top location context the same as the one for the new location? 1061 if (TopContextLoc == L) 1062 return; 1063 1064 if (containsLocation(TopContextLoc, L)) { 1065 CLocs.push_back(L); 1066 return; 1067 } 1068 1069 // Context does not contain the location. Flush it. 1070 popLocation(); 1071 } 1072 1073 CLocs.push_back(L); 1074} 1075 1076// Cone-of-influence: support the reverse propagation of "interesting" symbols 1077// and values by tracing interesting calculations backwards through evaluated 1078// expressions along a path. This is probably overly complicated, but the idea 1079// is that if an expression computed an "interesting" value, the child 1080// expressions are are also likely to be "interesting" as well (which then 1081// propagates to the values they in turn compute). This reverse propagation 1082// is needed to track interesting correlations across function call boundaries, 1083// where formal arguments bind to actual arguments, etc. This is also needed 1084// because the constraint solver sometimes simplifies certain symbolic values 1085// into constants when appropriate, and this complicates reasoning about 1086// interesting values. 1087typedef llvm::DenseSet<const Expr *> InterestingExprs; 1088 1089static void reversePropagateIntererstingSymbols(BugReport &R, 1090 InterestingExprs &IE, 1091 const ProgramState *State, 1092 const Expr *Ex, 1093 const LocationContext *LCtx) { 1094 SVal V = State->getSVal(Ex, LCtx); 1095 if (!(R.isInteresting(V) || IE.count(Ex))) 1096 return; 1097 1098 switch (Ex->getStmtClass()) { 1099 default: 1100 if (!isa<CastExpr>(Ex)) 1101 break; 1102 // Fall through. 1103 case Stmt::BinaryOperatorClass: 1104 case Stmt::UnaryOperatorClass: { 1105 for (Stmt::const_child_iterator CI = Ex->child_begin(), 1106 CE = Ex->child_end(); 1107 CI != CE; ++CI) { 1108 if (const Expr *child = dyn_cast_or_null<Expr>(*CI)) { 1109 IE.insert(child); 1110 SVal ChildV = State->getSVal(child, LCtx); 1111 R.markInteresting(ChildV); 1112 } 1113 break; 1114 } 1115 } 1116 } 1117 1118 R.markInteresting(V); 1119} 1120 1121static void reversePropagateInterestingSymbols(BugReport &R, 1122 InterestingExprs &IE, 1123 const ProgramState *State, 1124 const LocationContext *CalleeCtx, 1125 const LocationContext *CallerCtx) 1126{ 1127 // FIXME: Handle non-CallExpr-based CallEvents. 1128 const StackFrameContext *Callee = CalleeCtx->getCurrentStackFrame(); 1129 const Stmt *CallSite = Callee->getCallSite(); 1130 if (const CallExpr *CE = dyn_cast_or_null<CallExpr>(CallSite)) { 1131 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CalleeCtx->getDecl())) { 1132 FunctionDecl::param_const_iterator PI = FD->param_begin(), 1133 PE = FD->param_end(); 1134 CallExpr::const_arg_iterator AI = CE->arg_begin(), AE = CE->arg_end(); 1135 for (; AI != AE && PI != PE; ++AI, ++PI) { 1136 if (const Expr *ArgE = *AI) { 1137 if (const ParmVarDecl *PD = *PI) { 1138 Loc LV = State->getLValue(PD, CalleeCtx); 1139 if (R.isInteresting(LV) || R.isInteresting(State->getRawSVal(LV))) 1140 IE.insert(ArgE); 1141 } 1142 } 1143 } 1144 } 1145 } 1146} 1147 1148static void GenerateExtensivePathDiagnostic(PathDiagnostic& PD, 1149 PathDiagnosticBuilder &PDB, 1150 const ExplodedNode *N, 1151 ArrayRef<BugReporterVisitor *> visitors) { 1152 EdgeBuilder EB(PD, PDB); 1153 const SourceManager& SM = PDB.getSourceManager(); 1154 StackDiagVector CallStack; 1155 InterestingExprs IE; 1156 1157 const ExplodedNode *NextNode = N->pred_empty() ? NULL : *(N->pred_begin()); 1158 while (NextNode) { 1159 N = NextNode; 1160 NextNode = GetPredecessorNode(N); 1161 ProgramPoint P = N->getLocation(); 1162 1163 do { 1164 if (const PostStmt *PS = dyn_cast<PostStmt>(&P)) { 1165 if (const Expr *Ex = PS->getStmtAs<Expr>()) 1166 reversePropagateIntererstingSymbols(*PDB.getBugReport(), IE, 1167 N->getState().getPtr(), Ex, 1168 N->getLocationContext()); 1169 } 1170 1171 if (const CallExitEnd *CE = dyn_cast<CallExitEnd>(&P)) { 1172 const Stmt *S = CE->getCalleeContext()->getCallSite(); 1173 if (const Expr *Ex = dyn_cast_or_null<Expr>(S)) { 1174 reversePropagateIntererstingSymbols(*PDB.getBugReport(), IE, 1175 N->getState().getPtr(), Ex, 1176 N->getLocationContext()); 1177 } 1178 1179 PathDiagnosticCallPiece *C = 1180 PathDiagnosticCallPiece::construct(N, *CE, SM); 1181 GRBugReporter& BR = PDB.getBugReporter(); 1182 BR.addCallPieceLocationContextPair(C, CE->getCalleeContext()); 1183 1184 EB.addEdge(C->callReturn, true); 1185 EB.flushLocations(); 1186 1187 PD.getActivePath().push_front(C); 1188 PD.pushActivePath(&C->path); 1189 CallStack.push_back(StackDiagPair(C, N)); 1190 break; 1191 } 1192 1193 // Pop the call hierarchy if we are done walking the contents 1194 // of a function call. 1195 if (const CallEnter *CE = dyn_cast<CallEnter>(&P)) { 1196 // Add an edge to the start of the function. 1197 const Decl *D = CE->getCalleeContext()->getDecl(); 1198 PathDiagnosticLocation pos = 1199 PathDiagnosticLocation::createBegin(D, SM); 1200 EB.addEdge(pos); 1201 1202 // Flush all locations, and pop the active path. 1203 bool VisitedEntireCall = PD.isWithinCall(); 1204 EB.flushLocations(); 1205 PD.popActivePath(); 1206 PDB.LC = N->getLocationContext(); 1207 1208 // Either we just added a bunch of stuff to the top-level path, or 1209 // we have a previous CallExitEnd. If the former, it means that the 1210 // path terminated within a function call. We must then take the 1211 // current contents of the active path and place it within 1212 // a new PathDiagnosticCallPiece. 1213 PathDiagnosticCallPiece *C; 1214 if (VisitedEntireCall) { 1215 C = cast<PathDiagnosticCallPiece>(PD.getActivePath().front()); 1216 } else { 1217 const Decl *Caller = CE->getLocationContext()->getDecl(); 1218 C = PathDiagnosticCallPiece::construct(PD.getActivePath(), Caller); 1219 GRBugReporter& BR = PDB.getBugReporter(); 1220 BR.addCallPieceLocationContextPair(C, CE->getCalleeContext()); 1221 } 1222 1223 C->setCallee(*CE, SM); 1224 EB.addContext(C->getLocation()); 1225 1226 if (!CallStack.empty()) { 1227 assert(CallStack.back().first == C); 1228 CallStack.pop_back(); 1229 } 1230 break; 1231 } 1232 1233 // Note that is important that we update the LocationContext 1234 // after looking at CallExits. CallExit basically adds an 1235 // edge in the *caller*, so we don't want to update the LocationContext 1236 // too soon. 1237 PDB.LC = N->getLocationContext(); 1238 1239 // Block edges. 1240 if (const BlockEdge *BE = dyn_cast<BlockEdge>(&P)) { 1241 // Does this represent entering a call? If so, look at propagating 1242 // interesting symbols across call boundaries. 1243 if (NextNode) { 1244 const LocationContext *CallerCtx = NextNode->getLocationContext(); 1245 const LocationContext *CalleeCtx = PDB.LC; 1246 if (CallerCtx != CalleeCtx) { 1247 reversePropagateInterestingSymbols(*PDB.getBugReport(), IE, 1248 N->getState().getPtr(), 1249 CalleeCtx, CallerCtx); 1250 } 1251 } 1252 1253 const CFGBlock &Blk = *BE->getSrc(); 1254 const Stmt *Term = Blk.getTerminator(); 1255 1256 // Are we jumping to the head of a loop? Add a special diagnostic. 1257 if (const Stmt *Loop = BE->getDst()->getLoopTarget()) { 1258 PathDiagnosticLocation L(Loop, SM, PDB.LC); 1259 const CompoundStmt *CS = NULL; 1260 1261 if (!Term) { 1262 if (const ForStmt *FS = dyn_cast<ForStmt>(Loop)) 1263 CS = dyn_cast<CompoundStmt>(FS->getBody()); 1264 else if (const WhileStmt *WS = dyn_cast<WhileStmt>(Loop)) 1265 CS = dyn_cast<CompoundStmt>(WS->getBody()); 1266 } 1267 1268 PathDiagnosticEventPiece *p = 1269 new PathDiagnosticEventPiece(L, 1270 "Looping back to the head of the loop"); 1271 p->setPrunable(true); 1272 1273 EB.addEdge(p->getLocation(), true); 1274 PD.getActivePath().push_front(p); 1275 1276 if (CS) { 1277 PathDiagnosticLocation BL = 1278 PathDiagnosticLocation::createEndBrace(CS, SM); 1279 EB.addEdge(BL); 1280 } 1281 } 1282 1283 if (Term) 1284 EB.addContext(Term); 1285 1286 break; 1287 } 1288 1289 if (const BlockEntrance *BE = dyn_cast<BlockEntrance>(&P)) { 1290 if (const CFGStmt *S = BE->getFirstElement().getAs<CFGStmt>()) { 1291 const Stmt *stmt = S->getStmt(); 1292 if (IsControlFlowExpr(stmt)) { 1293 // Add the proper context for '&&', '||', and '?'. 1294 EB.addContext(stmt); 1295 } 1296 else 1297 EB.addExtendedContext(PDB.getEnclosingStmtLocation(stmt).asStmt()); 1298 } 1299 1300 break; 1301 } 1302 1303 1304 } while (0); 1305 1306 if (!NextNode) 1307 continue; 1308 1309 // Add pieces from custom visitors. 1310 BugReport *R = PDB.getBugReport(); 1311 for (ArrayRef<BugReporterVisitor *>::iterator I = visitors.begin(), 1312 E = visitors.end(); 1313 I != E; ++I) { 1314 if (PathDiagnosticPiece *p = (*I)->VisitNode(N, NextNode, PDB, *R)) { 1315 const PathDiagnosticLocation &Loc = p->getLocation(); 1316 EB.addEdge(Loc, true); 1317 PD.getActivePath().push_front(p); 1318 updateStackPiecesWithMessage(p, CallStack); 1319 1320 if (const Stmt *S = Loc.asStmt()) 1321 EB.addExtendedContext(PDB.getEnclosingStmtLocation(S).asStmt()); 1322 } 1323 } 1324 } 1325} 1326 1327//===----------------------------------------------------------------------===// 1328// Methods for BugType and subclasses. 1329//===----------------------------------------------------------------------===// 1330BugType::~BugType() { } 1331 1332void BugType::FlushReports(BugReporter &BR) {} 1333 1334void BuiltinBug::anchor() {} 1335 1336//===----------------------------------------------------------------------===// 1337// Methods for BugReport and subclasses. 1338//===----------------------------------------------------------------------===// 1339 1340void BugReport::NodeResolver::anchor() {} 1341 1342void BugReport::addVisitor(BugReporterVisitor* visitor) { 1343 if (!visitor) 1344 return; 1345 1346 llvm::FoldingSetNodeID ID; 1347 visitor->Profile(ID); 1348 void *InsertPos; 1349 1350 if (CallbacksSet.FindNodeOrInsertPos(ID, InsertPos)) { 1351 delete visitor; 1352 return; 1353 } 1354 1355 CallbacksSet.InsertNode(visitor, InsertPos); 1356 Callbacks.push_back(visitor); 1357 ++ConfigurationChangeToken; 1358} 1359 1360BugReport::~BugReport() { 1361 for (visitor_iterator I = visitor_begin(), E = visitor_end(); I != E; ++I) { 1362 delete *I; 1363 } 1364 while (!interestingSymbols.empty()) { 1365 popInterestingSymbolsAndRegions(); 1366 } 1367} 1368 1369const Decl *BugReport::getDeclWithIssue() const { 1370 if (DeclWithIssue) 1371 return DeclWithIssue; 1372 1373 const ExplodedNode *N = getErrorNode(); 1374 if (!N) 1375 return 0; 1376 1377 const LocationContext *LC = N->getLocationContext(); 1378 return LC->getCurrentStackFrame()->getDecl(); 1379} 1380 1381void BugReport::Profile(llvm::FoldingSetNodeID& hash) const { 1382 hash.AddPointer(&BT); 1383 hash.AddString(Description); 1384 if (UniqueingLocation.isValid()) { 1385 UniqueingLocation.Profile(hash); 1386 } else if (Location.isValid()) { 1387 Location.Profile(hash); 1388 } else { 1389 assert(ErrorNode); 1390 hash.AddPointer(GetCurrentOrPreviousStmt(ErrorNode)); 1391 } 1392 1393 for (SmallVectorImpl<SourceRange>::const_iterator I = 1394 Ranges.begin(), E = Ranges.end(); I != E; ++I) { 1395 const SourceRange range = *I; 1396 if (!range.isValid()) 1397 continue; 1398 hash.AddInteger(range.getBegin().getRawEncoding()); 1399 hash.AddInteger(range.getEnd().getRawEncoding()); 1400 } 1401} 1402 1403void BugReport::markInteresting(SymbolRef sym) { 1404 if (!sym) 1405 return; 1406 1407 // If the symbol wasn't already in our set, note a configuration change. 1408 if (getInterestingSymbols().insert(sym).second) 1409 ++ConfigurationChangeToken; 1410 1411 if (const SymbolMetadata *meta = dyn_cast<SymbolMetadata>(sym)) 1412 getInterestingRegions().insert(meta->getRegion()); 1413} 1414 1415void BugReport::markInteresting(const MemRegion *R) { 1416 if (!R) 1417 return; 1418 1419 // If the base region wasn't already in our set, note a configuration change. 1420 R = R->getBaseRegion(); 1421 if (getInterestingRegions().insert(R).second) 1422 ++ConfigurationChangeToken; 1423 1424 if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R)) 1425 getInterestingSymbols().insert(SR->getSymbol()); 1426} 1427 1428void BugReport::markInteresting(SVal V) { 1429 markInteresting(V.getAsRegion()); 1430 markInteresting(V.getAsSymbol()); 1431} 1432 1433void BugReport::markInteresting(const LocationContext *LC) { 1434 if (!LC) 1435 return; 1436 InterestingLocationContexts.insert(LC); 1437} 1438 1439bool BugReport::isInteresting(SVal V) { 1440 return isInteresting(V.getAsRegion()) || isInteresting(V.getAsSymbol()); 1441} 1442 1443bool BugReport::isInteresting(SymbolRef sym) { 1444 if (!sym) 1445 return false; 1446 // We don't currently consider metadata symbols to be interesting 1447 // even if we know their region is interesting. Is that correct behavior? 1448 return getInterestingSymbols().count(sym); 1449} 1450 1451bool BugReport::isInteresting(const MemRegion *R) { 1452 if (!R) 1453 return false; 1454 R = R->getBaseRegion(); 1455 bool b = getInterestingRegions().count(R); 1456 if (b) 1457 return true; 1458 if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R)) 1459 return getInterestingSymbols().count(SR->getSymbol()); 1460 return false; 1461} 1462 1463bool BugReport::isInteresting(const LocationContext *LC) { 1464 if (!LC) 1465 return false; 1466 return InterestingLocationContexts.count(LC); 1467} 1468 1469void BugReport::lazyInitializeInterestingSets() { 1470 if (interestingSymbols.empty()) { 1471 interestingSymbols.push_back(new Symbols()); 1472 interestingRegions.push_back(new Regions()); 1473 } 1474} 1475 1476BugReport::Symbols &BugReport::getInterestingSymbols() { 1477 lazyInitializeInterestingSets(); 1478 return *interestingSymbols.back(); 1479} 1480 1481BugReport::Regions &BugReport::getInterestingRegions() { 1482 lazyInitializeInterestingSets(); 1483 return *interestingRegions.back(); 1484} 1485 1486void BugReport::pushInterestingSymbolsAndRegions() { 1487 interestingSymbols.push_back(new Symbols(getInterestingSymbols())); 1488 interestingRegions.push_back(new Regions(getInterestingRegions())); 1489} 1490 1491void BugReport::popInterestingSymbolsAndRegions() { 1492 delete interestingSymbols.back(); 1493 interestingSymbols.pop_back(); 1494 delete interestingRegions.back(); 1495 interestingRegions.pop_back(); 1496} 1497 1498const Stmt *BugReport::getStmt() const { 1499 if (!ErrorNode) 1500 return 0; 1501 1502 ProgramPoint ProgP = ErrorNode->getLocation(); 1503 const Stmt *S = NULL; 1504 1505 if (BlockEntrance *BE = dyn_cast<BlockEntrance>(&ProgP)) { 1506 CFGBlock &Exit = ProgP.getLocationContext()->getCFG()->getExit(); 1507 if (BE->getBlock() == &Exit) 1508 S = GetPreviousStmt(ErrorNode); 1509 } 1510 if (!S) 1511 S = GetStmt(ProgP); 1512 1513 return S; 1514} 1515 1516std::pair<BugReport::ranges_iterator, BugReport::ranges_iterator> 1517BugReport::getRanges() { 1518 // If no custom ranges, add the range of the statement corresponding to 1519 // the error node. 1520 if (Ranges.empty()) { 1521 if (const Expr *E = dyn_cast_or_null<Expr>(getStmt())) 1522 addRange(E->getSourceRange()); 1523 else 1524 return std::make_pair(ranges_iterator(), ranges_iterator()); 1525 } 1526 1527 // User-specified absence of range info. 1528 if (Ranges.size() == 1 && !Ranges.begin()->isValid()) 1529 return std::make_pair(ranges_iterator(), ranges_iterator()); 1530 1531 return std::make_pair(Ranges.begin(), Ranges.end()); 1532} 1533 1534PathDiagnosticLocation BugReport::getLocation(const SourceManager &SM) const { 1535 if (ErrorNode) { 1536 assert(!Location.isValid() && 1537 "Either Location or ErrorNode should be specified but not both."); 1538 1539 if (const Stmt *S = GetCurrentOrPreviousStmt(ErrorNode)) { 1540 const LocationContext *LC = ErrorNode->getLocationContext(); 1541 1542 // For member expressions, return the location of the '.' or '->'. 1543 if (const MemberExpr *ME = dyn_cast<MemberExpr>(S)) 1544 return PathDiagnosticLocation::createMemberLoc(ME, SM); 1545 // For binary operators, return the location of the operator. 1546 if (const BinaryOperator *B = dyn_cast<BinaryOperator>(S)) 1547 return PathDiagnosticLocation::createOperatorLoc(B, SM); 1548 1549 return PathDiagnosticLocation::createBegin(S, SM, LC); 1550 } 1551 } else { 1552 assert(Location.isValid()); 1553 return Location; 1554 } 1555 1556 return PathDiagnosticLocation(); 1557} 1558 1559//===----------------------------------------------------------------------===// 1560// Methods for BugReporter and subclasses. 1561//===----------------------------------------------------------------------===// 1562 1563BugReportEquivClass::~BugReportEquivClass() { } 1564GRBugReporter::~GRBugReporter() { } 1565BugReporterData::~BugReporterData() {} 1566 1567ExplodedGraph &GRBugReporter::getGraph() { return Eng.getGraph(); } 1568 1569ProgramStateManager& 1570GRBugReporter::getStateManager() { return Eng.getStateManager(); } 1571 1572BugReporter::~BugReporter() { 1573 FlushReports(); 1574 1575 // Free the bug reports we are tracking. 1576 typedef std::vector<BugReportEquivClass *> ContTy; 1577 for (ContTy::iterator I = EQClassesVector.begin(), E = EQClassesVector.end(); 1578 I != E; ++I) { 1579 delete *I; 1580 } 1581} 1582 1583void BugReporter::FlushReports() { 1584 if (BugTypes.isEmpty()) 1585 return; 1586 1587 // First flush the warnings for each BugType. This may end up creating new 1588 // warnings and new BugTypes. 1589 // FIXME: Only NSErrorChecker needs BugType's FlushReports. 1590 // Turn NSErrorChecker into a proper checker and remove this. 1591 SmallVector<const BugType*, 16> bugTypes; 1592 for (BugTypesTy::iterator I=BugTypes.begin(), E=BugTypes.end(); I!=E; ++I) 1593 bugTypes.push_back(*I); 1594 for (SmallVector<const BugType*, 16>::iterator 1595 I = bugTypes.begin(), E = bugTypes.end(); I != E; ++I) 1596 const_cast<BugType*>(*I)->FlushReports(*this); 1597 1598 // We need to flush reports in deterministic order to ensure the order 1599 // of the reports is consistent between runs. 1600 typedef std::vector<BugReportEquivClass *> ContVecTy; 1601 for (ContVecTy::iterator EI=EQClassesVector.begin(), EE=EQClassesVector.end(); 1602 EI != EE; ++EI){ 1603 BugReportEquivClass& EQ = **EI; 1604 FlushReport(EQ); 1605 } 1606 1607 // BugReporter owns and deletes only BugTypes created implicitly through 1608 // EmitBasicReport. 1609 // FIXME: There are leaks from checkers that assume that the BugTypes they 1610 // create will be destroyed by the BugReporter. 1611 for (llvm::StringMap<BugType*>::iterator 1612 I = StrBugTypes.begin(), E = StrBugTypes.end(); I != E; ++I) 1613 delete I->second; 1614 1615 // Remove all references to the BugType objects. 1616 BugTypes = F.getEmptySet(); 1617} 1618 1619//===----------------------------------------------------------------------===// 1620// PathDiagnostics generation. 1621//===----------------------------------------------------------------------===// 1622 1623static std::pair<std::pair<ExplodedGraph*, NodeBackMap*>, 1624 std::pair<ExplodedNode*, unsigned> > 1625MakeReportGraph(const ExplodedGraph* G, 1626 SmallVectorImpl<const ExplodedNode*> &nodes) { 1627 1628 // Create the trimmed graph. It will contain the shortest paths from the 1629 // error nodes to the root. In the new graph we should only have one 1630 // error node unless there are two or more error nodes with the same minimum 1631 // path length. 1632 ExplodedGraph* GTrim; 1633 InterExplodedGraphMap* NMap; 1634 1635 llvm::DenseMap<const void*, const void*> InverseMap; 1636 llvm::tie(GTrim, NMap) = G->Trim(nodes.data(), nodes.data() + nodes.size(), 1637 &InverseMap); 1638 1639 // Create owning pointers for GTrim and NMap just to ensure that they are 1640 // released when this function exists. 1641 OwningPtr<ExplodedGraph> AutoReleaseGTrim(GTrim); 1642 OwningPtr<InterExplodedGraphMap> AutoReleaseNMap(NMap); 1643 1644 // Find the (first) error node in the trimmed graph. We just need to consult 1645 // the node map (NMap) which maps from nodes in the original graph to nodes 1646 // in the new graph. 1647 1648 std::queue<const ExplodedNode*> WS; 1649 typedef llvm::DenseMap<const ExplodedNode*, unsigned> IndexMapTy; 1650 IndexMapTy IndexMap; 1651 1652 for (unsigned nodeIndex = 0 ; nodeIndex < nodes.size(); ++nodeIndex) { 1653 const ExplodedNode *originalNode = nodes[nodeIndex]; 1654 if (const ExplodedNode *N = NMap->getMappedNode(originalNode)) { 1655 WS.push(N); 1656 IndexMap[originalNode] = nodeIndex; 1657 } 1658 } 1659 1660 assert(!WS.empty() && "No error node found in the trimmed graph."); 1661 1662 // Create a new (third!) graph with a single path. This is the graph 1663 // that will be returned to the caller. 1664 ExplodedGraph *GNew = new ExplodedGraph(); 1665 1666 // Sometimes the trimmed graph can contain a cycle. Perform a reverse BFS 1667 // to the root node, and then construct a new graph that contains only 1668 // a single path. 1669 llvm::DenseMap<const void*,unsigned> Visited; 1670 1671 unsigned cnt = 0; 1672 const ExplodedNode *Root = 0; 1673 1674 while (!WS.empty()) { 1675 const ExplodedNode *Node = WS.front(); 1676 WS.pop(); 1677 1678 if (Visited.find(Node) != Visited.end()) 1679 continue; 1680 1681 Visited[Node] = cnt++; 1682 1683 if (Node->pred_empty()) { 1684 Root = Node; 1685 break; 1686 } 1687 1688 for (ExplodedNode::const_pred_iterator I=Node->pred_begin(), 1689 E=Node->pred_end(); I!=E; ++I) 1690 WS.push(*I); 1691 } 1692 1693 assert(Root); 1694 1695 // Now walk from the root down the BFS path, always taking the successor 1696 // with the lowest number. 1697 ExplodedNode *Last = 0, *First = 0; 1698 NodeBackMap *BM = new NodeBackMap(); 1699 unsigned NodeIndex = 0; 1700 1701 for ( const ExplodedNode *N = Root ;;) { 1702 // Lookup the number associated with the current node. 1703 llvm::DenseMap<const void*,unsigned>::iterator I = Visited.find(N); 1704 assert(I != Visited.end()); 1705 1706 // Create the equivalent node in the new graph with the same state 1707 // and location. 1708 ExplodedNode *NewN = GNew->getNode(N->getLocation(), N->getState()); 1709 1710 // Store the mapping to the original node. 1711 llvm::DenseMap<const void*, const void*>::iterator IMitr=InverseMap.find(N); 1712 assert(IMitr != InverseMap.end() && "No mapping to original node."); 1713 (*BM)[NewN] = (const ExplodedNode*) IMitr->second; 1714 1715 // Link up the new node with the previous node. 1716 if (Last) 1717 NewN->addPredecessor(Last, *GNew); 1718 1719 Last = NewN; 1720 1721 // Are we at the final node? 1722 IndexMapTy::iterator IMI = 1723 IndexMap.find((const ExplodedNode*)(IMitr->second)); 1724 if (IMI != IndexMap.end()) { 1725 First = NewN; 1726 NodeIndex = IMI->second; 1727 break; 1728 } 1729 1730 // Find the next successor node. We choose the node that is marked 1731 // with the lowest DFS number. 1732 ExplodedNode::const_succ_iterator SI = N->succ_begin(); 1733 ExplodedNode::const_succ_iterator SE = N->succ_end(); 1734 N = 0; 1735 1736 for (unsigned MinVal = 0; SI != SE; ++SI) { 1737 1738 I = Visited.find(*SI); 1739 1740 if (I == Visited.end()) 1741 continue; 1742 1743 if (!N || I->second < MinVal) { 1744 N = *SI; 1745 MinVal = I->second; 1746 } 1747 } 1748 1749 assert(N); 1750 } 1751 1752 assert(First); 1753 1754 return std::make_pair(std::make_pair(GNew, BM), 1755 std::make_pair(First, NodeIndex)); 1756} 1757 1758/// CompactPathDiagnostic - This function postprocesses a PathDiagnostic object 1759/// and collapses PathDiagosticPieces that are expanded by macros. 1760static void CompactPathDiagnostic(PathPieces &path, const SourceManager& SM) { 1761 typedef std::vector<std::pair<IntrusiveRefCntPtr<PathDiagnosticMacroPiece>, 1762 SourceLocation> > MacroStackTy; 1763 1764 typedef std::vector<IntrusiveRefCntPtr<PathDiagnosticPiece> > 1765 PiecesTy; 1766 1767 MacroStackTy MacroStack; 1768 PiecesTy Pieces; 1769 1770 for (PathPieces::const_iterator I = path.begin(), E = path.end(); 1771 I!=E; ++I) { 1772 1773 PathDiagnosticPiece *piece = I->getPtr(); 1774 1775 // Recursively compact calls. 1776 if (PathDiagnosticCallPiece *call=dyn_cast<PathDiagnosticCallPiece>(piece)){ 1777 CompactPathDiagnostic(call->path, SM); 1778 } 1779 1780 // Get the location of the PathDiagnosticPiece. 1781 const FullSourceLoc Loc = piece->getLocation().asLocation(); 1782 1783 // Determine the instantiation location, which is the location we group 1784 // related PathDiagnosticPieces. 1785 SourceLocation InstantiationLoc = Loc.isMacroID() ? 1786 SM.getExpansionLoc(Loc) : 1787 SourceLocation(); 1788 1789 if (Loc.isFileID()) { 1790 MacroStack.clear(); 1791 Pieces.push_back(piece); 1792 continue; 1793 } 1794 1795 assert(Loc.isMacroID()); 1796 1797 // Is the PathDiagnosticPiece within the same macro group? 1798 if (!MacroStack.empty() && InstantiationLoc == MacroStack.back().second) { 1799 MacroStack.back().first->subPieces.push_back(piece); 1800 continue; 1801 } 1802 1803 // We aren't in the same group. Are we descending into a new macro 1804 // or are part of an old one? 1805 IntrusiveRefCntPtr<PathDiagnosticMacroPiece> MacroGroup; 1806 1807 SourceLocation ParentInstantiationLoc = InstantiationLoc.isMacroID() ? 1808 SM.getExpansionLoc(Loc) : 1809 SourceLocation(); 1810 1811 // Walk the entire macro stack. 1812 while (!MacroStack.empty()) { 1813 if (InstantiationLoc == MacroStack.back().second) { 1814 MacroGroup = MacroStack.back().first; 1815 break; 1816 } 1817 1818 if (ParentInstantiationLoc == MacroStack.back().second) { 1819 MacroGroup = MacroStack.back().first; 1820 break; 1821 } 1822 1823 MacroStack.pop_back(); 1824 } 1825 1826 if (!MacroGroup || ParentInstantiationLoc == MacroStack.back().second) { 1827 // Create a new macro group and add it to the stack. 1828 PathDiagnosticMacroPiece *NewGroup = 1829 new PathDiagnosticMacroPiece( 1830 PathDiagnosticLocation::createSingleLocation(piece->getLocation())); 1831 1832 if (MacroGroup) 1833 MacroGroup->subPieces.push_back(NewGroup); 1834 else { 1835 assert(InstantiationLoc.isFileID()); 1836 Pieces.push_back(NewGroup); 1837 } 1838 1839 MacroGroup = NewGroup; 1840 MacroStack.push_back(std::make_pair(MacroGroup, InstantiationLoc)); 1841 } 1842 1843 // Finally, add the PathDiagnosticPiece to the group. 1844 MacroGroup->subPieces.push_back(piece); 1845 } 1846 1847 // Now take the pieces and construct a new PathDiagnostic. 1848 path.clear(); 1849 1850 for (PiecesTy::iterator I=Pieces.begin(), E=Pieces.end(); I!=E; ++I) 1851 path.push_back(*I); 1852} 1853 1854void GRBugReporter::GeneratePathDiagnostic(PathDiagnostic& PD, 1855 PathDiagnosticConsumer &PC, 1856 ArrayRef<BugReport *> &bugReports) { 1857 1858 assert(!bugReports.empty()); 1859 SmallVector<const ExplodedNode *, 10> errorNodes; 1860 for (ArrayRef<BugReport*>::iterator I = bugReports.begin(), 1861 E = bugReports.end(); I != E; ++I) { 1862 errorNodes.push_back((*I)->getErrorNode()); 1863 } 1864 1865 // Construct a new graph that contains only a single path from the error 1866 // node to a root. 1867 const std::pair<std::pair<ExplodedGraph*, NodeBackMap*>, 1868 std::pair<ExplodedNode*, unsigned> >& 1869 GPair = MakeReportGraph(&getGraph(), errorNodes); 1870 1871 // Find the BugReport with the original location. 1872 assert(GPair.second.second < bugReports.size()); 1873 BugReport *R = bugReports[GPair.second.second]; 1874 assert(R && "No original report found for sliced graph."); 1875 1876 OwningPtr<ExplodedGraph> ReportGraph(GPair.first.first); 1877 OwningPtr<NodeBackMap> BackMap(GPair.first.second); 1878 const ExplodedNode *N = GPair.second.first; 1879 1880 // Start building the path diagnostic... 1881 PathDiagnosticBuilder PDB(*this, R, BackMap.get(), &PC); 1882 1883 // Register additional node visitors. 1884 R->addVisitor(new NilReceiverBRVisitor()); 1885 R->addVisitor(new ConditionBRVisitor()); 1886 1887 BugReport::VisitorList visitors; 1888 unsigned originalReportConfigToken, finalReportConfigToken; 1889 1890 // While generating diagnostics, it's possible the visitors will decide 1891 // new symbols and regions are interesting, or add other visitors based on 1892 // the information they find. If they do, we need to regenerate the path 1893 // based on our new report configuration. 1894 do { 1895 // Get a clean copy of all the visitors. 1896 for (BugReport::visitor_iterator I = R->visitor_begin(), 1897 E = R->visitor_end(); I != E; ++I) 1898 visitors.push_back((*I)->clone()); 1899 1900 // Clear out the active path from any previous work. 1901 PD.resetPath(); 1902 originalReportConfigToken = R->getConfigurationChangeToken(); 1903 1904 // Generate the very last diagnostic piece - the piece is visible before 1905 // the trace is expanded. 1906 PathDiagnosticPiece *LastPiece = 0; 1907 for (BugReport::visitor_iterator I = visitors.begin(), E = visitors.end(); 1908 I != E; ++I) { 1909 if (PathDiagnosticPiece *Piece = (*I)->getEndPath(PDB, N, *R)) { 1910 assert (!LastPiece && 1911 "There can only be one final piece in a diagnostic."); 1912 LastPiece = Piece; 1913 } 1914 } 1915 if (!LastPiece) 1916 LastPiece = BugReporterVisitor::getDefaultEndPath(PDB, N, *R); 1917 if (LastPiece) 1918 PD.setEndOfPath(LastPiece); 1919 else 1920 return; 1921 1922 switch (PDB.getGenerationScheme()) { 1923 case PathDiagnosticConsumer::Extensive: 1924 GenerateExtensivePathDiagnostic(PD, PDB, N, visitors); 1925 break; 1926 case PathDiagnosticConsumer::Minimal: 1927 GenerateMinimalPathDiagnostic(PD, PDB, N, visitors); 1928 break; 1929 case PathDiagnosticConsumer::None: 1930 llvm_unreachable("PathDiagnosticConsumer::None should never appear here"); 1931 } 1932 1933 // Clean up the visitors we used. 1934 llvm::DeleteContainerPointers(visitors); 1935 1936 // Did anything change while generating this path? 1937 finalReportConfigToken = R->getConfigurationChangeToken(); 1938 } while(finalReportConfigToken != originalReportConfigToken); 1939 1940 // Finally, prune the diagnostic path of uninteresting stuff. 1941 if (R->shouldPrunePath()) { 1942 bool hasSomethingInteresting = RemoveUneededCalls(PD.getMutablePieces(), R); 1943 assert(hasSomethingInteresting); 1944 (void) hasSomethingInteresting; 1945 } 1946} 1947 1948void BugReporter::Register(BugType *BT) { 1949 BugTypes = F.add(BugTypes, BT); 1950} 1951 1952void BugReporter::EmitReport(BugReport* R) { 1953 // Compute the bug report's hash to determine its equivalence class. 1954 llvm::FoldingSetNodeID ID; 1955 R->Profile(ID); 1956 1957 // Lookup the equivance class. If there isn't one, create it. 1958 BugType& BT = R->getBugType(); 1959 Register(&BT); 1960 void *InsertPos; 1961 BugReportEquivClass* EQ = EQClasses.FindNodeOrInsertPos(ID, InsertPos); 1962 1963 if (!EQ) { 1964 EQ = new BugReportEquivClass(R); 1965 EQClasses.InsertNode(EQ, InsertPos); 1966 EQClassesVector.push_back(EQ); 1967 } 1968 else 1969 EQ->AddReport(R); 1970} 1971 1972 1973//===----------------------------------------------------------------------===// 1974// Emitting reports in equivalence classes. 1975//===----------------------------------------------------------------------===// 1976 1977namespace { 1978struct FRIEC_WLItem { 1979 const ExplodedNode *N; 1980 ExplodedNode::const_succ_iterator I, E; 1981 1982 FRIEC_WLItem(const ExplodedNode *n) 1983 : N(n), I(N->succ_begin()), E(N->succ_end()) {} 1984}; 1985} 1986 1987static BugReport * 1988FindReportInEquivalenceClass(BugReportEquivClass& EQ, 1989 SmallVectorImpl<BugReport*> &bugReports) { 1990 1991 BugReportEquivClass::iterator I = EQ.begin(), E = EQ.end(); 1992 assert(I != E); 1993 BugType& BT = I->getBugType(); 1994 1995 // If we don't need to suppress any of the nodes because they are 1996 // post-dominated by a sink, simply add all the nodes in the equivalence class 1997 // to 'Nodes'. Any of the reports will serve as a "representative" report. 1998 if (!BT.isSuppressOnSink()) { 1999 BugReport *R = I; 2000 for (BugReportEquivClass::iterator I=EQ.begin(), E=EQ.end(); I!=E; ++I) { 2001 const ExplodedNode *N = I->getErrorNode(); 2002 if (N) { 2003 R = I; 2004 bugReports.push_back(R); 2005 } 2006 } 2007 return R; 2008 } 2009 2010 // For bug reports that should be suppressed when all paths are post-dominated 2011 // by a sink node, iterate through the reports in the equivalence class 2012 // until we find one that isn't post-dominated (if one exists). We use a 2013 // DFS traversal of the ExplodedGraph to find a non-sink node. We could write 2014 // this as a recursive function, but we don't want to risk blowing out the 2015 // stack for very long paths. 2016 BugReport *exampleReport = 0; 2017 2018 for (; I != E; ++I) { 2019 const ExplodedNode *errorNode = I->getErrorNode(); 2020 2021 if (!errorNode) 2022 continue; 2023 if (errorNode->isSink()) { 2024 llvm_unreachable( 2025 "BugType::isSuppressSink() should not be 'true' for sink end nodes"); 2026 } 2027 // No successors? By definition this nodes isn't post-dominated by a sink. 2028 if (errorNode->succ_empty()) { 2029 bugReports.push_back(I); 2030 if (!exampleReport) 2031 exampleReport = I; 2032 continue; 2033 } 2034 2035 // At this point we know that 'N' is not a sink and it has at least one 2036 // successor. Use a DFS worklist to find a non-sink end-of-path node. 2037 typedef FRIEC_WLItem WLItem; 2038 typedef SmallVector<WLItem, 10> DFSWorkList; 2039 llvm::DenseMap<const ExplodedNode *, unsigned> Visited; 2040 2041 DFSWorkList WL; 2042 WL.push_back(errorNode); 2043 Visited[errorNode] = 1; 2044 2045 while (!WL.empty()) { 2046 WLItem &WI = WL.back(); 2047 assert(!WI.N->succ_empty()); 2048 2049 for (; WI.I != WI.E; ++WI.I) { 2050 const ExplodedNode *Succ = *WI.I; 2051 // End-of-path node? 2052 if (Succ->succ_empty()) { 2053 // If we found an end-of-path node that is not a sink. 2054 if (!Succ->isSink()) { 2055 bugReports.push_back(I); 2056 if (!exampleReport) 2057 exampleReport = I; 2058 WL.clear(); 2059 break; 2060 } 2061 // Found a sink? Continue on to the next successor. 2062 continue; 2063 } 2064 // Mark the successor as visited. If it hasn't been explored, 2065 // enqueue it to the DFS worklist. 2066 unsigned &mark = Visited[Succ]; 2067 if (!mark) { 2068 mark = 1; 2069 WL.push_back(Succ); 2070 break; 2071 } 2072 } 2073 2074 // The worklist may have been cleared at this point. First 2075 // check if it is empty before checking the last item. 2076 if (!WL.empty() && &WL.back() == &WI) 2077 WL.pop_back(); 2078 } 2079 } 2080 2081 // ExampleReport will be NULL if all the nodes in the equivalence class 2082 // were post-dominated by sinks. 2083 return exampleReport; 2084} 2085 2086void BugReporter::FlushReport(BugReportEquivClass& EQ) { 2087 SmallVector<BugReport*, 10> bugReports; 2088 BugReport *exampleReport = FindReportInEquivalenceClass(EQ, bugReports); 2089 if (exampleReport) { 2090 const PathDiagnosticConsumers &C = getPathDiagnosticConsumers(); 2091 for (PathDiagnosticConsumers::const_iterator I=C.begin(), 2092 E=C.end(); I != E; ++I) { 2093 FlushReport(exampleReport, **I, bugReports); 2094 } 2095 } 2096} 2097 2098void BugReporter::FlushReport(BugReport *exampleReport, 2099 PathDiagnosticConsumer &PD, 2100 ArrayRef<BugReport*> bugReports) { 2101 2102 // FIXME: Make sure we use the 'R' for the path that was actually used. 2103 // Probably doesn't make a difference in practice. 2104 BugType& BT = exampleReport->getBugType(); 2105 2106 OwningPtr<PathDiagnostic> 2107 D(new PathDiagnostic(exampleReport->getDeclWithIssue(), 2108 exampleReport->getBugType().getName(), 2109 exampleReport->getDescription(), 2110 exampleReport->getShortDescription(/*Fallback=*/false), 2111 BT.getCategory())); 2112 2113 // Generate the full path diagnostic, using the generation scheme 2114 // specified by the PathDiagnosticConsumer. 2115 if (PD.getGenerationScheme() != PathDiagnosticConsumer::None) { 2116 if (!bugReports.empty()) 2117 GeneratePathDiagnostic(*D.get(), PD, bugReports); 2118 } 2119 2120 // If the path is empty, generate a single step path with the location 2121 // of the issue. 2122 if (D->path.empty()) { 2123 PathDiagnosticLocation L = exampleReport->getLocation(getSourceManager()); 2124 PathDiagnosticPiece *piece = 2125 new PathDiagnosticEventPiece(L, exampleReport->getDescription()); 2126 BugReport::ranges_iterator Beg, End; 2127 llvm::tie(Beg, End) = exampleReport->getRanges(); 2128 for ( ; Beg != End; ++Beg) 2129 piece->addRange(*Beg); 2130 D->setEndOfPath(piece); 2131 } 2132 2133 // Get the meta data. 2134 const BugReport::ExtraTextList &Meta = exampleReport->getExtraText(); 2135 for (BugReport::ExtraTextList::const_iterator i = Meta.begin(), 2136 e = Meta.end(); i != e; ++i) { 2137 D->addMeta(*i); 2138 } 2139 2140 PD.HandlePathDiagnostic(D.take()); 2141} 2142 2143void BugReporter::EmitBasicReport(const Decl *DeclWithIssue, 2144 StringRef name, 2145 StringRef category, 2146 StringRef str, PathDiagnosticLocation Loc, 2147 SourceRange* RBeg, unsigned NumRanges) { 2148 2149 // 'BT' is owned by BugReporter. 2150 BugType *BT = getBugTypeForName(name, category); 2151 BugReport *R = new BugReport(*BT, str, Loc); 2152 R->setDeclWithIssue(DeclWithIssue); 2153 for ( ; NumRanges > 0 ; --NumRanges, ++RBeg) R->addRange(*RBeg); 2154 EmitReport(R); 2155} 2156 2157BugType *BugReporter::getBugTypeForName(StringRef name, 2158 StringRef category) { 2159 SmallString<136> fullDesc; 2160 llvm::raw_svector_ostream(fullDesc) << name << ":" << category; 2161 llvm::StringMapEntry<BugType *> & 2162 entry = StrBugTypes.GetOrCreateValue(fullDesc); 2163 BugType *BT = entry.getValue(); 2164 if (!BT) { 2165 BT = new BugType(name, category); 2166 entry.setValue(BT); 2167 } 2168 return BT; 2169} 2170