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