BugReporter.cpp revision d3d0dcfbf784c828c2f07384fd6a3401b0cd4e9e
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#define DEBUG_TYPE "BugReporter" 16 17#include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h" 18#include "clang/AST/ASTContext.h" 19#include "clang/AST/DeclObjC.h" 20#include "clang/AST/Expr.h" 21#include "clang/AST/ExprCXX.h" 22#include "clang/AST/ParentMap.h" 23#include "clang/AST/StmtObjC.h" 24#include "clang/AST/StmtCXX.h" 25#include "clang/Analysis/CFG.h" 26#include "clang/Analysis/ProgramPoint.h" 27#include "clang/Basic/SourceManager.h" 28#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h" 29#include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h" 30#include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h" 31#include "llvm/ADT/DenseMap.h" 32#include "llvm/ADT/IntrusiveRefCntPtr.h" 33#include "llvm/ADT/OwningPtr.h" 34#include "llvm/ADT/STLExtras.h" 35#include "llvm/ADT/SmallString.h" 36#include "llvm/ADT/Statistic.h" 37#include "llvm/Support/raw_ostream.h" 38#include <queue> 39 40using namespace clang; 41using namespace ento; 42 43STATISTIC(MaxBugClassSize, 44 "The maximum number of bug reports in the same equivalence class"); 45STATISTIC(MaxValidBugClassSize, 46 "The maximum number of bug reports in the same equivalence class " 47 "where at least one report is valid (not suppressed)"); 48 49BugReporterVisitor::~BugReporterVisitor() {} 50 51void BugReporterContext::anchor() {} 52 53//===----------------------------------------------------------------------===// 54// Helper routines for walking the ExplodedGraph and fetching statements. 55//===----------------------------------------------------------------------===// 56 57static const Stmt *GetPreviousStmt(const ExplodedNode *N) { 58 for (N = N->getFirstPred(); N; N = N->getFirstPred()) 59 if (const Stmt *S = PathDiagnosticLocation::getStmt(N)) 60 return S; 61 62 return 0; 63} 64 65static inline const Stmt* 66GetCurrentOrPreviousStmt(const ExplodedNode *N) { 67 if (const Stmt *S = PathDiagnosticLocation::getStmt(N)) 68 return S; 69 70 return GetPreviousStmt(N); 71} 72 73//===----------------------------------------------------------------------===// 74// Diagnostic cleanup. 75//===----------------------------------------------------------------------===// 76 77static PathDiagnosticEventPiece * 78eventsDescribeSameCondition(PathDiagnosticEventPiece *X, 79 PathDiagnosticEventPiece *Y) { 80 // Prefer diagnostics that come from ConditionBRVisitor over 81 // those that came from TrackConstraintBRVisitor. 82 const void *tagPreferred = ConditionBRVisitor::getTag(); 83 const void *tagLesser = TrackConstraintBRVisitor::getTag(); 84 85 if (X->getLocation() != Y->getLocation()) 86 return 0; 87 88 if (X->getTag() == tagPreferred && Y->getTag() == tagLesser) 89 return X; 90 91 if (Y->getTag() == tagPreferred && X->getTag() == tagLesser) 92 return Y; 93 94 return 0; 95} 96 97/// An optimization pass over PathPieces that removes redundant diagnostics 98/// generated by both ConditionBRVisitor and TrackConstraintBRVisitor. Both 99/// BugReporterVisitors use different methods to generate diagnostics, with 100/// one capable of emitting diagnostics in some cases but not in others. This 101/// can lead to redundant diagnostic pieces at the same point in a path. 102static void removeRedundantMsgs(PathPieces &path) { 103 unsigned N = path.size(); 104 if (N < 2) 105 return; 106 // NOTE: this loop intentionally is not using an iterator. Instead, we 107 // are streaming the path and modifying it in place. This is done by 108 // grabbing the front, processing it, and if we decide to keep it append 109 // it to the end of the path. The entire path is processed in this way. 110 for (unsigned i = 0; i < N; ++i) { 111 IntrusiveRefCntPtr<PathDiagnosticPiece> piece(path.front()); 112 path.pop_front(); 113 114 switch (piece->getKind()) { 115 case clang::ento::PathDiagnosticPiece::Call: 116 removeRedundantMsgs(cast<PathDiagnosticCallPiece>(piece)->path); 117 break; 118 case clang::ento::PathDiagnosticPiece::Macro: 119 removeRedundantMsgs(cast<PathDiagnosticMacroPiece>(piece)->subPieces); 120 break; 121 case clang::ento::PathDiagnosticPiece::ControlFlow: 122 break; 123 case clang::ento::PathDiagnosticPiece::Event: { 124 if (i == N-1) 125 break; 126 127 if (PathDiagnosticEventPiece *nextEvent = 128 dyn_cast<PathDiagnosticEventPiece>(path.front().getPtr())) { 129 PathDiagnosticEventPiece *event = 130 cast<PathDiagnosticEventPiece>(piece); 131 // Check to see if we should keep one of the two pieces. If we 132 // come up with a preference, record which piece to keep, and consume 133 // another piece from the path. 134 if (PathDiagnosticEventPiece *pieceToKeep = 135 eventsDescribeSameCondition(event, nextEvent)) { 136 piece = pieceToKeep; 137 path.pop_front(); 138 ++i; 139 } 140 } 141 break; 142 } 143 } 144 path.push_back(piece); 145 } 146} 147 148/// A map from PathDiagnosticPiece to the LocationContext of the inlined 149/// function call it represents. 150typedef llvm::DenseMap<const PathPieces *, const LocationContext *> 151 LocationContextMap; 152 153/// Recursively scan through a path and prune out calls and macros pieces 154/// that aren't needed. Return true if afterwards the path contains 155/// "interesting stuff" which means it shouldn't be pruned from the parent path. 156static bool removeUnneededCalls(PathPieces &pieces, BugReport *R, 157 LocationContextMap &LCM) { 158 bool containsSomethingInteresting = false; 159 const unsigned N = pieces.size(); 160 161 for (unsigned i = 0 ; i < N ; ++i) { 162 // Remove the front piece from the path. If it is still something we 163 // want to keep once we are done, we will push it back on the end. 164 IntrusiveRefCntPtr<PathDiagnosticPiece> piece(pieces.front()); 165 pieces.pop_front(); 166 167 switch (piece->getKind()) { 168 case PathDiagnosticPiece::Call: { 169 PathDiagnosticCallPiece *call = cast<PathDiagnosticCallPiece>(piece); 170 // Check if the location context is interesting. 171 assert(LCM.count(&call->path)); 172 if (R->isInteresting(LCM[&call->path])) { 173 containsSomethingInteresting = true; 174 break; 175 } 176 177 if (!removeUnneededCalls(call->path, R, LCM)) 178 continue; 179 180 containsSomethingInteresting = true; 181 break; 182 } 183 case PathDiagnosticPiece::Macro: { 184 PathDiagnosticMacroPiece *macro = cast<PathDiagnosticMacroPiece>(piece); 185 if (!removeUnneededCalls(macro->subPieces, R, LCM)) 186 continue; 187 containsSomethingInteresting = true; 188 break; 189 } 190 case PathDiagnosticPiece::Event: { 191 PathDiagnosticEventPiece *event = cast<PathDiagnosticEventPiece>(piece); 192 193 // We never throw away an event, but we do throw it away wholesale 194 // as part of a path if we throw the entire path away. 195 containsSomethingInteresting |= !event->isPrunable(); 196 break; 197 } 198 case PathDiagnosticPiece::ControlFlow: 199 break; 200 } 201 202 pieces.push_back(piece); 203 } 204 205 return containsSomethingInteresting; 206} 207 208/// Returns true if the given decl has been implicitly given a body, either by 209/// the analyzer or by the compiler proper. 210static bool hasImplicitBody(const Decl *D) { 211 assert(D); 212 return D->isImplicit() || !D->hasBody(); 213} 214 215/// Recursively scan through a path and make sure that all call pieces have 216/// valid locations. 217static void adjustCallLocations(PathPieces &Pieces, 218 PathDiagnosticLocation *LastCallLocation = 0) { 219 for (PathPieces::iterator I = Pieces.begin(), E = Pieces.end(); I != E; ++I) { 220 PathDiagnosticCallPiece *Call = dyn_cast<PathDiagnosticCallPiece>(*I); 221 222 if (!Call) { 223 assert((*I)->getLocation().asLocation().isValid()); 224 continue; 225 } 226 227 if (LastCallLocation) { 228 bool CallerIsImplicit = hasImplicitBody(Call->getCaller()); 229 if (CallerIsImplicit || !Call->callEnter.asLocation().isValid()) 230 Call->callEnter = *LastCallLocation; 231 if (CallerIsImplicit || !Call->callReturn.asLocation().isValid()) 232 Call->callReturn = *LastCallLocation; 233 } 234 235 // Recursively clean out the subclass. Keep this call around if 236 // it contains any informative diagnostics. 237 PathDiagnosticLocation *ThisCallLocation; 238 if (Call->callEnterWithin.asLocation().isValid() && 239 !hasImplicitBody(Call->getCallee())) 240 ThisCallLocation = &Call->callEnterWithin; 241 else 242 ThisCallLocation = &Call->callEnter; 243 244 assert(ThisCallLocation && "Outermost call has an invalid location"); 245 adjustCallLocations(Call->path, ThisCallLocation); 246 } 247} 248 249/// Remove edges in and out of C++ default initializer expressions. These are 250/// for fields that have in-class initializers, as opposed to being initialized 251/// explicitly in a constructor or braced list. 252static void removeEdgesToDefaultInitializers(PathPieces &Pieces) { 253 for (PathPieces::iterator I = Pieces.begin(), E = Pieces.end(); I != E;) { 254 if (PathDiagnosticCallPiece *C = dyn_cast<PathDiagnosticCallPiece>(*I)) 255 removeEdgesToDefaultInitializers(C->path); 256 257 if (PathDiagnosticMacroPiece *M = dyn_cast<PathDiagnosticMacroPiece>(*I)) 258 removeEdgesToDefaultInitializers(M->subPieces); 259 260 if (PathDiagnosticControlFlowPiece *CF = 261 dyn_cast<PathDiagnosticControlFlowPiece>(*I)) { 262 const Stmt *Start = CF->getStartLocation().asStmt(); 263 const Stmt *End = CF->getEndLocation().asStmt(); 264 if (Start && isa<CXXDefaultInitExpr>(Start)) { 265 I = Pieces.erase(I); 266 continue; 267 } else if (End && isa<CXXDefaultInitExpr>(End)) { 268 PathPieces::iterator Next = llvm::next(I); 269 if (Next != E) { 270 if (PathDiagnosticControlFlowPiece *NextCF = 271 dyn_cast<PathDiagnosticControlFlowPiece>(*Next)) { 272 NextCF->setStartLocation(CF->getStartLocation()); 273 } 274 } 275 I = Pieces.erase(I); 276 continue; 277 } 278 } 279 280 I++; 281 } 282} 283 284/// Remove all pieces with invalid locations as these cannot be serialized. 285/// We might have pieces with invalid locations as a result of inlining Body 286/// Farm generated functions. 287static void removePiecesWithInvalidLocations(PathPieces &Pieces) { 288 for (PathPieces::iterator I = Pieces.begin(), E = Pieces.end(); I != E;) { 289 if (PathDiagnosticCallPiece *C = dyn_cast<PathDiagnosticCallPiece>(*I)) 290 removePiecesWithInvalidLocations(C->path); 291 292 if (PathDiagnosticMacroPiece *M = dyn_cast<PathDiagnosticMacroPiece>(*I)) 293 removePiecesWithInvalidLocations(M->subPieces); 294 295 if (!(*I)->getLocation().isValid() || 296 !(*I)->getLocation().asLocation().isValid()) { 297 I = Pieces.erase(I); 298 continue; 299 } 300 I++; 301 } 302} 303 304//===----------------------------------------------------------------------===// 305// PathDiagnosticBuilder and its associated routines and helper objects. 306//===----------------------------------------------------------------------===// 307 308namespace { 309class NodeMapClosure : public BugReport::NodeResolver { 310 InterExplodedGraphMap &M; 311public: 312 NodeMapClosure(InterExplodedGraphMap &m) : M(m) {} 313 314 const ExplodedNode *getOriginalNode(const ExplodedNode *N) { 315 return M.lookup(N); 316 } 317}; 318 319class PathDiagnosticBuilder : public BugReporterContext { 320 BugReport *R; 321 PathDiagnosticConsumer *PDC; 322 NodeMapClosure NMC; 323public: 324 const LocationContext *LC; 325 326 PathDiagnosticBuilder(GRBugReporter &br, 327 BugReport *r, InterExplodedGraphMap &Backmap, 328 PathDiagnosticConsumer *pdc) 329 : BugReporterContext(br), 330 R(r), PDC(pdc), NMC(Backmap), LC(r->getErrorNode()->getLocationContext()) 331 {} 332 333 PathDiagnosticLocation ExecutionContinues(const ExplodedNode *N); 334 335 PathDiagnosticLocation ExecutionContinues(llvm::raw_string_ostream &os, 336 const ExplodedNode *N); 337 338 BugReport *getBugReport() { return R; } 339 340 Decl const &getCodeDecl() { return R->getErrorNode()->getCodeDecl(); } 341 342 ParentMap& getParentMap() { return LC->getParentMap(); } 343 344 const Stmt *getParent(const Stmt *S) { 345 return getParentMap().getParent(S); 346 } 347 348 virtual NodeMapClosure& getNodeResolver() { return NMC; } 349 350 PathDiagnosticLocation getEnclosingStmtLocation(const Stmt *S); 351 352 PathDiagnosticConsumer::PathGenerationScheme getGenerationScheme() const { 353 return PDC ? PDC->getGenerationScheme() : PathDiagnosticConsumer::Extensive; 354 } 355 356 bool supportsLogicalOpControlFlow() const { 357 return PDC ? PDC->supportsLogicalOpControlFlow() : true; 358 } 359}; 360} // end anonymous namespace 361 362PathDiagnosticLocation 363PathDiagnosticBuilder::ExecutionContinues(const ExplodedNode *N) { 364 if (const Stmt *S = PathDiagnosticLocation::getNextStmt(N)) 365 return PathDiagnosticLocation(S, getSourceManager(), LC); 366 367 return PathDiagnosticLocation::createDeclEnd(N->getLocationContext(), 368 getSourceManager()); 369} 370 371PathDiagnosticLocation 372PathDiagnosticBuilder::ExecutionContinues(llvm::raw_string_ostream &os, 373 const ExplodedNode *N) { 374 375 // Slow, but probably doesn't matter. 376 if (os.str().empty()) 377 os << ' '; 378 379 const PathDiagnosticLocation &Loc = ExecutionContinues(N); 380 381 if (Loc.asStmt()) 382 os << "Execution continues on line " 383 << getSourceManager().getExpansionLineNumber(Loc.asLocation()) 384 << '.'; 385 else { 386 os << "Execution jumps to the end of the "; 387 const Decl *D = N->getLocationContext()->getDecl(); 388 if (isa<ObjCMethodDecl>(D)) 389 os << "method"; 390 else if (isa<FunctionDecl>(D)) 391 os << "function"; 392 else { 393 assert(isa<BlockDecl>(D)); 394 os << "anonymous block"; 395 } 396 os << '.'; 397 } 398 399 return Loc; 400} 401 402static const Stmt *getEnclosingParent(const Stmt *S, const ParentMap &PM) { 403 if (isa<Expr>(S) && PM.isConsumedExpr(cast<Expr>(S))) 404 return PM.getParentIgnoreParens(S); 405 406 const Stmt *Parent = PM.getParentIgnoreParens(S); 407 if (!Parent) 408 return 0; 409 410 switch (Parent->getStmtClass()) { 411 case Stmt::ForStmtClass: 412 case Stmt::DoStmtClass: 413 case Stmt::WhileStmtClass: 414 case Stmt::ObjCForCollectionStmtClass: 415 case Stmt::CXXForRangeStmtClass: 416 return Parent; 417 default: 418 break; 419 } 420 421 return 0; 422} 423 424static PathDiagnosticLocation 425getEnclosingStmtLocation(const Stmt *S, SourceManager &SMgr, const ParentMap &P, 426 const LocationContext *LC, bool allowNestedContexts) { 427 if (!S) 428 return PathDiagnosticLocation(); 429 430 while (const Stmt *Parent = getEnclosingParent(S, P)) { 431 switch (Parent->getStmtClass()) { 432 case Stmt::BinaryOperatorClass: { 433 const BinaryOperator *B = cast<BinaryOperator>(Parent); 434 if (B->isLogicalOp()) 435 return PathDiagnosticLocation(allowNestedContexts ? B : S, SMgr, LC); 436 break; 437 } 438 case Stmt::CompoundStmtClass: 439 case Stmt::StmtExprClass: 440 return PathDiagnosticLocation(S, SMgr, LC); 441 case Stmt::ChooseExprClass: 442 // Similar to '?' if we are referring to condition, just have the edge 443 // point to the entire choose expression. 444 if (allowNestedContexts || cast<ChooseExpr>(Parent)->getCond() == S) 445 return PathDiagnosticLocation(Parent, SMgr, LC); 446 else 447 return PathDiagnosticLocation(S, SMgr, LC); 448 case Stmt::BinaryConditionalOperatorClass: 449 case Stmt::ConditionalOperatorClass: 450 // For '?', if we are referring to condition, just have the edge point 451 // to the entire '?' expression. 452 if (allowNestedContexts || 453 cast<AbstractConditionalOperator>(Parent)->getCond() == S) 454 return PathDiagnosticLocation(Parent, SMgr, LC); 455 else 456 return PathDiagnosticLocation(S, SMgr, LC); 457 case Stmt::CXXForRangeStmtClass: 458 if (cast<CXXForRangeStmt>(Parent)->getBody() == S) 459 return PathDiagnosticLocation(S, SMgr, LC); 460 break; 461 case Stmt::DoStmtClass: 462 return PathDiagnosticLocation(S, SMgr, LC); 463 case Stmt::ForStmtClass: 464 if (cast<ForStmt>(Parent)->getBody() == S) 465 return PathDiagnosticLocation(S, SMgr, LC); 466 break; 467 case Stmt::IfStmtClass: 468 if (cast<IfStmt>(Parent)->getCond() != S) 469 return PathDiagnosticLocation(S, SMgr, LC); 470 break; 471 case Stmt::ObjCForCollectionStmtClass: 472 if (cast<ObjCForCollectionStmt>(Parent)->getBody() == S) 473 return PathDiagnosticLocation(S, SMgr, LC); 474 break; 475 case Stmt::WhileStmtClass: 476 if (cast<WhileStmt>(Parent)->getCond() != S) 477 return PathDiagnosticLocation(S, SMgr, LC); 478 break; 479 default: 480 break; 481 } 482 483 S = Parent; 484 } 485 486 assert(S && "Cannot have null Stmt for PathDiagnosticLocation"); 487 488 return PathDiagnosticLocation(S, SMgr, LC); 489} 490 491PathDiagnosticLocation 492PathDiagnosticBuilder::getEnclosingStmtLocation(const Stmt *S) { 493 assert(S && "Null Stmt passed to getEnclosingStmtLocation"); 494 return ::getEnclosingStmtLocation(S, getSourceManager(), getParentMap(), LC, 495 /*allowNestedContexts=*/false); 496} 497 498//===----------------------------------------------------------------------===// 499// "Visitors only" path diagnostic generation algorithm. 500//===----------------------------------------------------------------------===// 501static bool GenerateVisitorsOnlyPathDiagnostic(PathDiagnostic &PD, 502 PathDiagnosticBuilder &PDB, 503 const ExplodedNode *N, 504 ArrayRef<BugReporterVisitor *> visitors) { 505 // All path generation skips the very first node (the error node). 506 // This is because there is special handling for the end-of-path note. 507 N = N->getFirstPred(); 508 if (!N) 509 return true; 510 511 BugReport *R = PDB.getBugReport(); 512 while (const ExplodedNode *Pred = N->getFirstPred()) { 513 for (ArrayRef<BugReporterVisitor *>::iterator I = visitors.begin(), 514 E = visitors.end(); 515 I != E; ++I) { 516 // Visit all the node pairs, but throw the path pieces away. 517 PathDiagnosticPiece *Piece = (*I)->VisitNode(N, Pred, PDB, *R); 518 delete Piece; 519 } 520 521 N = Pred; 522 } 523 524 return R->isValid(); 525} 526 527//===----------------------------------------------------------------------===// 528// "Minimal" path diagnostic generation algorithm. 529//===----------------------------------------------------------------------===// 530typedef std::pair<PathDiagnosticCallPiece*, const ExplodedNode*> StackDiagPair; 531typedef SmallVector<StackDiagPair, 6> StackDiagVector; 532 533static void updateStackPiecesWithMessage(PathDiagnosticPiece *P, 534 StackDiagVector &CallStack) { 535 // If the piece contains a special message, add it to all the call 536 // pieces on the active stack. 537 if (PathDiagnosticEventPiece *ep = 538 dyn_cast<PathDiagnosticEventPiece>(P)) { 539 540 if (ep->hasCallStackHint()) 541 for (StackDiagVector::iterator I = CallStack.begin(), 542 E = CallStack.end(); I != E; ++I) { 543 PathDiagnosticCallPiece *CP = I->first; 544 const ExplodedNode *N = I->second; 545 std::string stackMsg = ep->getCallStackMessage(N); 546 547 // The last message on the path to final bug is the most important 548 // one. Since we traverse the path backwards, do not add the message 549 // if one has been previously added. 550 if (!CP->hasCallStackMessage()) 551 CP->setCallStackMessage(stackMsg); 552 } 553 } 554} 555 556static void CompactPathDiagnostic(PathPieces &path, const SourceManager& SM); 557 558static bool GenerateMinimalPathDiagnostic(PathDiagnostic& PD, 559 PathDiagnosticBuilder &PDB, 560 const ExplodedNode *N, 561 LocationContextMap &LCM, 562 ArrayRef<BugReporterVisitor *> visitors) { 563 564 SourceManager& SMgr = PDB.getSourceManager(); 565 const LocationContext *LC = PDB.LC; 566 const ExplodedNode *NextNode = N->pred_empty() 567 ? NULL : *(N->pred_begin()); 568 569 StackDiagVector CallStack; 570 571 while (NextNode) { 572 N = NextNode; 573 PDB.LC = N->getLocationContext(); 574 NextNode = N->getFirstPred(); 575 576 ProgramPoint P = N->getLocation(); 577 578 do { 579 if (Optional<CallExitEnd> CE = P.getAs<CallExitEnd>()) { 580 PathDiagnosticCallPiece *C = 581 PathDiagnosticCallPiece::construct(N, *CE, SMgr); 582 // Record the mapping from call piece to LocationContext. 583 LCM[&C->path] = CE->getCalleeContext(); 584 PD.getActivePath().push_front(C); 585 PD.pushActivePath(&C->path); 586 CallStack.push_back(StackDiagPair(C, N)); 587 break; 588 } 589 590 if (Optional<CallEnter> CE = P.getAs<CallEnter>()) { 591 // Flush all locations, and pop the active path. 592 bool VisitedEntireCall = PD.isWithinCall(); 593 PD.popActivePath(); 594 595 // Either we just added a bunch of stuff to the top-level path, or 596 // we have a previous CallExitEnd. If the former, it means that the 597 // path terminated within a function call. We must then take the 598 // current contents of the active path and place it within 599 // a new PathDiagnosticCallPiece. 600 PathDiagnosticCallPiece *C; 601 if (VisitedEntireCall) { 602 C = cast<PathDiagnosticCallPiece>(PD.getActivePath().front()); 603 } else { 604 const Decl *Caller = CE->getLocationContext()->getDecl(); 605 C = PathDiagnosticCallPiece::construct(PD.getActivePath(), Caller); 606 // Record the mapping from call piece to LocationContext. 607 LCM[&C->path] = CE->getCalleeContext(); 608 } 609 610 C->setCallee(*CE, SMgr); 611 if (!CallStack.empty()) { 612 assert(CallStack.back().first == C); 613 CallStack.pop_back(); 614 } 615 break; 616 } 617 618 if (Optional<BlockEdge> BE = P.getAs<BlockEdge>()) { 619 const CFGBlock *Src = BE->getSrc(); 620 const CFGBlock *Dst = BE->getDst(); 621 const Stmt *T = Src->getTerminator(); 622 623 if (!T) 624 break; 625 626 PathDiagnosticLocation Start = 627 PathDiagnosticLocation::createBegin(T, SMgr, 628 N->getLocationContext()); 629 630 switch (T->getStmtClass()) { 631 default: 632 break; 633 634 case Stmt::GotoStmtClass: 635 case Stmt::IndirectGotoStmtClass: { 636 const Stmt *S = PathDiagnosticLocation::getNextStmt(N); 637 638 if (!S) 639 break; 640 641 std::string sbuf; 642 llvm::raw_string_ostream os(sbuf); 643 const PathDiagnosticLocation &End = PDB.getEnclosingStmtLocation(S); 644 645 os << "Control jumps to line " 646 << End.asLocation().getExpansionLineNumber(); 647 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece( 648 Start, End, os.str())); 649 break; 650 } 651 652 case Stmt::SwitchStmtClass: { 653 // Figure out what case arm we took. 654 std::string sbuf; 655 llvm::raw_string_ostream os(sbuf); 656 657 if (const Stmt *S = Dst->getLabel()) { 658 PathDiagnosticLocation End(S, SMgr, LC); 659 660 switch (S->getStmtClass()) { 661 default: 662 os << "No cases match in the switch statement. " 663 "Control jumps to line " 664 << End.asLocation().getExpansionLineNumber(); 665 break; 666 case Stmt::DefaultStmtClass: 667 os << "Control jumps to the 'default' case at line " 668 << End.asLocation().getExpansionLineNumber(); 669 break; 670 671 case Stmt::CaseStmtClass: { 672 os << "Control jumps to 'case "; 673 const CaseStmt *Case = cast<CaseStmt>(S); 674 const Expr *LHS = Case->getLHS()->IgnoreParenCasts(); 675 676 // Determine if it is an enum. 677 bool GetRawInt = true; 678 679 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(LHS)) { 680 // FIXME: Maybe this should be an assertion. Are there cases 681 // were it is not an EnumConstantDecl? 682 const EnumConstantDecl *D = 683 dyn_cast<EnumConstantDecl>(DR->getDecl()); 684 685 if (D) { 686 GetRawInt = false; 687 os << *D; 688 } 689 } 690 691 if (GetRawInt) 692 os << LHS->EvaluateKnownConstInt(PDB.getASTContext()); 693 694 os << ":' at line " 695 << End.asLocation().getExpansionLineNumber(); 696 break; 697 } 698 } 699 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece( 700 Start, End, os.str())); 701 } 702 else { 703 os << "'Default' branch taken. "; 704 const PathDiagnosticLocation &End = PDB.ExecutionContinues(os, N); 705 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece( 706 Start, End, os.str())); 707 } 708 709 break; 710 } 711 712 case Stmt::BreakStmtClass: 713 case Stmt::ContinueStmtClass: { 714 std::string sbuf; 715 llvm::raw_string_ostream os(sbuf); 716 PathDiagnosticLocation End = PDB.ExecutionContinues(os, N); 717 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece( 718 Start, End, os.str())); 719 break; 720 } 721 722 // Determine control-flow for ternary '?'. 723 case Stmt::BinaryConditionalOperatorClass: 724 case Stmt::ConditionalOperatorClass: { 725 std::string sbuf; 726 llvm::raw_string_ostream os(sbuf); 727 os << "'?' condition is "; 728 729 if (*(Src->succ_begin()+1) == Dst) 730 os << "false"; 731 else 732 os << "true"; 733 734 PathDiagnosticLocation End = PDB.ExecutionContinues(N); 735 736 if (const Stmt *S = End.asStmt()) 737 End = PDB.getEnclosingStmtLocation(S); 738 739 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece( 740 Start, End, os.str())); 741 break; 742 } 743 744 // Determine control-flow for short-circuited '&&' and '||'. 745 case Stmt::BinaryOperatorClass: { 746 if (!PDB.supportsLogicalOpControlFlow()) 747 break; 748 749 const BinaryOperator *B = cast<BinaryOperator>(T); 750 std::string sbuf; 751 llvm::raw_string_ostream os(sbuf); 752 os << "Left side of '"; 753 754 if (B->getOpcode() == BO_LAnd) { 755 os << "&&" << "' is "; 756 757 if (*(Src->succ_begin()+1) == Dst) { 758 os << "false"; 759 PathDiagnosticLocation End(B->getLHS(), SMgr, LC); 760 PathDiagnosticLocation Start = 761 PathDiagnosticLocation::createOperatorLoc(B, SMgr); 762 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece( 763 Start, End, os.str())); 764 } 765 else { 766 os << "true"; 767 PathDiagnosticLocation Start(B->getLHS(), SMgr, LC); 768 PathDiagnosticLocation End = PDB.ExecutionContinues(N); 769 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece( 770 Start, End, os.str())); 771 } 772 } 773 else { 774 assert(B->getOpcode() == BO_LOr); 775 os << "||" << "' is "; 776 777 if (*(Src->succ_begin()+1) == Dst) { 778 os << "false"; 779 PathDiagnosticLocation Start(B->getLHS(), SMgr, LC); 780 PathDiagnosticLocation End = PDB.ExecutionContinues(N); 781 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece( 782 Start, End, os.str())); 783 } 784 else { 785 os << "true"; 786 PathDiagnosticLocation End(B->getLHS(), SMgr, LC); 787 PathDiagnosticLocation Start = 788 PathDiagnosticLocation::createOperatorLoc(B, SMgr); 789 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece( 790 Start, End, os.str())); 791 } 792 } 793 794 break; 795 } 796 797 case Stmt::DoStmtClass: { 798 if (*(Src->succ_begin()) == Dst) { 799 std::string sbuf; 800 llvm::raw_string_ostream os(sbuf); 801 802 os << "Loop condition is true. "; 803 PathDiagnosticLocation End = PDB.ExecutionContinues(os, N); 804 805 if (const Stmt *S = End.asStmt()) 806 End = PDB.getEnclosingStmtLocation(S); 807 808 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece( 809 Start, End, os.str())); 810 } 811 else { 812 PathDiagnosticLocation End = PDB.ExecutionContinues(N); 813 814 if (const Stmt *S = End.asStmt()) 815 End = PDB.getEnclosingStmtLocation(S); 816 817 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece( 818 Start, End, "Loop condition is false. Exiting loop")); 819 } 820 821 break; 822 } 823 824 case Stmt::WhileStmtClass: 825 case Stmt::ForStmtClass: { 826 if (*(Src->succ_begin()+1) == Dst) { 827 std::string sbuf; 828 llvm::raw_string_ostream os(sbuf); 829 830 os << "Loop condition is false. "; 831 PathDiagnosticLocation End = PDB.ExecutionContinues(os, N); 832 if (const Stmt *S = End.asStmt()) 833 End = PDB.getEnclosingStmtLocation(S); 834 835 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece( 836 Start, End, os.str())); 837 } 838 else { 839 PathDiagnosticLocation End = PDB.ExecutionContinues(N); 840 if (const Stmt *S = End.asStmt()) 841 End = PDB.getEnclosingStmtLocation(S); 842 843 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece( 844 Start, End, "Loop condition is true. Entering loop body")); 845 } 846 847 break; 848 } 849 850 case Stmt::IfStmtClass: { 851 PathDiagnosticLocation End = PDB.ExecutionContinues(N); 852 853 if (const Stmt *S = End.asStmt()) 854 End = PDB.getEnclosingStmtLocation(S); 855 856 if (*(Src->succ_begin()+1) == Dst) 857 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece( 858 Start, End, "Taking false branch")); 859 else 860 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece( 861 Start, End, "Taking true branch")); 862 863 break; 864 } 865 } 866 } 867 } while(0); 868 869 if (NextNode) { 870 // Add diagnostic pieces from custom visitors. 871 BugReport *R = PDB.getBugReport(); 872 for (ArrayRef<BugReporterVisitor *>::iterator I = visitors.begin(), 873 E = visitors.end(); 874 I != E; ++I) { 875 if (PathDiagnosticPiece *p = (*I)->VisitNode(N, NextNode, PDB, *R)) { 876 PD.getActivePath().push_front(p); 877 updateStackPiecesWithMessage(p, CallStack); 878 } 879 } 880 } 881 } 882 883 if (!PDB.getBugReport()->isValid()) 884 return false; 885 886 // After constructing the full PathDiagnostic, do a pass over it to compact 887 // PathDiagnosticPieces that occur within a macro. 888 CompactPathDiagnostic(PD.getMutablePieces(), PDB.getSourceManager()); 889 return true; 890} 891 892//===----------------------------------------------------------------------===// 893// "Extensive" PathDiagnostic generation. 894//===----------------------------------------------------------------------===// 895 896static bool IsControlFlowExpr(const Stmt *S) { 897 const Expr *E = dyn_cast<Expr>(S); 898 899 if (!E) 900 return false; 901 902 E = E->IgnoreParenCasts(); 903 904 if (isa<AbstractConditionalOperator>(E)) 905 return true; 906 907 if (const BinaryOperator *B = dyn_cast<BinaryOperator>(E)) 908 if (B->isLogicalOp()) 909 return true; 910 911 return false; 912} 913 914namespace { 915class ContextLocation : public PathDiagnosticLocation { 916 bool IsDead; 917public: 918 ContextLocation(const PathDiagnosticLocation &L, bool isdead = false) 919 : PathDiagnosticLocation(L), IsDead(isdead) {} 920 921 void markDead() { IsDead = true; } 922 bool isDead() const { return IsDead; } 923}; 924 925static PathDiagnosticLocation cleanUpLocation(PathDiagnosticLocation L, 926 const LocationContext *LC, 927 bool firstCharOnly = false) { 928 if (const Stmt *S = L.asStmt()) { 929 const Stmt *Original = S; 930 while (1) { 931 // Adjust the location for some expressions that are best referenced 932 // by one of their subexpressions. 933 switch (S->getStmtClass()) { 934 default: 935 break; 936 case Stmt::ParenExprClass: 937 case Stmt::GenericSelectionExprClass: 938 S = cast<Expr>(S)->IgnoreParens(); 939 firstCharOnly = true; 940 continue; 941 case Stmt::BinaryConditionalOperatorClass: 942 case Stmt::ConditionalOperatorClass: 943 S = cast<AbstractConditionalOperator>(S)->getCond(); 944 firstCharOnly = true; 945 continue; 946 case Stmt::ChooseExprClass: 947 S = cast<ChooseExpr>(S)->getCond(); 948 firstCharOnly = true; 949 continue; 950 case Stmt::BinaryOperatorClass: 951 S = cast<BinaryOperator>(S)->getLHS(); 952 firstCharOnly = true; 953 continue; 954 } 955 956 break; 957 } 958 959 if (S != Original) 960 L = PathDiagnosticLocation(S, L.getManager(), LC); 961 } 962 963 if (firstCharOnly) 964 L = PathDiagnosticLocation::createSingleLocation(L); 965 966 return L; 967} 968 969class EdgeBuilder { 970 std::vector<ContextLocation> CLocs; 971 typedef std::vector<ContextLocation>::iterator iterator; 972 PathDiagnostic &PD; 973 PathDiagnosticBuilder &PDB; 974 PathDiagnosticLocation PrevLoc; 975 976 bool IsConsumedExpr(const PathDiagnosticLocation &L); 977 978 bool containsLocation(const PathDiagnosticLocation &Container, 979 const PathDiagnosticLocation &Containee); 980 981 PathDiagnosticLocation getContextLocation(const PathDiagnosticLocation &L); 982 983 984 985 void popLocation() { 986 if (!CLocs.back().isDead() && CLocs.back().asLocation().isFileID()) { 987 // For contexts, we only one the first character as the range. 988 rawAddEdge(cleanUpLocation(CLocs.back(), PDB.LC, true)); 989 } 990 CLocs.pop_back(); 991 } 992 993public: 994 EdgeBuilder(PathDiagnostic &pd, PathDiagnosticBuilder &pdb) 995 : PD(pd), PDB(pdb) { 996 997 // If the PathDiagnostic already has pieces, add the enclosing statement 998 // of the first piece as a context as well. 999 if (!PD.path.empty()) { 1000 PrevLoc = (*PD.path.begin())->getLocation(); 1001 1002 if (const Stmt *S = PrevLoc.asStmt()) 1003 addExtendedContext(PDB.getEnclosingStmtLocation(S).asStmt()); 1004 } 1005 } 1006 1007 ~EdgeBuilder() { 1008 while (!CLocs.empty()) popLocation(); 1009 1010 // Finally, add an initial edge from the start location of the first 1011 // statement (if it doesn't already exist). 1012 PathDiagnosticLocation L = PathDiagnosticLocation::createDeclBegin( 1013 PDB.LC, 1014 PDB.getSourceManager()); 1015 if (L.isValid()) 1016 rawAddEdge(L); 1017 } 1018 1019 void flushLocations() { 1020 while (!CLocs.empty()) 1021 popLocation(); 1022 PrevLoc = PathDiagnosticLocation(); 1023 } 1024 1025 void addEdge(PathDiagnosticLocation NewLoc, bool alwaysAdd = false, 1026 bool IsPostJump = false); 1027 1028 void rawAddEdge(PathDiagnosticLocation NewLoc); 1029 1030 void addContext(const Stmt *S); 1031 void addContext(const PathDiagnosticLocation &L); 1032 void addExtendedContext(const Stmt *S); 1033}; 1034} // end anonymous namespace 1035 1036 1037PathDiagnosticLocation 1038EdgeBuilder::getContextLocation(const PathDiagnosticLocation &L) { 1039 if (const Stmt *S = L.asStmt()) { 1040 if (IsControlFlowExpr(S)) 1041 return L; 1042 1043 return PDB.getEnclosingStmtLocation(S); 1044 } 1045 1046 return L; 1047} 1048 1049bool EdgeBuilder::containsLocation(const PathDiagnosticLocation &Container, 1050 const PathDiagnosticLocation &Containee) { 1051 1052 if (Container == Containee) 1053 return true; 1054 1055 if (Container.asDecl()) 1056 return true; 1057 1058 if (const Stmt *S = Containee.asStmt()) 1059 if (const Stmt *ContainerS = Container.asStmt()) { 1060 while (S) { 1061 if (S == ContainerS) 1062 return true; 1063 S = PDB.getParent(S); 1064 } 1065 return false; 1066 } 1067 1068 // Less accurate: compare using source ranges. 1069 SourceRange ContainerR = Container.asRange(); 1070 SourceRange ContaineeR = Containee.asRange(); 1071 1072 SourceManager &SM = PDB.getSourceManager(); 1073 SourceLocation ContainerRBeg = SM.getExpansionLoc(ContainerR.getBegin()); 1074 SourceLocation ContainerREnd = SM.getExpansionLoc(ContainerR.getEnd()); 1075 SourceLocation ContaineeRBeg = SM.getExpansionLoc(ContaineeR.getBegin()); 1076 SourceLocation ContaineeREnd = SM.getExpansionLoc(ContaineeR.getEnd()); 1077 1078 unsigned ContainerBegLine = SM.getExpansionLineNumber(ContainerRBeg); 1079 unsigned ContainerEndLine = SM.getExpansionLineNumber(ContainerREnd); 1080 unsigned ContaineeBegLine = SM.getExpansionLineNumber(ContaineeRBeg); 1081 unsigned ContaineeEndLine = SM.getExpansionLineNumber(ContaineeREnd); 1082 1083 assert(ContainerBegLine <= ContainerEndLine); 1084 assert(ContaineeBegLine <= ContaineeEndLine); 1085 1086 return (ContainerBegLine <= ContaineeBegLine && 1087 ContainerEndLine >= ContaineeEndLine && 1088 (ContainerBegLine != ContaineeBegLine || 1089 SM.getExpansionColumnNumber(ContainerRBeg) <= 1090 SM.getExpansionColumnNumber(ContaineeRBeg)) && 1091 (ContainerEndLine != ContaineeEndLine || 1092 SM.getExpansionColumnNumber(ContainerREnd) >= 1093 SM.getExpansionColumnNumber(ContaineeREnd))); 1094} 1095 1096void EdgeBuilder::rawAddEdge(PathDiagnosticLocation NewLoc) { 1097 if (!PrevLoc.isValid()) { 1098 PrevLoc = NewLoc; 1099 return; 1100 } 1101 1102 const PathDiagnosticLocation &NewLocClean = cleanUpLocation(NewLoc, PDB.LC); 1103 const PathDiagnosticLocation &PrevLocClean = cleanUpLocation(PrevLoc, PDB.LC); 1104 1105 if (PrevLocClean.asLocation().isInvalid()) { 1106 PrevLoc = NewLoc; 1107 return; 1108 } 1109 1110 if (NewLocClean.asLocation() == PrevLocClean.asLocation()) 1111 return; 1112 1113 // FIXME: Ignore intra-macro edges for now. 1114 if (NewLocClean.asLocation().getExpansionLoc() == 1115 PrevLocClean.asLocation().getExpansionLoc()) 1116 return; 1117 1118 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(NewLocClean, PrevLocClean)); 1119 PrevLoc = NewLoc; 1120} 1121 1122void EdgeBuilder::addEdge(PathDiagnosticLocation NewLoc, bool alwaysAdd, 1123 bool IsPostJump) { 1124 1125 if (!alwaysAdd && NewLoc.asLocation().isMacroID()) 1126 return; 1127 1128 const PathDiagnosticLocation &CLoc = getContextLocation(NewLoc); 1129 1130 while (!CLocs.empty()) { 1131 ContextLocation &TopContextLoc = CLocs.back(); 1132 1133 // Is the top location context the same as the one for the new location? 1134 if (TopContextLoc == CLoc) { 1135 if (alwaysAdd) { 1136 if (IsConsumedExpr(TopContextLoc)) 1137 TopContextLoc.markDead(); 1138 1139 rawAddEdge(NewLoc); 1140 } 1141 1142 if (IsPostJump) 1143 TopContextLoc.markDead(); 1144 return; 1145 } 1146 1147 if (containsLocation(TopContextLoc, CLoc)) { 1148 if (alwaysAdd) { 1149 rawAddEdge(NewLoc); 1150 1151 if (IsConsumedExpr(CLoc)) { 1152 CLocs.push_back(ContextLocation(CLoc, /*IsDead=*/true)); 1153 return; 1154 } 1155 } 1156 1157 CLocs.push_back(ContextLocation(CLoc, /*IsDead=*/IsPostJump)); 1158 return; 1159 } 1160 1161 // Context does not contain the location. Flush it. 1162 popLocation(); 1163 } 1164 1165 // If we reach here, there is no enclosing context. Just add the edge. 1166 rawAddEdge(NewLoc); 1167} 1168 1169bool EdgeBuilder::IsConsumedExpr(const PathDiagnosticLocation &L) { 1170 if (const Expr *X = dyn_cast_or_null<Expr>(L.asStmt())) 1171 return PDB.getParentMap().isConsumedExpr(X) && !IsControlFlowExpr(X); 1172 1173 return false; 1174} 1175 1176void EdgeBuilder::addExtendedContext(const Stmt *S) { 1177 if (!S) 1178 return; 1179 1180 const Stmt *Parent = PDB.getParent(S); 1181 while (Parent) { 1182 if (isa<CompoundStmt>(Parent)) 1183 Parent = PDB.getParent(Parent); 1184 else 1185 break; 1186 } 1187 1188 if (Parent) { 1189 switch (Parent->getStmtClass()) { 1190 case Stmt::DoStmtClass: 1191 case Stmt::ObjCAtSynchronizedStmtClass: 1192 addContext(Parent); 1193 default: 1194 break; 1195 } 1196 } 1197 1198 addContext(S); 1199} 1200 1201void EdgeBuilder::addContext(const Stmt *S) { 1202 if (!S) 1203 return; 1204 1205 PathDiagnosticLocation L(S, PDB.getSourceManager(), PDB.LC); 1206 addContext(L); 1207} 1208 1209void EdgeBuilder::addContext(const PathDiagnosticLocation &L) { 1210 while (!CLocs.empty()) { 1211 const PathDiagnosticLocation &TopContextLoc = CLocs.back(); 1212 1213 // Is the top location context the same as the one for the new location? 1214 if (TopContextLoc == L) 1215 return; 1216 1217 if (containsLocation(TopContextLoc, L)) { 1218 CLocs.push_back(L); 1219 return; 1220 } 1221 1222 // Context does not contain the location. Flush it. 1223 popLocation(); 1224 } 1225 1226 CLocs.push_back(L); 1227} 1228 1229// Cone-of-influence: support the reverse propagation of "interesting" symbols 1230// and values by tracing interesting calculations backwards through evaluated 1231// expressions along a path. This is probably overly complicated, but the idea 1232// is that if an expression computed an "interesting" value, the child 1233// expressions are are also likely to be "interesting" as well (which then 1234// propagates to the values they in turn compute). This reverse propagation 1235// is needed to track interesting correlations across function call boundaries, 1236// where formal arguments bind to actual arguments, etc. This is also needed 1237// because the constraint solver sometimes simplifies certain symbolic values 1238// into constants when appropriate, and this complicates reasoning about 1239// interesting values. 1240typedef llvm::DenseSet<const Expr *> InterestingExprs; 1241 1242static void reversePropagateIntererstingSymbols(BugReport &R, 1243 InterestingExprs &IE, 1244 const ProgramState *State, 1245 const Expr *Ex, 1246 const LocationContext *LCtx) { 1247 SVal V = State->getSVal(Ex, LCtx); 1248 if (!(R.isInteresting(V) || IE.count(Ex))) 1249 return; 1250 1251 switch (Ex->getStmtClass()) { 1252 default: 1253 if (!isa<CastExpr>(Ex)) 1254 break; 1255 // Fall through. 1256 case Stmt::BinaryOperatorClass: 1257 case Stmt::UnaryOperatorClass: { 1258 for (Stmt::const_child_iterator CI = Ex->child_begin(), 1259 CE = Ex->child_end(); 1260 CI != CE; ++CI) { 1261 if (const Expr *child = dyn_cast_or_null<Expr>(*CI)) { 1262 IE.insert(child); 1263 SVal ChildV = State->getSVal(child, LCtx); 1264 R.markInteresting(ChildV); 1265 } 1266 break; 1267 } 1268 } 1269 } 1270 1271 R.markInteresting(V); 1272} 1273 1274static void reversePropagateInterestingSymbols(BugReport &R, 1275 InterestingExprs &IE, 1276 const ProgramState *State, 1277 const LocationContext *CalleeCtx, 1278 const LocationContext *CallerCtx) 1279{ 1280 // FIXME: Handle non-CallExpr-based CallEvents. 1281 const StackFrameContext *Callee = CalleeCtx->getCurrentStackFrame(); 1282 const Stmt *CallSite = Callee->getCallSite(); 1283 if (const CallExpr *CE = dyn_cast_or_null<CallExpr>(CallSite)) { 1284 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CalleeCtx->getDecl())) { 1285 FunctionDecl::param_const_iterator PI = FD->param_begin(), 1286 PE = FD->param_end(); 1287 CallExpr::const_arg_iterator AI = CE->arg_begin(), AE = CE->arg_end(); 1288 for (; AI != AE && PI != PE; ++AI, ++PI) { 1289 if (const Expr *ArgE = *AI) { 1290 if (const ParmVarDecl *PD = *PI) { 1291 Loc LV = State->getLValue(PD, CalleeCtx); 1292 if (R.isInteresting(LV) || R.isInteresting(State->getRawSVal(LV))) 1293 IE.insert(ArgE); 1294 } 1295 } 1296 } 1297 } 1298 } 1299} 1300 1301//===----------------------------------------------------------------------===// 1302// Functions for determining if a loop was executed 0 times. 1303//===----------------------------------------------------------------------===// 1304 1305static bool isLoop(const Stmt *Term) { 1306 switch (Term->getStmtClass()) { 1307 case Stmt::ForStmtClass: 1308 case Stmt::WhileStmtClass: 1309 case Stmt::ObjCForCollectionStmtClass: 1310 case Stmt::CXXForRangeStmtClass: 1311 return true; 1312 default: 1313 // Note that we intentionally do not include do..while here. 1314 return false; 1315 } 1316} 1317 1318static bool isJumpToFalseBranch(const BlockEdge *BE) { 1319 const CFGBlock *Src = BE->getSrc(); 1320 assert(Src->succ_size() == 2); 1321 return (*(Src->succ_begin()+1) == BE->getDst()); 1322} 1323 1324/// Return true if the terminator is a loop and the destination is the 1325/// false branch. 1326static bool isLoopJumpPastBody(const Stmt *Term, const BlockEdge *BE) { 1327 if (!isLoop(Term)) 1328 return false; 1329 1330 // Did we take the false branch? 1331 return isJumpToFalseBranch(BE); 1332} 1333 1334static bool isContainedByStmt(ParentMap &PM, const Stmt *S, const Stmt *SubS) { 1335 while (SubS) { 1336 if (SubS == S) 1337 return true; 1338 SubS = PM.getParent(SubS); 1339 } 1340 return false; 1341} 1342 1343static const Stmt *getStmtBeforeCond(ParentMap &PM, const Stmt *Term, 1344 const ExplodedNode *N) { 1345 while (N) { 1346 Optional<StmtPoint> SP = N->getLocation().getAs<StmtPoint>(); 1347 if (SP) { 1348 const Stmt *S = SP->getStmt(); 1349 if (!isContainedByStmt(PM, Term, S)) 1350 return S; 1351 } 1352 N = N->getFirstPred(); 1353 } 1354 return 0; 1355} 1356 1357static bool isInLoopBody(ParentMap &PM, const Stmt *S, const Stmt *Term) { 1358 const Stmt *LoopBody = 0; 1359 switch (Term->getStmtClass()) { 1360 case Stmt::CXXForRangeStmtClass: { 1361 const CXXForRangeStmt *FR = cast<CXXForRangeStmt>(Term); 1362 if (isContainedByStmt(PM, FR->getInc(), S)) 1363 return true; 1364 if (isContainedByStmt(PM, FR->getLoopVarStmt(), S)) 1365 return true; 1366 LoopBody = FR->getBody(); 1367 break; 1368 } 1369 case Stmt::ForStmtClass: { 1370 const ForStmt *FS = cast<ForStmt>(Term); 1371 if (isContainedByStmt(PM, FS->getInc(), S)) 1372 return true; 1373 LoopBody = FS->getBody(); 1374 break; 1375 } 1376 case Stmt::ObjCForCollectionStmtClass: { 1377 const ObjCForCollectionStmt *FC = cast<ObjCForCollectionStmt>(Term); 1378 LoopBody = FC->getBody(); 1379 break; 1380 } 1381 case Stmt::WhileStmtClass: 1382 LoopBody = cast<WhileStmt>(Term)->getBody(); 1383 break; 1384 default: 1385 return false; 1386 } 1387 return isContainedByStmt(PM, LoopBody, S); 1388} 1389 1390//===----------------------------------------------------------------------===// 1391// Top-level logic for generating extensive path diagnostics. 1392//===----------------------------------------------------------------------===// 1393 1394static bool GenerateExtensivePathDiagnostic(PathDiagnostic& PD, 1395 PathDiagnosticBuilder &PDB, 1396 const ExplodedNode *N, 1397 LocationContextMap &LCM, 1398 ArrayRef<BugReporterVisitor *> visitors) { 1399 EdgeBuilder EB(PD, PDB); 1400 const SourceManager& SM = PDB.getSourceManager(); 1401 StackDiagVector CallStack; 1402 InterestingExprs IE; 1403 1404 const ExplodedNode *NextNode = N->pred_empty() ? NULL : *(N->pred_begin()); 1405 while (NextNode) { 1406 N = NextNode; 1407 NextNode = N->getFirstPred(); 1408 ProgramPoint P = N->getLocation(); 1409 1410 do { 1411 if (Optional<PostStmt> PS = P.getAs<PostStmt>()) { 1412 if (const Expr *Ex = PS->getStmtAs<Expr>()) 1413 reversePropagateIntererstingSymbols(*PDB.getBugReport(), IE, 1414 N->getState().getPtr(), Ex, 1415 N->getLocationContext()); 1416 } 1417 1418 if (Optional<CallExitEnd> CE = P.getAs<CallExitEnd>()) { 1419 const Stmt *S = CE->getCalleeContext()->getCallSite(); 1420 if (const Expr *Ex = dyn_cast_or_null<Expr>(S)) { 1421 reversePropagateIntererstingSymbols(*PDB.getBugReport(), IE, 1422 N->getState().getPtr(), Ex, 1423 N->getLocationContext()); 1424 } 1425 1426 PathDiagnosticCallPiece *C = 1427 PathDiagnosticCallPiece::construct(N, *CE, SM); 1428 LCM[&C->path] = CE->getCalleeContext(); 1429 1430 EB.addEdge(C->callReturn, /*AlwaysAdd=*/true, /*IsPostJump=*/true); 1431 EB.flushLocations(); 1432 1433 PD.getActivePath().push_front(C); 1434 PD.pushActivePath(&C->path); 1435 CallStack.push_back(StackDiagPair(C, N)); 1436 break; 1437 } 1438 1439 // Pop the call hierarchy if we are done walking the contents 1440 // of a function call. 1441 if (Optional<CallEnter> CE = P.getAs<CallEnter>()) { 1442 // Add an edge to the start of the function. 1443 const Decl *D = CE->getCalleeContext()->getDecl(); 1444 PathDiagnosticLocation pos = 1445 PathDiagnosticLocation::createBegin(D, SM); 1446 EB.addEdge(pos); 1447 1448 // Flush all locations, and pop the active path. 1449 bool VisitedEntireCall = PD.isWithinCall(); 1450 EB.flushLocations(); 1451 PD.popActivePath(); 1452 PDB.LC = N->getLocationContext(); 1453 1454 // Either we just added a bunch of stuff to the top-level path, or 1455 // we have a previous CallExitEnd. If the former, it means that the 1456 // path terminated within a function call. We must then take the 1457 // current contents of the active path and place it within 1458 // a new PathDiagnosticCallPiece. 1459 PathDiagnosticCallPiece *C; 1460 if (VisitedEntireCall) { 1461 C = cast<PathDiagnosticCallPiece>(PD.getActivePath().front()); 1462 } else { 1463 const Decl *Caller = CE->getLocationContext()->getDecl(); 1464 C = PathDiagnosticCallPiece::construct(PD.getActivePath(), Caller); 1465 LCM[&C->path] = CE->getCalleeContext(); 1466 } 1467 1468 C->setCallee(*CE, SM); 1469 EB.addContext(C->getLocation()); 1470 1471 if (!CallStack.empty()) { 1472 assert(CallStack.back().first == C); 1473 CallStack.pop_back(); 1474 } 1475 break; 1476 } 1477 1478 // Note that is important that we update the LocationContext 1479 // after looking at CallExits. CallExit basically adds an 1480 // edge in the *caller*, so we don't want to update the LocationContext 1481 // too soon. 1482 PDB.LC = N->getLocationContext(); 1483 1484 // Block edges. 1485 if (Optional<BlockEdge> BE = P.getAs<BlockEdge>()) { 1486 // Does this represent entering a call? If so, look at propagating 1487 // interesting symbols across call boundaries. 1488 if (NextNode) { 1489 const LocationContext *CallerCtx = NextNode->getLocationContext(); 1490 const LocationContext *CalleeCtx = PDB.LC; 1491 if (CallerCtx != CalleeCtx) { 1492 reversePropagateInterestingSymbols(*PDB.getBugReport(), IE, 1493 N->getState().getPtr(), 1494 CalleeCtx, CallerCtx); 1495 } 1496 } 1497 1498 // Are we jumping to the head of a loop? Add a special diagnostic. 1499 if (const Stmt *Loop = BE->getSrc()->getLoopTarget()) { 1500 PathDiagnosticLocation L(Loop, SM, PDB.LC); 1501 const CompoundStmt *CS = NULL; 1502 1503 if (const ForStmt *FS = dyn_cast<ForStmt>(Loop)) 1504 CS = dyn_cast<CompoundStmt>(FS->getBody()); 1505 else if (const WhileStmt *WS = dyn_cast<WhileStmt>(Loop)) 1506 CS = dyn_cast<CompoundStmt>(WS->getBody()); 1507 1508 PathDiagnosticEventPiece *p = 1509 new PathDiagnosticEventPiece(L, 1510 "Looping back to the head of the loop"); 1511 p->setPrunable(true); 1512 1513 EB.addEdge(p->getLocation(), true); 1514 PD.getActivePath().push_front(p); 1515 1516 if (CS) { 1517 PathDiagnosticLocation BL = 1518 PathDiagnosticLocation::createEndBrace(CS, SM); 1519 EB.addEdge(BL); 1520 } 1521 } 1522 1523 const CFGBlock *BSrc = BE->getSrc(); 1524 ParentMap &PM = PDB.getParentMap(); 1525 1526 if (const Stmt *Term = BSrc->getTerminator()) { 1527 // Are we jumping past the loop body without ever executing the 1528 // loop (because the condition was false)? 1529 if (isLoopJumpPastBody(Term, &*BE) && 1530 !isInLoopBody(PM, 1531 getStmtBeforeCond(PM, 1532 BSrc->getTerminatorCondition(), 1533 N), 1534 Term)) { 1535 PathDiagnosticLocation L(Term, SM, PDB.LC); 1536 PathDiagnosticEventPiece *PE = 1537 new PathDiagnosticEventPiece(L, "Loop body executed 0 times"); 1538 PE->setPrunable(true); 1539 1540 EB.addEdge(PE->getLocation(), true); 1541 PD.getActivePath().push_front(PE); 1542 } 1543 1544 // In any case, add the terminator as the current statement 1545 // context for control edges. 1546 EB.addContext(Term); 1547 } 1548 1549 break; 1550 } 1551 1552 if (Optional<BlockEntrance> BE = P.getAs<BlockEntrance>()) { 1553 Optional<CFGElement> First = BE->getFirstElement(); 1554 if (Optional<CFGStmt> S = First ? First->getAs<CFGStmt>() : None) { 1555 const Stmt *stmt = S->getStmt(); 1556 if (IsControlFlowExpr(stmt)) { 1557 // Add the proper context for '&&', '||', and '?'. 1558 EB.addContext(stmt); 1559 } 1560 else 1561 EB.addExtendedContext(PDB.getEnclosingStmtLocation(stmt).asStmt()); 1562 } 1563 1564 break; 1565 } 1566 1567 1568 } while (0); 1569 1570 if (!NextNode) 1571 continue; 1572 1573 // Add pieces from custom visitors. 1574 BugReport *R = PDB.getBugReport(); 1575 for (ArrayRef<BugReporterVisitor *>::iterator I = visitors.begin(), 1576 E = visitors.end(); 1577 I != E; ++I) { 1578 if (PathDiagnosticPiece *p = (*I)->VisitNode(N, NextNode, PDB, *R)) { 1579 const PathDiagnosticLocation &Loc = p->getLocation(); 1580 EB.addEdge(Loc, true); 1581 PD.getActivePath().push_front(p); 1582 updateStackPiecesWithMessage(p, CallStack); 1583 1584 if (const Stmt *S = Loc.asStmt()) 1585 EB.addExtendedContext(PDB.getEnclosingStmtLocation(S).asStmt()); 1586 } 1587 } 1588 } 1589 1590 return PDB.getBugReport()->isValid(); 1591} 1592 1593/// \brief Adds a sanitized control-flow diagnostic edge to a path. 1594static void addEdgeToPath(PathPieces &path, 1595 PathDiagnosticLocation &PrevLoc, 1596 PathDiagnosticLocation NewLoc, 1597 const LocationContext *LC) { 1598 if (!NewLoc.isValid()) 1599 return; 1600 1601 SourceLocation NewLocL = NewLoc.asLocation(); 1602 if (NewLocL.isInvalid()) 1603 return; 1604 1605 if (!PrevLoc.isValid() || !PrevLoc.asLocation().isValid()) { 1606 PrevLoc = NewLoc; 1607 return; 1608 } 1609 1610 // Ignore self-edges, which occur when there are multiple nodes at the same 1611 // statement. 1612 if (NewLoc.asStmt() && NewLoc.asStmt() == PrevLoc.asStmt()) 1613 return; 1614 1615 path.push_front(new PathDiagnosticControlFlowPiece(NewLoc, 1616 PrevLoc)); 1617 PrevLoc = NewLoc; 1618} 1619 1620/// A customized wrapper for CFGBlock::getTerminatorCondition() 1621/// which returns the element for ObjCForCollectionStmts. 1622static const Stmt *getTerminatorCondition(const CFGBlock *B) { 1623 const Stmt *S = B->getTerminatorCondition(); 1624 if (const ObjCForCollectionStmt *FS = 1625 dyn_cast_or_null<ObjCForCollectionStmt>(S)) 1626 return FS->getElement(); 1627 return S; 1628} 1629 1630static const char StrEnteringLoop[] = "Entering loop body"; 1631static const char StrLoopBodyZero[] = "Loop body executed 0 times"; 1632 1633static bool 1634GenerateAlternateExtensivePathDiagnostic(PathDiagnostic& PD, 1635 PathDiagnosticBuilder &PDB, 1636 const ExplodedNode *N, 1637 LocationContextMap &LCM, 1638 ArrayRef<BugReporterVisitor *> visitors) { 1639 1640 BugReport *report = PDB.getBugReport(); 1641 const SourceManager& SM = PDB.getSourceManager(); 1642 StackDiagVector CallStack; 1643 InterestingExprs IE; 1644 1645 PathDiagnosticLocation PrevLoc = PD.getLocation(); 1646 1647 const ExplodedNode *NextNode = N->getFirstPred(); 1648 while (NextNode) { 1649 N = NextNode; 1650 NextNode = N->getFirstPred(); 1651 ProgramPoint P = N->getLocation(); 1652 1653 do { 1654 // Have we encountered an entrance to a call? It may be 1655 // the case that we have not encountered a matching 1656 // call exit before this point. This means that the path 1657 // terminated within the call itself. 1658 if (Optional<CallEnter> CE = P.getAs<CallEnter>()) { 1659 // Add an edge to the start of the function. 1660 const StackFrameContext *CalleeLC = CE->getCalleeContext(); 1661 const Decl *D = CalleeLC->getDecl(); 1662 addEdgeToPath(PD.getActivePath(), PrevLoc, 1663 PathDiagnosticLocation::createBegin(D, SM), 1664 CalleeLC); 1665 1666 // Did we visit an entire call? 1667 bool VisitedEntireCall = PD.isWithinCall(); 1668 PD.popActivePath(); 1669 1670 PathDiagnosticCallPiece *C; 1671 if (VisitedEntireCall) { 1672 PathDiagnosticPiece *P = PD.getActivePath().front().getPtr(); 1673 C = cast<PathDiagnosticCallPiece>(P); 1674 } else { 1675 const Decl *Caller = CE->getLocationContext()->getDecl(); 1676 C = PathDiagnosticCallPiece::construct(PD.getActivePath(), Caller); 1677 1678 // Since we just transferred the path over to the call piece, 1679 // reset the mapping from active to location context. 1680 assert(PD.getActivePath().size() == 1 && 1681 PD.getActivePath().front() == C); 1682 LCM[&PD.getActivePath()] = 0; 1683 1684 // Record the location context mapping for the path within 1685 // the call. 1686 assert(LCM[&C->path] == 0 || 1687 LCM[&C->path] == CE->getCalleeContext()); 1688 LCM[&C->path] = CE->getCalleeContext(); 1689 1690 // If this is the first item in the active path, record 1691 // the new mapping from active path to location context. 1692 const LocationContext *&NewLC = LCM[&PD.getActivePath()]; 1693 if (!NewLC) 1694 NewLC = N->getLocationContext(); 1695 1696 PDB.LC = NewLC; 1697 } 1698 C->setCallee(*CE, SM); 1699 1700 // Update the previous location in the active path. 1701 PrevLoc = C->getLocation(); 1702 1703 if (!CallStack.empty()) { 1704 assert(CallStack.back().first == C); 1705 CallStack.pop_back(); 1706 } 1707 break; 1708 } 1709 1710 // Query the location context here and the previous location 1711 // as processing CallEnter may change the active path. 1712 PDB.LC = N->getLocationContext(); 1713 1714 // Record the mapping from the active path to the location 1715 // context. 1716 assert(!LCM[&PD.getActivePath()] || 1717 LCM[&PD.getActivePath()] == PDB.LC); 1718 LCM[&PD.getActivePath()] = PDB.LC; 1719 1720 // Have we encountered an exit from a function call? 1721 if (Optional<CallExitEnd> CE = P.getAs<CallExitEnd>()) { 1722 const Stmt *S = CE->getCalleeContext()->getCallSite(); 1723 // Propagate the interesting symbols accordingly. 1724 if (const Expr *Ex = dyn_cast_or_null<Expr>(S)) { 1725 reversePropagateIntererstingSymbols(*PDB.getBugReport(), IE, 1726 N->getState().getPtr(), Ex, 1727 N->getLocationContext()); 1728 } 1729 1730 // We are descending into a call (backwards). Construct 1731 // a new call piece to contain the path pieces for that call. 1732 PathDiagnosticCallPiece *C = 1733 PathDiagnosticCallPiece::construct(N, *CE, SM); 1734 1735 // Record the location context for this call piece. 1736 LCM[&C->path] = CE->getCalleeContext(); 1737 1738 // Add the edge to the return site. 1739 addEdgeToPath(PD.getActivePath(), PrevLoc, C->callReturn, PDB.LC); 1740 PD.getActivePath().push_front(C); 1741 PrevLoc.invalidate(); 1742 1743 // Make the contents of the call the active path for now. 1744 PD.pushActivePath(&C->path); 1745 CallStack.push_back(StackDiagPair(C, N)); 1746 break; 1747 } 1748 1749 if (Optional<PostStmt> PS = P.getAs<PostStmt>()) { 1750 // For expressions, make sure we propagate the 1751 // interesting symbols correctly. 1752 if (const Expr *Ex = PS->getStmtAs<Expr>()) 1753 reversePropagateIntererstingSymbols(*PDB.getBugReport(), IE, 1754 N->getState().getPtr(), Ex, 1755 N->getLocationContext()); 1756 1757 // Add an edge. If this is an ObjCForCollectionStmt do 1758 // not add an edge here as it appears in the CFG both 1759 // as a terminator and as a terminator condition. 1760 if (!isa<ObjCForCollectionStmt>(PS->getStmt())) { 1761 PathDiagnosticLocation L = 1762 PathDiagnosticLocation(PS->getStmt(), SM, PDB.LC); 1763 addEdgeToPath(PD.getActivePath(), PrevLoc, L, PDB.LC); 1764 } 1765 break; 1766 } 1767 1768 // Block edges. 1769 if (Optional<BlockEdge> BE = P.getAs<BlockEdge>()) { 1770 // Does this represent entering a call? If so, look at propagating 1771 // interesting symbols across call boundaries. 1772 if (NextNode) { 1773 const LocationContext *CallerCtx = NextNode->getLocationContext(); 1774 const LocationContext *CalleeCtx = PDB.LC; 1775 if (CallerCtx != CalleeCtx) { 1776 reversePropagateInterestingSymbols(*PDB.getBugReport(), IE, 1777 N->getState().getPtr(), 1778 CalleeCtx, CallerCtx); 1779 } 1780 } 1781 1782 // Are we jumping to the head of a loop? Add a special diagnostic. 1783 if (const Stmt *Loop = BE->getSrc()->getLoopTarget()) { 1784 PathDiagnosticLocation L(Loop, SM, PDB.LC); 1785 const Stmt *Body = NULL; 1786 1787 if (const ForStmt *FS = dyn_cast<ForStmt>(Loop)) 1788 Body = FS->getBody(); 1789 else if (const WhileStmt *WS = dyn_cast<WhileStmt>(Loop)) 1790 Body = WS->getBody(); 1791 else if (const ObjCForCollectionStmt *OFS = 1792 dyn_cast<ObjCForCollectionStmt>(Loop)) { 1793 Body = OFS->getBody(); 1794 } else if (const CXXForRangeStmt *FRS = 1795 dyn_cast<CXXForRangeStmt>(Loop)) { 1796 Body = FRS->getBody(); 1797 } 1798 // do-while statements are explicitly excluded here 1799 1800 PathDiagnosticEventPiece *p = 1801 new PathDiagnosticEventPiece(L, "Looping back to the head " 1802 "of the loop"); 1803 p->setPrunable(true); 1804 1805 addEdgeToPath(PD.getActivePath(), PrevLoc, p->getLocation(), PDB.LC); 1806 PD.getActivePath().push_front(p); 1807 1808 if (const CompoundStmt *CS = dyn_cast_or_null<CompoundStmt>(Body)) { 1809 addEdgeToPath(PD.getActivePath(), PrevLoc, 1810 PathDiagnosticLocation::createEndBrace(CS, SM), 1811 PDB.LC); 1812 } 1813 } 1814 1815 const CFGBlock *BSrc = BE->getSrc(); 1816 ParentMap &PM = PDB.getParentMap(); 1817 1818 if (const Stmt *Term = BSrc->getTerminator()) { 1819 // Are we jumping past the loop body without ever executing the 1820 // loop (because the condition was false)? 1821 if (isLoop(Term)) { 1822 const Stmt *TermCond = getTerminatorCondition(BSrc); 1823 bool IsInLoopBody = 1824 isInLoopBody(PM, getStmtBeforeCond(PM, TermCond, N), Term); 1825 1826 const char *str = 0; 1827 1828 if (isJumpToFalseBranch(&*BE)) { 1829 if (!IsInLoopBody) { 1830 str = StrLoopBodyZero; 1831 } 1832 } else { 1833 str = StrEnteringLoop; 1834 } 1835 1836 if (str) { 1837 PathDiagnosticLocation L(TermCond ? TermCond : Term, SM, PDB.LC); 1838 PathDiagnosticEventPiece *PE = 1839 new PathDiagnosticEventPiece(L, str); 1840 PE->setPrunable(true); 1841 addEdgeToPath(PD.getActivePath(), PrevLoc, 1842 PE->getLocation(), PDB.LC); 1843 PD.getActivePath().push_front(PE); 1844 } 1845 } else if (isa<BreakStmt>(Term) || isa<ContinueStmt>(Term) || 1846 isa<GotoStmt>(Term)) { 1847 PathDiagnosticLocation L(Term, SM, PDB.LC); 1848 addEdgeToPath(PD.getActivePath(), PrevLoc, L, PDB.LC); 1849 } 1850 } 1851 break; 1852 } 1853 } while (0); 1854 1855 if (!NextNode) 1856 continue; 1857 1858 // Add pieces from custom visitors. 1859 for (ArrayRef<BugReporterVisitor *>::iterator I = visitors.begin(), 1860 E = visitors.end(); 1861 I != E; ++I) { 1862 if (PathDiagnosticPiece *p = (*I)->VisitNode(N, NextNode, PDB, *report)) { 1863 addEdgeToPath(PD.getActivePath(), PrevLoc, p->getLocation(), PDB.LC); 1864 PD.getActivePath().push_front(p); 1865 updateStackPiecesWithMessage(p, CallStack); 1866 } 1867 } 1868 } 1869 1870 // Add an edge to the start of the function. 1871 // We'll prune it out later, but it helps make diagnostics more uniform. 1872 const StackFrameContext *CalleeLC = PDB.LC->getCurrentStackFrame(); 1873 const Decl *D = CalleeLC->getDecl(); 1874 addEdgeToPath(PD.getActivePath(), PrevLoc, 1875 PathDiagnosticLocation::createBegin(D, SM), 1876 CalleeLC); 1877 1878 return report->isValid(); 1879} 1880 1881static const Stmt *getLocStmt(PathDiagnosticLocation L) { 1882 if (!L.isValid()) 1883 return 0; 1884 return L.asStmt(); 1885} 1886 1887static const Stmt *getStmtParent(const Stmt *S, const ParentMap &PM) { 1888 if (!S) 1889 return 0; 1890 1891 while (true) { 1892 S = PM.getParentIgnoreParens(S); 1893 1894 if (!S) 1895 break; 1896 1897 if (isa<ExprWithCleanups>(S) || 1898 isa<CXXBindTemporaryExpr>(S) || 1899 isa<SubstNonTypeTemplateParmExpr>(S)) 1900 continue; 1901 1902 break; 1903 } 1904 1905 return S; 1906} 1907 1908static bool isConditionForTerminator(const Stmt *S, const Stmt *Cond) { 1909 switch (S->getStmtClass()) { 1910 case Stmt::BinaryOperatorClass: { 1911 const BinaryOperator *BO = cast<BinaryOperator>(S); 1912 if (!BO->isLogicalOp()) 1913 return false; 1914 return BO->getLHS() == Cond || BO->getRHS() == Cond; 1915 } 1916 case Stmt::IfStmtClass: 1917 return cast<IfStmt>(S)->getCond() == Cond; 1918 case Stmt::ForStmtClass: 1919 return cast<ForStmt>(S)->getCond() == Cond; 1920 case Stmt::WhileStmtClass: 1921 return cast<WhileStmt>(S)->getCond() == Cond; 1922 case Stmt::DoStmtClass: 1923 return cast<DoStmt>(S)->getCond() == Cond; 1924 case Stmt::ChooseExprClass: 1925 return cast<ChooseExpr>(S)->getCond() == Cond; 1926 case Stmt::IndirectGotoStmtClass: 1927 return cast<IndirectGotoStmt>(S)->getTarget() == Cond; 1928 case Stmt::SwitchStmtClass: 1929 return cast<SwitchStmt>(S)->getCond() == Cond; 1930 case Stmt::BinaryConditionalOperatorClass: 1931 return cast<BinaryConditionalOperator>(S)->getCond() == Cond; 1932 case Stmt::ConditionalOperatorClass: { 1933 const ConditionalOperator *CO = cast<ConditionalOperator>(S); 1934 return CO->getCond() == Cond || 1935 CO->getLHS() == Cond || 1936 CO->getRHS() == Cond; 1937 } 1938 case Stmt::ObjCForCollectionStmtClass: 1939 return cast<ObjCForCollectionStmt>(S)->getElement() == Cond; 1940 case Stmt::CXXForRangeStmtClass: { 1941 const CXXForRangeStmt *FRS = cast<CXXForRangeStmt>(S); 1942 return FRS->getCond() == Cond || FRS->getRangeInit() == Cond; 1943 } 1944 default: 1945 return false; 1946 } 1947} 1948 1949static bool isIncrementOrInitInForLoop(const Stmt *S, const Stmt *FL) { 1950 if (const ForStmt *FS = dyn_cast<ForStmt>(FL)) 1951 return FS->getInc() == S || FS->getInit() == S; 1952 if (const CXXForRangeStmt *FRS = dyn_cast<CXXForRangeStmt>(FL)) 1953 return FRS->getInc() == S || FRS->getRangeStmt() == S || 1954 FRS->getLoopVarStmt() || FRS->getRangeInit() == S; 1955 return false; 1956} 1957 1958typedef llvm::DenseSet<const PathDiagnosticCallPiece *> 1959 OptimizedCallsSet; 1960 1961/// Adds synthetic edges from top-level statements to their subexpressions. 1962/// 1963/// This avoids a "swoosh" effect, where an edge from a top-level statement A 1964/// points to a sub-expression B.1 that's not at the start of B. In these cases, 1965/// we'd like to see an edge from A to B, then another one from B to B.1. 1966static void addContextEdges(PathPieces &pieces, SourceManager &SM, 1967 const ParentMap &PM, const LocationContext *LCtx) { 1968 PathPieces::iterator Prev = pieces.end(); 1969 for (PathPieces::iterator I = pieces.begin(), E = Prev; I != E; 1970 Prev = I, ++I) { 1971 PathDiagnosticControlFlowPiece *Piece = 1972 dyn_cast<PathDiagnosticControlFlowPiece>(*I); 1973 1974 if (!Piece) 1975 continue; 1976 1977 PathDiagnosticLocation SrcLoc = Piece->getStartLocation(); 1978 SmallVector<PathDiagnosticLocation, 4> SrcContexts; 1979 1980 PathDiagnosticLocation NextSrcContext = SrcLoc; 1981 const Stmt *InnerStmt = 0; 1982 while (NextSrcContext.isValid() && NextSrcContext.asStmt() != InnerStmt) { 1983 SrcContexts.push_back(NextSrcContext); 1984 InnerStmt = NextSrcContext.asStmt(); 1985 NextSrcContext = getEnclosingStmtLocation(InnerStmt, SM, PM, LCtx, 1986 /*allowNested=*/true); 1987 } 1988 1989 // Repeatedly split the edge as necessary. 1990 // This is important for nested logical expressions (||, &&, ?:) where we 1991 // want to show all the levels of context. 1992 while (true) { 1993 const Stmt *Dst = getLocStmt(Piece->getEndLocation()); 1994 1995 // We are looking at an edge. Is the destination within a larger 1996 // expression? 1997 PathDiagnosticLocation DstContext = 1998 getEnclosingStmtLocation(Dst, SM, PM, LCtx, /*allowNested=*/true); 1999 if (!DstContext.isValid() || DstContext.asStmt() == Dst) 2000 break; 2001 2002 // If the source is in the same context, we're already good. 2003 if (std::find(SrcContexts.begin(), SrcContexts.end(), DstContext) != 2004 SrcContexts.end()) 2005 break; 2006 2007 // Update the subexpression node to point to the context edge. 2008 Piece->setStartLocation(DstContext); 2009 2010 // Try to extend the previous edge if it's at the same level as the source 2011 // context. 2012 if (Prev != E) { 2013 PathDiagnosticControlFlowPiece *PrevPiece = 2014 dyn_cast<PathDiagnosticControlFlowPiece>(*Prev); 2015 2016 if (PrevPiece) { 2017 if (const Stmt *PrevSrc = getLocStmt(PrevPiece->getStartLocation())) { 2018 const Stmt *PrevSrcParent = getStmtParent(PrevSrc, PM); 2019 if (PrevSrcParent == getStmtParent(getLocStmt(DstContext), PM)) { 2020 PrevPiece->setEndLocation(DstContext); 2021 break; 2022 } 2023 } 2024 } 2025 } 2026 2027 // Otherwise, split the current edge into a context edge and a 2028 // subexpression edge. Note that the context statement may itself have 2029 // context. 2030 Piece = new PathDiagnosticControlFlowPiece(SrcLoc, DstContext); 2031 I = pieces.insert(I, Piece); 2032 } 2033 } 2034} 2035 2036/// \brief Move edges from a branch condition to a branch target 2037/// when the condition is simple. 2038/// 2039/// This restructures some of the work of addContextEdges. That function 2040/// creates edges this may destroy, but they work together to create a more 2041/// aesthetically set of edges around branches. After the call to 2042/// addContextEdges, we may have (1) an edge to the branch, (2) an edge from 2043/// the branch to the branch condition, and (3) an edge from the branch 2044/// condition to the branch target. We keep (1), but may wish to remove (2) 2045/// and move the source of (3) to the branch if the branch condition is simple. 2046/// 2047static void simplifySimpleBranches(PathPieces &pieces) { 2048 for (PathPieces::iterator I = pieces.begin(), E = pieces.end(); I != E; ++I) { 2049 2050 PathDiagnosticControlFlowPiece *PieceI = 2051 dyn_cast<PathDiagnosticControlFlowPiece>(*I); 2052 2053 if (!PieceI) 2054 continue; 2055 2056 const Stmt *s1Start = getLocStmt(PieceI->getStartLocation()); 2057 const Stmt *s1End = getLocStmt(PieceI->getEndLocation()); 2058 2059 if (!s1Start || !s1End) 2060 continue; 2061 2062 PathPieces::iterator NextI = I; ++NextI; 2063 if (NextI == E) 2064 break; 2065 2066 PathDiagnosticControlFlowPiece *PieceNextI = 0; 2067 2068 while (true) { 2069 if (NextI == E) 2070 break; 2071 2072 PathDiagnosticEventPiece *EV = dyn_cast<PathDiagnosticEventPiece>(*NextI); 2073 if (EV) { 2074 StringRef S = EV->getString(); 2075 if (S == StrEnteringLoop || S == StrLoopBodyZero) { 2076 ++NextI; 2077 continue; 2078 } 2079 break; 2080 } 2081 2082 PieceNextI = dyn_cast<PathDiagnosticControlFlowPiece>(*NextI); 2083 break; 2084 } 2085 2086 if (!PieceNextI) 2087 continue; 2088 2089 const Stmt *s2Start = getLocStmt(PieceNextI->getStartLocation()); 2090 const Stmt *s2End = getLocStmt(PieceNextI->getEndLocation()); 2091 2092 if (!s2Start || !s2End || s1End != s2Start) 2093 continue; 2094 2095 // We only perform this transformation for specific branch kinds. 2096 // We don't want to do this for do..while, for example. 2097 if (!(isa<ForStmt>(s1Start) || isa<WhileStmt>(s1Start) || 2098 isa<IfStmt>(s1Start) || isa<ObjCForCollectionStmt>(s1Start) || 2099 isa<CXXForRangeStmt>(s1Start))) 2100 continue; 2101 2102 // Is s1End the branch condition? 2103 if (!isConditionForTerminator(s1Start, s1End)) 2104 continue; 2105 2106 // Perform the hoisting by eliminating (2) and changing the start 2107 // location of (3). 2108 PieceNextI->setStartLocation(PieceI->getStartLocation()); 2109 I = pieces.erase(I); 2110 } 2111} 2112 2113/// Returns the number of bytes in the given (character-based) SourceRange. 2114/// 2115/// If the locations in the range are not on the same line, returns None. 2116/// 2117/// Note that this does not do a precise user-visible character or column count. 2118static Optional<size_t> getLengthOnSingleLine(SourceManager &SM, 2119 SourceRange Range) { 2120 SourceRange ExpansionRange(SM.getExpansionLoc(Range.getBegin()), 2121 SM.getExpansionRange(Range.getEnd()).second); 2122 2123 FileID FID = SM.getFileID(ExpansionRange.getBegin()); 2124 if (FID != SM.getFileID(ExpansionRange.getEnd())) 2125 return None; 2126 2127 bool Invalid; 2128 const llvm::MemoryBuffer *Buffer = SM.getBuffer(FID, &Invalid); 2129 if (Invalid) 2130 return None; 2131 2132 unsigned BeginOffset = SM.getFileOffset(ExpansionRange.getBegin()); 2133 unsigned EndOffset = SM.getFileOffset(ExpansionRange.getEnd()); 2134 StringRef Snippet = Buffer->getBuffer().slice(BeginOffset, EndOffset); 2135 2136 // We're searching the raw bytes of the buffer here, which might include 2137 // escaped newlines and such. That's okay; we're trying to decide whether the 2138 // SourceRange is covering a large or small amount of space in the user's 2139 // editor. 2140 if (Snippet.find_first_of("\r\n") != StringRef::npos) 2141 return None; 2142 2143 // This isn't Unicode-aware, but it doesn't need to be. 2144 return Snippet.size(); 2145} 2146 2147/// \sa getLengthOnSingleLine(SourceManager, SourceRange) 2148static Optional<size_t> getLengthOnSingleLine(SourceManager &SM, 2149 const Stmt *S) { 2150 return getLengthOnSingleLine(SM, S->getSourceRange()); 2151} 2152 2153/// Eliminate two-edge cycles created by addContextEdges(). 2154/// 2155/// Once all the context edges are in place, there are plenty of cases where 2156/// there's a single edge from a top-level statement to a subexpression, 2157/// followed by a single path note, and then a reverse edge to get back out to 2158/// the top level. If the statement is simple enough, the subexpression edges 2159/// just add noise and make it harder to understand what's going on. 2160/// 2161/// This function only removes edges in pairs, because removing only one edge 2162/// might leave other edges dangling. 2163/// 2164/// This will not remove edges in more complicated situations: 2165/// - if there is more than one "hop" leading to or from a subexpression. 2166/// - if there is an inlined call between the edges instead of a single event. 2167/// - if the whole statement is large enough that having subexpression arrows 2168/// might be helpful. 2169static void removeContextCycles(PathPieces &Path, SourceManager &SM, 2170 ParentMap &PM) { 2171 for (PathPieces::iterator I = Path.begin(), E = Path.end(); I != E; ) { 2172 // Pattern match the current piece and its successor. 2173 PathDiagnosticControlFlowPiece *PieceI = 2174 dyn_cast<PathDiagnosticControlFlowPiece>(*I); 2175 2176 if (!PieceI) { 2177 ++I; 2178 continue; 2179 } 2180 2181 const Stmt *s1Start = getLocStmt(PieceI->getStartLocation()); 2182 const Stmt *s1End = getLocStmt(PieceI->getEndLocation()); 2183 2184 PathPieces::iterator NextI = I; ++NextI; 2185 if (NextI == E) 2186 break; 2187 2188 PathDiagnosticControlFlowPiece *PieceNextI = 2189 dyn_cast<PathDiagnosticControlFlowPiece>(*NextI); 2190 2191 if (!PieceNextI) { 2192 if (isa<PathDiagnosticEventPiece>(*NextI)) { 2193 ++NextI; 2194 if (NextI == E) 2195 break; 2196 PieceNextI = dyn_cast<PathDiagnosticControlFlowPiece>(*NextI); 2197 } 2198 2199 if (!PieceNextI) { 2200 ++I; 2201 continue; 2202 } 2203 } 2204 2205 const Stmt *s2Start = getLocStmt(PieceNextI->getStartLocation()); 2206 const Stmt *s2End = getLocStmt(PieceNextI->getEndLocation()); 2207 2208 if (s1Start && s2Start && s1Start == s2End && s2Start == s1End) { 2209 const size_t MAX_SHORT_LINE_LENGTH = 80; 2210 Optional<size_t> s1Length = getLengthOnSingleLine(SM, s1Start); 2211 if (s1Length && *s1Length <= MAX_SHORT_LINE_LENGTH) { 2212 Optional<size_t> s2Length = getLengthOnSingleLine(SM, s2Start); 2213 if (s2Length && *s2Length <= MAX_SHORT_LINE_LENGTH) { 2214 Path.erase(I); 2215 I = Path.erase(NextI); 2216 continue; 2217 } 2218 } 2219 } 2220 2221 ++I; 2222 } 2223} 2224 2225/// \brief Return true if X is contained by Y. 2226static bool lexicalContains(ParentMap &PM, 2227 const Stmt *X, 2228 const Stmt *Y) { 2229 while (X) { 2230 if (X == Y) 2231 return true; 2232 X = PM.getParent(X); 2233 } 2234 return false; 2235} 2236 2237// Remove short edges on the same line less than 3 columns in difference. 2238static void removePunyEdges(PathPieces &path, 2239 SourceManager &SM, 2240 ParentMap &PM) { 2241 2242 bool erased = false; 2243 2244 for (PathPieces::iterator I = path.begin(), E = path.end(); I != E; 2245 erased ? I : ++I) { 2246 2247 erased = false; 2248 2249 PathDiagnosticControlFlowPiece *PieceI = 2250 dyn_cast<PathDiagnosticControlFlowPiece>(*I); 2251 2252 if (!PieceI) 2253 continue; 2254 2255 const Stmt *start = getLocStmt(PieceI->getStartLocation()); 2256 const Stmt *end = getLocStmt(PieceI->getEndLocation()); 2257 2258 if (!start || !end) 2259 continue; 2260 2261 const Stmt *endParent = PM.getParent(end); 2262 if (!endParent) 2263 continue; 2264 2265 if (isConditionForTerminator(end, endParent)) 2266 continue; 2267 2268 SourceLocation FirstLoc = start->getLocStart(); 2269 SourceLocation SecondLoc = end->getLocStart(); 2270 2271 if (!SM.isWrittenInSameFile(FirstLoc, SecondLoc)) 2272 continue; 2273 if (SM.isBeforeInTranslationUnit(SecondLoc, FirstLoc)) 2274 std::swap(SecondLoc, FirstLoc); 2275 2276 SourceRange EdgeRange(FirstLoc, SecondLoc); 2277 Optional<size_t> ByteWidth = getLengthOnSingleLine(SM, EdgeRange); 2278 2279 // If the statements are on different lines, continue. 2280 if (!ByteWidth) 2281 continue; 2282 2283 const size_t MAX_PUNY_EDGE_LENGTH = 2; 2284 if (*ByteWidth <= MAX_PUNY_EDGE_LENGTH) { 2285 // FIXME: There are enough /bytes/ between the endpoints of the edge, but 2286 // there might not be enough /columns/. A proper user-visible column count 2287 // is probably too expensive, though. 2288 I = path.erase(I); 2289 erased = true; 2290 continue; 2291 } 2292 } 2293} 2294 2295static void removeIdenticalEvents(PathPieces &path) { 2296 for (PathPieces::iterator I = path.begin(), E = path.end(); I != E; ++I) { 2297 PathDiagnosticEventPiece *PieceI = 2298 dyn_cast<PathDiagnosticEventPiece>(*I); 2299 2300 if (!PieceI) 2301 continue; 2302 2303 PathPieces::iterator NextI = I; ++NextI; 2304 if (NextI == E) 2305 return; 2306 2307 PathDiagnosticEventPiece *PieceNextI = 2308 dyn_cast<PathDiagnosticEventPiece>(*NextI); 2309 2310 if (!PieceNextI) 2311 continue; 2312 2313 // Erase the second piece if it has the same exact message text. 2314 if (PieceI->getString() == PieceNextI->getString()) { 2315 path.erase(NextI); 2316 } 2317 } 2318} 2319 2320static bool optimizeEdges(PathPieces &path, SourceManager &SM, 2321 OptimizedCallsSet &OCS, 2322 LocationContextMap &LCM) { 2323 bool hasChanges = false; 2324 const LocationContext *LC = LCM[&path]; 2325 assert(LC); 2326 ParentMap &PM = LC->getParentMap(); 2327 2328 for (PathPieces::iterator I = path.begin(), E = path.end(); I != E; ) { 2329 // Optimize subpaths. 2330 if (PathDiagnosticCallPiece *CallI = dyn_cast<PathDiagnosticCallPiece>(*I)){ 2331 // Record the fact that a call has been optimized so we only do the 2332 // effort once. 2333 if (!OCS.count(CallI)) { 2334 while (optimizeEdges(CallI->path, SM, OCS, LCM)) {} 2335 OCS.insert(CallI); 2336 } 2337 ++I; 2338 continue; 2339 } 2340 2341 // Pattern match the current piece and its successor. 2342 PathDiagnosticControlFlowPiece *PieceI = 2343 dyn_cast<PathDiagnosticControlFlowPiece>(*I); 2344 2345 if (!PieceI) { 2346 ++I; 2347 continue; 2348 } 2349 2350 const Stmt *s1Start = getLocStmt(PieceI->getStartLocation()); 2351 const Stmt *s1End = getLocStmt(PieceI->getEndLocation()); 2352 const Stmt *level1 = getStmtParent(s1Start, PM); 2353 const Stmt *level2 = getStmtParent(s1End, PM); 2354 2355 PathPieces::iterator NextI = I; ++NextI; 2356 if (NextI == E) 2357 break; 2358 2359 PathDiagnosticControlFlowPiece *PieceNextI = 2360 dyn_cast<PathDiagnosticControlFlowPiece>(*NextI); 2361 2362 if (!PieceNextI) { 2363 ++I; 2364 continue; 2365 } 2366 2367 const Stmt *s2Start = getLocStmt(PieceNextI->getStartLocation()); 2368 const Stmt *s2End = getLocStmt(PieceNextI->getEndLocation()); 2369 const Stmt *level3 = getStmtParent(s2Start, PM); 2370 const Stmt *level4 = getStmtParent(s2End, PM); 2371 2372 // Rule I. 2373 // 2374 // If we have two consecutive control edges whose end/begin locations 2375 // are at the same level (e.g. statements or top-level expressions within 2376 // a compound statement, or siblings share a single ancestor expression), 2377 // then merge them if they have no interesting intermediate event. 2378 // 2379 // For example: 2380 // 2381 // (1.1 -> 1.2) -> (1.2 -> 1.3) becomes (1.1 -> 1.3) because the common 2382 // parent is '1'. Here 'x.y.z' represents the hierarchy of statements. 2383 // 2384 // NOTE: this will be limited later in cases where we add barriers 2385 // to prevent this optimization. 2386 // 2387 if (level1 && level1 == level2 && level1 == level3 && level1 == level4) { 2388 PieceI->setEndLocation(PieceNextI->getEndLocation()); 2389 path.erase(NextI); 2390 hasChanges = true; 2391 continue; 2392 } 2393 2394 // Rule II. 2395 // 2396 // Eliminate edges between subexpressions and parent expressions 2397 // when the subexpression is consumed. 2398 // 2399 // NOTE: this will be limited later in cases where we add barriers 2400 // to prevent this optimization. 2401 // 2402 if (s1End && s1End == s2Start && level2) { 2403 bool removeEdge = false; 2404 // Remove edges into the increment or initialization of a 2405 // loop that have no interleaving event. This means that 2406 // they aren't interesting. 2407 if (isIncrementOrInitInForLoop(s1End, level2)) 2408 removeEdge = true; 2409 // Next only consider edges that are not anchored on 2410 // the condition of a terminator. This are intermediate edges 2411 // that we might want to trim. 2412 else if (!isConditionForTerminator(level2, s1End)) { 2413 // Trim edges on expressions that are consumed by 2414 // the parent expression. 2415 if (isa<Expr>(s1End) && PM.isConsumedExpr(cast<Expr>(s1End))) { 2416 removeEdge = true; 2417 } 2418 // Trim edges where a lexical containment doesn't exist. 2419 // For example: 2420 // 2421 // X -> Y -> Z 2422 // 2423 // If 'Z' lexically contains Y (it is an ancestor) and 2424 // 'X' does not lexically contain Y (it is a descendant OR 2425 // it has no lexical relationship at all) then trim. 2426 // 2427 // This can eliminate edges where we dive into a subexpression 2428 // and then pop back out, etc. 2429 else if (s1Start && s2End && 2430 lexicalContains(PM, s2Start, s2End) && 2431 !lexicalContains(PM, s1End, s1Start)) { 2432 removeEdge = true; 2433 } 2434 // Trim edges from a subexpression back to the top level if the 2435 // subexpression is on a different line. 2436 // 2437 // A.1 -> A -> B 2438 // becomes 2439 // A.1 -> B 2440 // 2441 // These edges just look ugly and don't usually add anything. 2442 else if (s1Start && s2End && 2443 lexicalContains(PM, s1Start, s1End)) { 2444 SourceRange EdgeRange(PieceI->getEndLocation().asLocation(), 2445 PieceI->getStartLocation().asLocation()); 2446 if (!getLengthOnSingleLine(SM, EdgeRange).hasValue()) 2447 removeEdge = true; 2448 } 2449 } 2450 2451 if (removeEdge) { 2452 PieceI->setEndLocation(PieceNextI->getEndLocation()); 2453 path.erase(NextI); 2454 hasChanges = true; 2455 continue; 2456 } 2457 } 2458 2459 // Optimize edges for ObjC fast-enumeration loops. 2460 // 2461 // (X -> collection) -> (collection -> element) 2462 // 2463 // becomes: 2464 // 2465 // (X -> element) 2466 if (s1End == s2Start) { 2467 const ObjCForCollectionStmt *FS = 2468 dyn_cast_or_null<ObjCForCollectionStmt>(level3); 2469 if (FS && FS->getCollection()->IgnoreParens() == s2Start && 2470 s2End == FS->getElement()) { 2471 PieceI->setEndLocation(PieceNextI->getEndLocation()); 2472 path.erase(NextI); 2473 hasChanges = true; 2474 continue; 2475 } 2476 } 2477 2478 // No changes at this index? Move to the next one. 2479 ++I; 2480 } 2481 2482 if (!hasChanges) { 2483 // Adjust edges into subexpressions to make them more uniform 2484 // and aesthetically pleasing. 2485 addContextEdges(path, SM, PM, LC); 2486 // Remove "cyclical" edges that include one or more context edges. 2487 removeContextCycles(path, SM, PM); 2488 // Hoist edges originating from branch conditions to branches 2489 // for simple branches. 2490 simplifySimpleBranches(path); 2491 // Remove any puny edges left over after primary optimization pass. 2492 removePunyEdges(path, SM, PM); 2493 // Remove identical events. 2494 removeIdenticalEvents(path); 2495 } 2496 2497 return hasChanges; 2498} 2499 2500/// Drop the very first edge in a path, which should be a function entry edge. 2501/// 2502/// If the first edge is not a function entry edge (say, because the first 2503/// statement had an invalid source location), this function does nothing. 2504// FIXME: We should just generate invalid edges anyway and have the optimizer 2505// deal with them. 2506static void dropFunctionEntryEdge(PathPieces &Path, 2507 LocationContextMap &LCM, 2508 SourceManager &SM) { 2509 const PathDiagnosticControlFlowPiece *FirstEdge = 2510 dyn_cast<PathDiagnosticControlFlowPiece>(Path.front()); 2511 if (!FirstEdge) 2512 return; 2513 2514 const Decl *D = LCM[&Path]->getDecl(); 2515 PathDiagnosticLocation EntryLoc = PathDiagnosticLocation::createBegin(D, SM); 2516 if (FirstEdge->getStartLocation() != EntryLoc) 2517 return; 2518 2519 Path.pop_front(); 2520} 2521 2522 2523//===----------------------------------------------------------------------===// 2524// Methods for BugType and subclasses. 2525//===----------------------------------------------------------------------===// 2526void BugType::anchor() { } 2527 2528void BugType::FlushReports(BugReporter &BR) {} 2529 2530void BuiltinBug::anchor() {} 2531 2532//===----------------------------------------------------------------------===// 2533// Methods for BugReport and subclasses. 2534//===----------------------------------------------------------------------===// 2535 2536void BugReport::NodeResolver::anchor() {} 2537 2538void BugReport::addVisitor(BugReporterVisitor* visitor) { 2539 if (!visitor) 2540 return; 2541 2542 llvm::FoldingSetNodeID ID; 2543 visitor->Profile(ID); 2544 void *InsertPos; 2545 2546 if (CallbacksSet.FindNodeOrInsertPos(ID, InsertPos)) { 2547 delete visitor; 2548 return; 2549 } 2550 2551 CallbacksSet.InsertNode(visitor, InsertPos); 2552 Callbacks.push_back(visitor); 2553 ++ConfigurationChangeToken; 2554} 2555 2556BugReport::~BugReport() { 2557 for (visitor_iterator I = visitor_begin(), E = visitor_end(); I != E; ++I) { 2558 delete *I; 2559 } 2560 while (!interestingSymbols.empty()) { 2561 popInterestingSymbolsAndRegions(); 2562 } 2563} 2564 2565const Decl *BugReport::getDeclWithIssue() const { 2566 if (DeclWithIssue) 2567 return DeclWithIssue; 2568 2569 const ExplodedNode *N = getErrorNode(); 2570 if (!N) 2571 return 0; 2572 2573 const LocationContext *LC = N->getLocationContext(); 2574 return LC->getCurrentStackFrame()->getDecl(); 2575} 2576 2577void BugReport::Profile(llvm::FoldingSetNodeID& hash) const { 2578 hash.AddPointer(&BT); 2579 hash.AddString(Description); 2580 PathDiagnosticLocation UL = getUniqueingLocation(); 2581 if (UL.isValid()) { 2582 UL.Profile(hash); 2583 } else if (Location.isValid()) { 2584 Location.Profile(hash); 2585 } else { 2586 assert(ErrorNode); 2587 hash.AddPointer(GetCurrentOrPreviousStmt(ErrorNode)); 2588 } 2589 2590 for (SmallVectorImpl<SourceRange>::const_iterator I = 2591 Ranges.begin(), E = Ranges.end(); I != E; ++I) { 2592 const SourceRange range = *I; 2593 if (!range.isValid()) 2594 continue; 2595 hash.AddInteger(range.getBegin().getRawEncoding()); 2596 hash.AddInteger(range.getEnd().getRawEncoding()); 2597 } 2598} 2599 2600void BugReport::markInteresting(SymbolRef sym) { 2601 if (!sym) 2602 return; 2603 2604 // If the symbol wasn't already in our set, note a configuration change. 2605 if (getInterestingSymbols().insert(sym).second) 2606 ++ConfigurationChangeToken; 2607 2608 if (const SymbolMetadata *meta = dyn_cast<SymbolMetadata>(sym)) 2609 getInterestingRegions().insert(meta->getRegion()); 2610} 2611 2612void BugReport::markInteresting(const MemRegion *R) { 2613 if (!R) 2614 return; 2615 2616 // If the base region wasn't already in our set, note a configuration change. 2617 R = R->getBaseRegion(); 2618 if (getInterestingRegions().insert(R).second) 2619 ++ConfigurationChangeToken; 2620 2621 if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R)) 2622 getInterestingSymbols().insert(SR->getSymbol()); 2623} 2624 2625void BugReport::markInteresting(SVal V) { 2626 markInteresting(V.getAsRegion()); 2627 markInteresting(V.getAsSymbol()); 2628} 2629 2630void BugReport::markInteresting(const LocationContext *LC) { 2631 if (!LC) 2632 return; 2633 InterestingLocationContexts.insert(LC); 2634} 2635 2636bool BugReport::isInteresting(SVal V) { 2637 return isInteresting(V.getAsRegion()) || isInteresting(V.getAsSymbol()); 2638} 2639 2640bool BugReport::isInteresting(SymbolRef sym) { 2641 if (!sym) 2642 return false; 2643 // We don't currently consider metadata symbols to be interesting 2644 // even if we know their region is interesting. Is that correct behavior? 2645 return getInterestingSymbols().count(sym); 2646} 2647 2648bool BugReport::isInteresting(const MemRegion *R) { 2649 if (!R) 2650 return false; 2651 R = R->getBaseRegion(); 2652 bool b = getInterestingRegions().count(R); 2653 if (b) 2654 return true; 2655 if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R)) 2656 return getInterestingSymbols().count(SR->getSymbol()); 2657 return false; 2658} 2659 2660bool BugReport::isInteresting(const LocationContext *LC) { 2661 if (!LC) 2662 return false; 2663 return InterestingLocationContexts.count(LC); 2664} 2665 2666void BugReport::lazyInitializeInterestingSets() { 2667 if (interestingSymbols.empty()) { 2668 interestingSymbols.push_back(new Symbols()); 2669 interestingRegions.push_back(new Regions()); 2670 } 2671} 2672 2673BugReport::Symbols &BugReport::getInterestingSymbols() { 2674 lazyInitializeInterestingSets(); 2675 return *interestingSymbols.back(); 2676} 2677 2678BugReport::Regions &BugReport::getInterestingRegions() { 2679 lazyInitializeInterestingSets(); 2680 return *interestingRegions.back(); 2681} 2682 2683void BugReport::pushInterestingSymbolsAndRegions() { 2684 interestingSymbols.push_back(new Symbols(getInterestingSymbols())); 2685 interestingRegions.push_back(new Regions(getInterestingRegions())); 2686} 2687 2688void BugReport::popInterestingSymbolsAndRegions() { 2689 delete interestingSymbols.pop_back_val(); 2690 delete interestingRegions.pop_back_val(); 2691} 2692 2693const Stmt *BugReport::getStmt() const { 2694 if (!ErrorNode) 2695 return 0; 2696 2697 ProgramPoint ProgP = ErrorNode->getLocation(); 2698 const Stmt *S = NULL; 2699 2700 if (Optional<BlockEntrance> BE = ProgP.getAs<BlockEntrance>()) { 2701 CFGBlock &Exit = ProgP.getLocationContext()->getCFG()->getExit(); 2702 if (BE->getBlock() == &Exit) 2703 S = GetPreviousStmt(ErrorNode); 2704 } 2705 if (!S) 2706 S = PathDiagnosticLocation::getStmt(ErrorNode); 2707 2708 return S; 2709} 2710 2711std::pair<BugReport::ranges_iterator, BugReport::ranges_iterator> 2712BugReport::getRanges() { 2713 // If no custom ranges, add the range of the statement corresponding to 2714 // the error node. 2715 if (Ranges.empty()) { 2716 if (const Expr *E = dyn_cast_or_null<Expr>(getStmt())) 2717 addRange(E->getSourceRange()); 2718 else 2719 return std::make_pair(ranges_iterator(), ranges_iterator()); 2720 } 2721 2722 // User-specified absence of range info. 2723 if (Ranges.size() == 1 && !Ranges.begin()->isValid()) 2724 return std::make_pair(ranges_iterator(), ranges_iterator()); 2725 2726 return std::make_pair(Ranges.begin(), Ranges.end()); 2727} 2728 2729PathDiagnosticLocation BugReport::getLocation(const SourceManager &SM) const { 2730 if (ErrorNode) { 2731 assert(!Location.isValid() && 2732 "Either Location or ErrorNode should be specified but not both."); 2733 return PathDiagnosticLocation::createEndOfPath(ErrorNode, SM); 2734 } else { 2735 assert(Location.isValid()); 2736 return Location; 2737 } 2738 2739 return PathDiagnosticLocation(); 2740} 2741 2742//===----------------------------------------------------------------------===// 2743// Methods for BugReporter and subclasses. 2744//===----------------------------------------------------------------------===// 2745 2746BugReportEquivClass::~BugReportEquivClass() { } 2747GRBugReporter::~GRBugReporter() { } 2748BugReporterData::~BugReporterData() {} 2749 2750ExplodedGraph &GRBugReporter::getGraph() { return Eng.getGraph(); } 2751 2752ProgramStateManager& 2753GRBugReporter::getStateManager() { return Eng.getStateManager(); } 2754 2755BugReporter::~BugReporter() { 2756 FlushReports(); 2757 2758 // Free the bug reports we are tracking. 2759 typedef std::vector<BugReportEquivClass *> ContTy; 2760 for (ContTy::iterator I = EQClassesVector.begin(), E = EQClassesVector.end(); 2761 I != E; ++I) { 2762 delete *I; 2763 } 2764} 2765 2766void BugReporter::FlushReports() { 2767 if (BugTypes.isEmpty()) 2768 return; 2769 2770 // First flush the warnings for each BugType. This may end up creating new 2771 // warnings and new BugTypes. 2772 // FIXME: Only NSErrorChecker needs BugType's FlushReports. 2773 // Turn NSErrorChecker into a proper checker and remove this. 2774 SmallVector<const BugType*, 16> bugTypes; 2775 for (BugTypesTy::iterator I=BugTypes.begin(), E=BugTypes.end(); I!=E; ++I) 2776 bugTypes.push_back(*I); 2777 for (SmallVectorImpl<const BugType *>::iterator 2778 I = bugTypes.begin(), E = bugTypes.end(); I != E; ++I) 2779 const_cast<BugType*>(*I)->FlushReports(*this); 2780 2781 // We need to flush reports in deterministic order to ensure the order 2782 // of the reports is consistent between runs. 2783 typedef std::vector<BugReportEquivClass *> ContVecTy; 2784 for (ContVecTy::iterator EI=EQClassesVector.begin(), EE=EQClassesVector.end(); 2785 EI != EE; ++EI){ 2786 BugReportEquivClass& EQ = **EI; 2787 FlushReport(EQ); 2788 } 2789 2790 // BugReporter owns and deletes only BugTypes created implicitly through 2791 // EmitBasicReport. 2792 // FIXME: There are leaks from checkers that assume that the BugTypes they 2793 // create will be destroyed by the BugReporter. 2794 for (llvm::StringMap<BugType*>::iterator 2795 I = StrBugTypes.begin(), E = StrBugTypes.end(); I != E; ++I) 2796 delete I->second; 2797 2798 // Remove all references to the BugType objects. 2799 BugTypes = F.getEmptySet(); 2800} 2801 2802//===----------------------------------------------------------------------===// 2803// PathDiagnostics generation. 2804//===----------------------------------------------------------------------===// 2805 2806namespace { 2807/// A wrapper around a report graph, which contains only a single path, and its 2808/// node maps. 2809class ReportGraph { 2810public: 2811 InterExplodedGraphMap BackMap; 2812 OwningPtr<ExplodedGraph> Graph; 2813 const ExplodedNode *ErrorNode; 2814 size_t Index; 2815}; 2816 2817/// A wrapper around a trimmed graph and its node maps. 2818class TrimmedGraph { 2819 InterExplodedGraphMap InverseMap; 2820 2821 typedef llvm::DenseMap<const ExplodedNode *, unsigned> PriorityMapTy; 2822 PriorityMapTy PriorityMap; 2823 2824 typedef std::pair<const ExplodedNode *, size_t> NodeIndexPair; 2825 SmallVector<NodeIndexPair, 32> ReportNodes; 2826 2827 OwningPtr<ExplodedGraph> G; 2828 2829 /// A helper class for sorting ExplodedNodes by priority. 2830 template <bool Descending> 2831 class PriorityCompare { 2832 const PriorityMapTy &PriorityMap; 2833 2834 public: 2835 PriorityCompare(const PriorityMapTy &M) : PriorityMap(M) {} 2836 2837 bool operator()(const ExplodedNode *LHS, const ExplodedNode *RHS) const { 2838 PriorityMapTy::const_iterator LI = PriorityMap.find(LHS); 2839 PriorityMapTy::const_iterator RI = PriorityMap.find(RHS); 2840 PriorityMapTy::const_iterator E = PriorityMap.end(); 2841 2842 if (LI == E) 2843 return Descending; 2844 if (RI == E) 2845 return !Descending; 2846 2847 return Descending ? LI->second > RI->second 2848 : LI->second < RI->second; 2849 } 2850 2851 bool operator()(const NodeIndexPair &LHS, const NodeIndexPair &RHS) const { 2852 return (*this)(LHS.first, RHS.first); 2853 } 2854 }; 2855 2856public: 2857 TrimmedGraph(const ExplodedGraph *OriginalGraph, 2858 ArrayRef<const ExplodedNode *> Nodes); 2859 2860 bool popNextReportGraph(ReportGraph &GraphWrapper); 2861}; 2862} 2863 2864TrimmedGraph::TrimmedGraph(const ExplodedGraph *OriginalGraph, 2865 ArrayRef<const ExplodedNode *> Nodes) { 2866 // The trimmed graph is created in the body of the constructor to ensure 2867 // that the DenseMaps have been initialized already. 2868 InterExplodedGraphMap ForwardMap; 2869 G.reset(OriginalGraph->trim(Nodes, &ForwardMap, &InverseMap)); 2870 2871 // Find the (first) error node in the trimmed graph. We just need to consult 2872 // the node map which maps from nodes in the original graph to nodes 2873 // in the new graph. 2874 llvm::SmallPtrSet<const ExplodedNode *, 32> RemainingNodes; 2875 2876 for (unsigned i = 0, count = Nodes.size(); i < count; ++i) { 2877 if (const ExplodedNode *NewNode = ForwardMap.lookup(Nodes[i])) { 2878 ReportNodes.push_back(std::make_pair(NewNode, i)); 2879 RemainingNodes.insert(NewNode); 2880 } 2881 } 2882 2883 assert(!RemainingNodes.empty() && "No error node found in the trimmed graph"); 2884 2885 // Perform a forward BFS to find all the shortest paths. 2886 std::queue<const ExplodedNode *> WS; 2887 2888 assert(G->num_roots() == 1); 2889 WS.push(*G->roots_begin()); 2890 unsigned Priority = 0; 2891 2892 while (!WS.empty()) { 2893 const ExplodedNode *Node = WS.front(); 2894 WS.pop(); 2895 2896 PriorityMapTy::iterator PriorityEntry; 2897 bool IsNew; 2898 llvm::tie(PriorityEntry, IsNew) = 2899 PriorityMap.insert(std::make_pair(Node, Priority)); 2900 ++Priority; 2901 2902 if (!IsNew) { 2903 assert(PriorityEntry->second <= Priority); 2904 continue; 2905 } 2906 2907 if (RemainingNodes.erase(Node)) 2908 if (RemainingNodes.empty()) 2909 break; 2910 2911 for (ExplodedNode::const_pred_iterator I = Node->succ_begin(), 2912 E = Node->succ_end(); 2913 I != E; ++I) 2914 WS.push(*I); 2915 } 2916 2917 // Sort the error paths from longest to shortest. 2918 std::sort(ReportNodes.begin(), ReportNodes.end(), 2919 PriorityCompare<true>(PriorityMap)); 2920} 2921 2922bool TrimmedGraph::popNextReportGraph(ReportGraph &GraphWrapper) { 2923 if (ReportNodes.empty()) 2924 return false; 2925 2926 const ExplodedNode *OrigN; 2927 llvm::tie(OrigN, GraphWrapper.Index) = ReportNodes.pop_back_val(); 2928 assert(PriorityMap.find(OrigN) != PriorityMap.end() && 2929 "error node not accessible from root"); 2930 2931 // Create a new graph with a single path. This is the graph 2932 // that will be returned to the caller. 2933 ExplodedGraph *GNew = new ExplodedGraph(); 2934 GraphWrapper.Graph.reset(GNew); 2935 GraphWrapper.BackMap.clear(); 2936 2937 // Now walk from the error node up the BFS path, always taking the 2938 // predeccessor with the lowest number. 2939 ExplodedNode *Succ = 0; 2940 while (true) { 2941 // Create the equivalent node in the new graph with the same state 2942 // and location. 2943 ExplodedNode *NewN = GNew->getNode(OrigN->getLocation(), OrigN->getState(), 2944 OrigN->isSink()); 2945 2946 // Store the mapping to the original node. 2947 InterExplodedGraphMap::const_iterator IMitr = InverseMap.find(OrigN); 2948 assert(IMitr != InverseMap.end() && "No mapping to original node."); 2949 GraphWrapper.BackMap[NewN] = IMitr->second; 2950 2951 // Link up the new node with the previous node. 2952 if (Succ) 2953 Succ->addPredecessor(NewN, *GNew); 2954 else 2955 GraphWrapper.ErrorNode = NewN; 2956 2957 Succ = NewN; 2958 2959 // Are we at the final node? 2960 if (OrigN->pred_empty()) { 2961 GNew->addRoot(NewN); 2962 break; 2963 } 2964 2965 // Find the next predeccessor node. We choose the node that is marked 2966 // with the lowest BFS number. 2967 OrigN = *std::min_element(OrigN->pred_begin(), OrigN->pred_end(), 2968 PriorityCompare<false>(PriorityMap)); 2969 } 2970 2971 return true; 2972} 2973 2974 2975/// CompactPathDiagnostic - This function postprocesses a PathDiagnostic object 2976/// and collapses PathDiagosticPieces that are expanded by macros. 2977static void CompactPathDiagnostic(PathPieces &path, const SourceManager& SM) { 2978 typedef std::vector<std::pair<IntrusiveRefCntPtr<PathDiagnosticMacroPiece>, 2979 SourceLocation> > MacroStackTy; 2980 2981 typedef std::vector<IntrusiveRefCntPtr<PathDiagnosticPiece> > 2982 PiecesTy; 2983 2984 MacroStackTy MacroStack; 2985 PiecesTy Pieces; 2986 2987 for (PathPieces::const_iterator I = path.begin(), E = path.end(); 2988 I!=E; ++I) { 2989 2990 PathDiagnosticPiece *piece = I->getPtr(); 2991 2992 // Recursively compact calls. 2993 if (PathDiagnosticCallPiece *call=dyn_cast<PathDiagnosticCallPiece>(piece)){ 2994 CompactPathDiagnostic(call->path, SM); 2995 } 2996 2997 // Get the location of the PathDiagnosticPiece. 2998 const FullSourceLoc Loc = piece->getLocation().asLocation(); 2999 3000 // Determine the instantiation location, which is the location we group 3001 // related PathDiagnosticPieces. 3002 SourceLocation InstantiationLoc = Loc.isMacroID() ? 3003 SM.getExpansionLoc(Loc) : 3004 SourceLocation(); 3005 3006 if (Loc.isFileID()) { 3007 MacroStack.clear(); 3008 Pieces.push_back(piece); 3009 continue; 3010 } 3011 3012 assert(Loc.isMacroID()); 3013 3014 // Is the PathDiagnosticPiece within the same macro group? 3015 if (!MacroStack.empty() && InstantiationLoc == MacroStack.back().second) { 3016 MacroStack.back().first->subPieces.push_back(piece); 3017 continue; 3018 } 3019 3020 // We aren't in the same group. Are we descending into a new macro 3021 // or are part of an old one? 3022 IntrusiveRefCntPtr<PathDiagnosticMacroPiece> MacroGroup; 3023 3024 SourceLocation ParentInstantiationLoc = InstantiationLoc.isMacroID() ? 3025 SM.getExpansionLoc(Loc) : 3026 SourceLocation(); 3027 3028 // Walk the entire macro stack. 3029 while (!MacroStack.empty()) { 3030 if (InstantiationLoc == MacroStack.back().second) { 3031 MacroGroup = MacroStack.back().first; 3032 break; 3033 } 3034 3035 if (ParentInstantiationLoc == MacroStack.back().second) { 3036 MacroGroup = MacroStack.back().first; 3037 break; 3038 } 3039 3040 MacroStack.pop_back(); 3041 } 3042 3043 if (!MacroGroup || ParentInstantiationLoc == MacroStack.back().second) { 3044 // Create a new macro group and add it to the stack. 3045 PathDiagnosticMacroPiece *NewGroup = 3046 new PathDiagnosticMacroPiece( 3047 PathDiagnosticLocation::createSingleLocation(piece->getLocation())); 3048 3049 if (MacroGroup) 3050 MacroGroup->subPieces.push_back(NewGroup); 3051 else { 3052 assert(InstantiationLoc.isFileID()); 3053 Pieces.push_back(NewGroup); 3054 } 3055 3056 MacroGroup = NewGroup; 3057 MacroStack.push_back(std::make_pair(MacroGroup, InstantiationLoc)); 3058 } 3059 3060 // Finally, add the PathDiagnosticPiece to the group. 3061 MacroGroup->subPieces.push_back(piece); 3062 } 3063 3064 // Now take the pieces and construct a new PathDiagnostic. 3065 path.clear(); 3066 3067 for (PiecesTy::iterator I=Pieces.begin(), E=Pieces.end(); I!=E; ++I) 3068 path.push_back(*I); 3069} 3070 3071bool GRBugReporter::generatePathDiagnostic(PathDiagnostic& PD, 3072 PathDiagnosticConsumer &PC, 3073 ArrayRef<BugReport *> &bugReports) { 3074 assert(!bugReports.empty()); 3075 3076 bool HasValid = false; 3077 bool HasInvalid = false; 3078 SmallVector<const ExplodedNode *, 32> errorNodes; 3079 for (ArrayRef<BugReport*>::iterator I = bugReports.begin(), 3080 E = bugReports.end(); I != E; ++I) { 3081 if ((*I)->isValid()) { 3082 HasValid = true; 3083 errorNodes.push_back((*I)->getErrorNode()); 3084 } else { 3085 // Keep the errorNodes list in sync with the bugReports list. 3086 HasInvalid = true; 3087 errorNodes.push_back(0); 3088 } 3089 } 3090 3091 // If all the reports have been marked invalid by a previous path generation, 3092 // we're done. 3093 if (!HasValid) 3094 return false; 3095 3096 typedef PathDiagnosticConsumer::PathGenerationScheme PathGenerationScheme; 3097 PathGenerationScheme ActiveScheme = PC.getGenerationScheme(); 3098 3099 if (ActiveScheme == PathDiagnosticConsumer::Extensive) { 3100 AnalyzerOptions &options = getAnalyzerOptions(); 3101 if (options.getBooleanOption("path-diagnostics-alternate", true)) { 3102 ActiveScheme = PathDiagnosticConsumer::AlternateExtensive; 3103 } 3104 } 3105 3106 TrimmedGraph TrimG(&getGraph(), errorNodes); 3107 ReportGraph ErrorGraph; 3108 3109 while (TrimG.popNextReportGraph(ErrorGraph)) { 3110 // Find the BugReport with the original location. 3111 assert(ErrorGraph.Index < bugReports.size()); 3112 BugReport *R = bugReports[ErrorGraph.Index]; 3113 assert(R && "No original report found for sliced graph."); 3114 assert(R->isValid() && "Report selected by trimmed graph marked invalid."); 3115 3116 // Start building the path diagnostic... 3117 PathDiagnosticBuilder PDB(*this, R, ErrorGraph.BackMap, &PC); 3118 const ExplodedNode *N = ErrorGraph.ErrorNode; 3119 3120 // Register additional node visitors. 3121 R->addVisitor(new NilReceiverBRVisitor()); 3122 R->addVisitor(new ConditionBRVisitor()); 3123 R->addVisitor(new LikelyFalsePositiveSuppressionBRVisitor()); 3124 3125 BugReport::VisitorList visitors; 3126 unsigned origReportConfigToken, finalReportConfigToken; 3127 LocationContextMap LCM; 3128 3129 // While generating diagnostics, it's possible the visitors will decide 3130 // new symbols and regions are interesting, or add other visitors based on 3131 // the information they find. If they do, we need to regenerate the path 3132 // based on our new report configuration. 3133 do { 3134 // Get a clean copy of all the visitors. 3135 for (BugReport::visitor_iterator I = R->visitor_begin(), 3136 E = R->visitor_end(); I != E; ++I) 3137 visitors.push_back((*I)->clone()); 3138 3139 // Clear out the active path from any previous work. 3140 PD.resetPath(); 3141 origReportConfigToken = R->getConfigurationChangeToken(); 3142 3143 // Generate the very last diagnostic piece - the piece is visible before 3144 // the trace is expanded. 3145 PathDiagnosticPiece *LastPiece = 0; 3146 for (BugReport::visitor_iterator I = visitors.begin(), E = visitors.end(); 3147 I != E; ++I) { 3148 if (PathDiagnosticPiece *Piece = (*I)->getEndPath(PDB, N, *R)) { 3149 assert (!LastPiece && 3150 "There can only be one final piece in a diagnostic."); 3151 LastPiece = Piece; 3152 } 3153 } 3154 3155 if (ActiveScheme != PathDiagnosticConsumer::None) { 3156 if (!LastPiece) 3157 LastPiece = BugReporterVisitor::getDefaultEndPath(PDB, N, *R); 3158 assert(LastPiece); 3159 PD.setEndOfPath(LastPiece); 3160 } 3161 3162 // Make sure we get a clean location context map so we don't 3163 // hold onto old mappings. 3164 LCM.clear(); 3165 3166 switch (ActiveScheme) { 3167 case PathDiagnosticConsumer::AlternateExtensive: 3168 GenerateAlternateExtensivePathDiagnostic(PD, PDB, N, LCM, visitors); 3169 break; 3170 case PathDiagnosticConsumer::Extensive: 3171 GenerateExtensivePathDiagnostic(PD, PDB, N, LCM, visitors); 3172 break; 3173 case PathDiagnosticConsumer::Minimal: 3174 GenerateMinimalPathDiagnostic(PD, PDB, N, LCM, visitors); 3175 break; 3176 case PathDiagnosticConsumer::None: 3177 GenerateVisitorsOnlyPathDiagnostic(PD, PDB, N, visitors); 3178 break; 3179 } 3180 3181 // Clean up the visitors we used. 3182 llvm::DeleteContainerPointers(visitors); 3183 3184 // Did anything change while generating this path? 3185 finalReportConfigToken = R->getConfigurationChangeToken(); 3186 } while (finalReportConfigToken != origReportConfigToken); 3187 3188 if (!R->isValid()) 3189 continue; 3190 3191 // Finally, prune the diagnostic path of uninteresting stuff. 3192 if (!PD.path.empty()) { 3193 if (R->shouldPrunePath() && getAnalyzerOptions().shouldPrunePaths()) { 3194 bool stillHasNotes = removeUnneededCalls(PD.getMutablePieces(), R, LCM); 3195 assert(stillHasNotes); 3196 (void)stillHasNotes; 3197 } 3198 3199 // Redirect all call pieces to have valid locations. 3200 adjustCallLocations(PD.getMutablePieces()); 3201 removePiecesWithInvalidLocations(PD.getMutablePieces()); 3202 3203 if (ActiveScheme == PathDiagnosticConsumer::AlternateExtensive) { 3204 SourceManager &SM = getSourceManager(); 3205 3206 // Reduce the number of edges from a very conservative set 3207 // to an aesthetically pleasing subset that conveys the 3208 // necessary information. 3209 OptimizedCallsSet OCS; 3210 while (optimizeEdges(PD.getMutablePieces(), SM, OCS, LCM)) {} 3211 3212 // Drop the very first function-entry edge. It's not really necessary 3213 // for top-level functions. 3214 dropFunctionEntryEdge(PD.getMutablePieces(), LCM, SM); 3215 } 3216 3217 // Remove messages that are basically the same, and edges that may not 3218 // make sense. 3219 // We have to do this after edge optimization in the Extensive mode. 3220 removeRedundantMsgs(PD.getMutablePieces()); 3221 removeEdgesToDefaultInitializers(PD.getMutablePieces()); 3222 } 3223 3224 // We found a report and didn't suppress it. 3225 return true; 3226 } 3227 3228 // We suppressed all the reports in this equivalence class. 3229 assert(!HasInvalid && "Inconsistent suppression"); 3230 (void)HasInvalid; 3231 return false; 3232} 3233 3234void BugReporter::Register(BugType *BT) { 3235 BugTypes = F.add(BugTypes, BT); 3236} 3237 3238void BugReporter::emitReport(BugReport* R) { 3239 // Defensive checking: throw the bug away if it comes from a BodyFarm- 3240 // generated body. We do this very early because report processing relies 3241 // on the report's location being valid. 3242 // FIXME: Valid bugs can occur in BodyFarm-generated bodies, so really we 3243 // need to just find a reasonable location like we do later on with the path 3244 // pieces. 3245 if (const ExplodedNode *E = R->getErrorNode()) { 3246 const LocationContext *LCtx = E->getLocationContext(); 3247 if (LCtx->getAnalysisDeclContext()->isBodyAutosynthesized()) 3248 return; 3249 } 3250 3251 bool ValidSourceLoc = R->getLocation(getSourceManager()).isValid(); 3252 assert(ValidSourceLoc); 3253 // If we mess up in a release build, we'd still prefer to just drop the bug 3254 // instead of trying to go on. 3255 if (!ValidSourceLoc) 3256 return; 3257 3258 // Compute the bug report's hash to determine its equivalence class. 3259 llvm::FoldingSetNodeID ID; 3260 R->Profile(ID); 3261 3262 // Lookup the equivance class. If there isn't one, create it. 3263 BugType& BT = R->getBugType(); 3264 Register(&BT); 3265 void *InsertPos; 3266 BugReportEquivClass* EQ = EQClasses.FindNodeOrInsertPos(ID, InsertPos); 3267 3268 if (!EQ) { 3269 EQ = new BugReportEquivClass(R); 3270 EQClasses.InsertNode(EQ, InsertPos); 3271 EQClassesVector.push_back(EQ); 3272 } 3273 else 3274 EQ->AddReport(R); 3275} 3276 3277 3278//===----------------------------------------------------------------------===// 3279// Emitting reports in equivalence classes. 3280//===----------------------------------------------------------------------===// 3281 3282namespace { 3283struct FRIEC_WLItem { 3284 const ExplodedNode *N; 3285 ExplodedNode::const_succ_iterator I, E; 3286 3287 FRIEC_WLItem(const ExplodedNode *n) 3288 : N(n), I(N->succ_begin()), E(N->succ_end()) {} 3289}; 3290} 3291 3292static BugReport * 3293FindReportInEquivalenceClass(BugReportEquivClass& EQ, 3294 SmallVectorImpl<BugReport*> &bugReports) { 3295 3296 BugReportEquivClass::iterator I = EQ.begin(), E = EQ.end(); 3297 assert(I != E); 3298 BugType& BT = I->getBugType(); 3299 3300 // If we don't need to suppress any of the nodes because they are 3301 // post-dominated by a sink, simply add all the nodes in the equivalence class 3302 // to 'Nodes'. Any of the reports will serve as a "representative" report. 3303 if (!BT.isSuppressOnSink()) { 3304 BugReport *R = I; 3305 for (BugReportEquivClass::iterator I=EQ.begin(), E=EQ.end(); I!=E; ++I) { 3306 const ExplodedNode *N = I->getErrorNode(); 3307 if (N) { 3308 R = I; 3309 bugReports.push_back(R); 3310 } 3311 } 3312 return R; 3313 } 3314 3315 // For bug reports that should be suppressed when all paths are post-dominated 3316 // by a sink node, iterate through the reports in the equivalence class 3317 // until we find one that isn't post-dominated (if one exists). We use a 3318 // DFS traversal of the ExplodedGraph to find a non-sink node. We could write 3319 // this as a recursive function, but we don't want to risk blowing out the 3320 // stack for very long paths. 3321 BugReport *exampleReport = 0; 3322 3323 for (; I != E; ++I) { 3324 const ExplodedNode *errorNode = I->getErrorNode(); 3325 3326 if (!errorNode) 3327 continue; 3328 if (errorNode->isSink()) { 3329 llvm_unreachable( 3330 "BugType::isSuppressSink() should not be 'true' for sink end nodes"); 3331 } 3332 // No successors? By definition this nodes isn't post-dominated by a sink. 3333 if (errorNode->succ_empty()) { 3334 bugReports.push_back(I); 3335 if (!exampleReport) 3336 exampleReport = I; 3337 continue; 3338 } 3339 3340 // At this point we know that 'N' is not a sink and it has at least one 3341 // successor. Use a DFS worklist to find a non-sink end-of-path node. 3342 typedef FRIEC_WLItem WLItem; 3343 typedef SmallVector<WLItem, 10> DFSWorkList; 3344 llvm::DenseMap<const ExplodedNode *, unsigned> Visited; 3345 3346 DFSWorkList WL; 3347 WL.push_back(errorNode); 3348 Visited[errorNode] = 1; 3349 3350 while (!WL.empty()) { 3351 WLItem &WI = WL.back(); 3352 assert(!WI.N->succ_empty()); 3353 3354 for (; WI.I != WI.E; ++WI.I) { 3355 const ExplodedNode *Succ = *WI.I; 3356 // End-of-path node? 3357 if (Succ->succ_empty()) { 3358 // If we found an end-of-path node that is not a sink. 3359 if (!Succ->isSink()) { 3360 bugReports.push_back(I); 3361 if (!exampleReport) 3362 exampleReport = I; 3363 WL.clear(); 3364 break; 3365 } 3366 // Found a sink? Continue on to the next successor. 3367 continue; 3368 } 3369 // Mark the successor as visited. If it hasn't been explored, 3370 // enqueue it to the DFS worklist. 3371 unsigned &mark = Visited[Succ]; 3372 if (!mark) { 3373 mark = 1; 3374 WL.push_back(Succ); 3375 break; 3376 } 3377 } 3378 3379 // The worklist may have been cleared at this point. First 3380 // check if it is empty before checking the last item. 3381 if (!WL.empty() && &WL.back() == &WI) 3382 WL.pop_back(); 3383 } 3384 } 3385 3386 // ExampleReport will be NULL if all the nodes in the equivalence class 3387 // were post-dominated by sinks. 3388 return exampleReport; 3389} 3390 3391void BugReporter::FlushReport(BugReportEquivClass& EQ) { 3392 SmallVector<BugReport*, 10> bugReports; 3393 BugReport *exampleReport = FindReportInEquivalenceClass(EQ, bugReports); 3394 if (exampleReport) { 3395 const PathDiagnosticConsumers &C = getPathDiagnosticConsumers(); 3396 for (PathDiagnosticConsumers::const_iterator I=C.begin(), 3397 E=C.end(); I != E; ++I) { 3398 FlushReport(exampleReport, **I, bugReports); 3399 } 3400 } 3401} 3402 3403void BugReporter::FlushReport(BugReport *exampleReport, 3404 PathDiagnosticConsumer &PD, 3405 ArrayRef<BugReport*> bugReports) { 3406 3407 // FIXME: Make sure we use the 'R' for the path that was actually used. 3408 // Probably doesn't make a difference in practice. 3409 BugType& BT = exampleReport->getBugType(); 3410 3411 OwningPtr<PathDiagnostic> 3412 D(new PathDiagnostic(exampleReport->getDeclWithIssue(), 3413 exampleReport->getBugType().getName(), 3414 exampleReport->getDescription(), 3415 exampleReport->getShortDescription(/*Fallback=*/false), 3416 BT.getCategory(), 3417 exampleReport->getUniqueingLocation(), 3418 exampleReport->getUniqueingDecl())); 3419 3420 MaxBugClassSize = std::max(bugReports.size(), 3421 static_cast<size_t>(MaxBugClassSize)); 3422 3423 // Generate the full path diagnostic, using the generation scheme 3424 // specified by the PathDiagnosticConsumer. Note that we have to generate 3425 // path diagnostics even for consumers which do not support paths, because 3426 // the BugReporterVisitors may mark this bug as a false positive. 3427 if (!bugReports.empty()) 3428 if (!generatePathDiagnostic(*D.get(), PD, bugReports)) 3429 return; 3430 3431 MaxValidBugClassSize = std::max(bugReports.size(), 3432 static_cast<size_t>(MaxValidBugClassSize)); 3433 3434 // Examine the report and see if the last piece is in a header. Reset the 3435 // report location to the last piece in the main source file. 3436 AnalyzerOptions& Opts = getAnalyzerOptions(); 3437 if (Opts.shouldReportIssuesInMainSourceFile() && !Opts.AnalyzeAll) 3438 D->resetDiagnosticLocationToMainFile(); 3439 3440 // If the path is empty, generate a single step path with the location 3441 // of the issue. 3442 if (D->path.empty()) { 3443 PathDiagnosticLocation L = exampleReport->getLocation(getSourceManager()); 3444 PathDiagnosticPiece *piece = 3445 new PathDiagnosticEventPiece(L, exampleReport->getDescription()); 3446 BugReport::ranges_iterator Beg, End; 3447 llvm::tie(Beg, End) = exampleReport->getRanges(); 3448 for ( ; Beg != End; ++Beg) 3449 piece->addRange(*Beg); 3450 D->setEndOfPath(piece); 3451 } 3452 3453 // Get the meta data. 3454 const BugReport::ExtraTextList &Meta = exampleReport->getExtraText(); 3455 for (BugReport::ExtraTextList::const_iterator i = Meta.begin(), 3456 e = Meta.end(); i != e; ++i) { 3457 D->addMeta(*i); 3458 } 3459 3460 PD.HandlePathDiagnostic(D.take()); 3461} 3462 3463void BugReporter::EmitBasicReport(const Decl *DeclWithIssue, 3464 StringRef name, 3465 StringRef category, 3466 StringRef str, PathDiagnosticLocation Loc, 3467 ArrayRef<SourceRange> Ranges) { 3468 3469 // 'BT' is owned by BugReporter. 3470 BugType *BT = getBugTypeForName(name, category); 3471 BugReport *R = new BugReport(*BT, str, Loc); 3472 R->setDeclWithIssue(DeclWithIssue); 3473 for (ArrayRef<SourceRange>::iterator I = Ranges.begin(), E = Ranges.end(); 3474 I != E; ++I) 3475 R->addRange(*I); 3476 emitReport(R); 3477} 3478 3479BugType *BugReporter::getBugTypeForName(StringRef name, 3480 StringRef category) { 3481 SmallString<136> fullDesc; 3482 llvm::raw_svector_ostream(fullDesc) << name << ":" << category; 3483 llvm::StringMapEntry<BugType *> & 3484 entry = StrBugTypes.GetOrCreateValue(fullDesc); 3485 BugType *BT = entry.getValue(); 3486 if (!BT) { 3487 BT = new BugType(name, category); 3488 entry.setValue(BT); 3489 } 3490 return BT; 3491} 3492 3493 3494void PathPieces::dump() const { 3495 unsigned index = 0; 3496 for (PathPieces::const_iterator I = begin(), E = end(); I != E; ++I) { 3497 llvm::errs() << "[" << index++ << "] "; 3498 (*I)->dump(); 3499 llvm::errs() << "\n"; 3500 } 3501} 3502 3503void PathDiagnosticCallPiece::dump() const { 3504 llvm::errs() << "CALL\n--------------\n"; 3505 3506 if (const Stmt *SLoc = getLocStmt(getLocation())) 3507 SLoc->dump(); 3508 else if (const NamedDecl *ND = dyn_cast<NamedDecl>(getCallee())) 3509 llvm::errs() << *ND << "\n"; 3510 else 3511 getLocation().dump(); 3512} 3513 3514void PathDiagnosticEventPiece::dump() const { 3515 llvm::errs() << "EVENT\n--------------\n"; 3516 llvm::errs() << getString() << "\n"; 3517 llvm::errs() << " ---- at ----\n"; 3518 getLocation().dump(); 3519} 3520 3521void PathDiagnosticControlFlowPiece::dump() const { 3522 llvm::errs() << "CONTROL\n--------------\n"; 3523 getStartLocation().dump(); 3524 llvm::errs() << " ---- to ----\n"; 3525 getEndLocation().dump(); 3526} 3527 3528void PathDiagnosticMacroPiece::dump() const { 3529 llvm::errs() << "MACRO\n--------------\n"; 3530 // FIXME: Print which macro is being invoked. 3531} 3532 3533void PathDiagnosticLocation::dump() const { 3534 if (!isValid()) { 3535 llvm::errs() << "<INVALID>\n"; 3536 return; 3537 } 3538 3539 switch (K) { 3540 case RangeK: 3541 // FIXME: actually print the range. 3542 llvm::errs() << "<range>\n"; 3543 break; 3544 case SingleLocK: 3545 asLocation().dump(); 3546 llvm::errs() << "\n"; 3547 break; 3548 case StmtK: 3549 if (S) 3550 S->dump(); 3551 else 3552 llvm::errs() << "<NULL STMT>\n"; 3553 break; 3554 case DeclK: 3555 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D)) 3556 llvm::errs() << *ND << "\n"; 3557 else if (isa<BlockDecl>(D)) 3558 // FIXME: Make this nicer. 3559 llvm::errs() << "<block>\n"; 3560 else if (D) 3561 llvm::errs() << "<unknown decl>\n"; 3562 else 3563 llvm::errs() << "<NULL DECL>\n"; 3564 break; 3565 } 3566} 3567