blob: f54200b0407cf954909f3e85fb429409da15a0ec [file] [log] [blame]
Ted Kremenek61f3e052008-04-03 04:42:52 +00001// 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 for analyses based on GRSimpleVals.
12//
13//===----------------------------------------------------------------------===//
14
15#include "clang/Analysis/PathSensitive/BugReporter.h"
Ted Kremenek50a6d0c2008-04-09 21:41:14 +000016#include "clang/Analysis/PathSensitive/GRExprEngine.h"
Ted Kremenek61f3e052008-04-03 04:42:52 +000017#include "clang/Basic/SourceManager.h"
18#include "clang/Basic/SourceLocation.h"
19#include "clang/AST/ASTContext.h"
20#include "clang/AST/CFG.h"
21#include "clang/AST/Expr.h"
Ted Kremenek00605e02009-03-27 20:55:39 +000022#include "clang/AST/ParentMap.h"
Ted Kremenek61f3e052008-04-03 04:42:52 +000023#include "clang/Analysis/ProgramPoint.h"
24#include "clang/Analysis/PathDiagnostic.h"
Chris Lattner405674c2008-08-23 22:23:37 +000025#include "llvm/Support/raw_ostream.h"
Ted Kremenek331b0ac2008-06-18 05:34:07 +000026#include "llvm/ADT/DenseMap.h"
Ted Kremenekcf118d42009-02-04 23:49:09 +000027#include "llvm/ADT/STLExtras.h"
Ted Kremenek00605e02009-03-27 20:55:39 +000028#include "llvm/ADT/OwningPtr.h"
Ted Kremenek10aa5542009-03-12 23:41:59 +000029#include <queue>
Ted Kremenek61f3e052008-04-03 04:42:52 +000030
31using namespace clang;
32
Ted Kremenekcf118d42009-02-04 23:49:09 +000033//===----------------------------------------------------------------------===//
Ted Kremenek31061982009-03-31 23:00:32 +000034// Helper routines for walking the ExplodedGraph and fetching statements.
Ted Kremenekcf118d42009-02-04 23:49:09 +000035//===----------------------------------------------------------------------===//
Ted Kremenek61f3e052008-04-03 04:42:52 +000036
Ted Kremenekb697b102009-02-23 22:44:26 +000037static inline Stmt* GetStmt(ProgramPoint P) {
38 if (const PostStmt* PS = dyn_cast<PostStmt>(&P))
Ted Kremenek61f3e052008-04-03 04:42:52 +000039 return PS->getStmt();
Ted Kremenekb697b102009-02-23 22:44:26 +000040 else if (const BlockEdge* BE = dyn_cast<BlockEdge>(&P))
Ted Kremenek61f3e052008-04-03 04:42:52 +000041 return BE->getSrc()->getTerminator();
Ted Kremenek61f3e052008-04-03 04:42:52 +000042
Ted Kremenekb697b102009-02-23 22:44:26 +000043 return 0;
Ted Kremenek706e3cf2008-04-07 23:35:17 +000044}
45
Ted Kremenek3148eb42009-01-24 00:55:43 +000046static inline const ExplodedNode<GRState>*
Ted Kremenekb697b102009-02-23 22:44:26 +000047GetPredecessorNode(const ExplodedNode<GRState>* N) {
Ted Kremenekbd7efa82008-04-17 23:44:37 +000048 return N->pred_empty() ? NULL : *(N->pred_begin());
49}
Ted Kremenek2673c9f2008-04-25 19:01:27 +000050
Ted Kremenekb697b102009-02-23 22:44:26 +000051static inline const ExplodedNode<GRState>*
52GetSuccessorNode(const ExplodedNode<GRState>* N) {
53 return N->succ_empty() ? NULL : *(N->succ_begin());
Ted Kremenekbd7efa82008-04-17 23:44:37 +000054}
55
Ted Kremenekb697b102009-02-23 22:44:26 +000056static Stmt* GetPreviousStmt(const ExplodedNode<GRState>* N) {
57 for (N = GetPredecessorNode(N); N; N = GetPredecessorNode(N))
58 if (Stmt *S = GetStmt(N->getLocation()))
59 return S;
60
61 return 0;
Ted Kremenek3148eb42009-01-24 00:55:43 +000062}
63
Ted Kremenekb697b102009-02-23 22:44:26 +000064static Stmt* GetNextStmt(const ExplodedNode<GRState>* N) {
65 for (N = GetSuccessorNode(N); N; N = GetSuccessorNode(N))
Ted Kremenekf5ab8e62009-03-28 17:33:57 +000066 if (Stmt *S = GetStmt(N->getLocation())) {
67 // Check if the statement is '?' or '&&'/'||'. These are "merges",
68 // not actual statement points.
69 switch (S->getStmtClass()) {
70 case Stmt::ChooseExprClass:
71 case Stmt::ConditionalOperatorClass: continue;
72 case Stmt::BinaryOperatorClass: {
73 BinaryOperator::Opcode Op = cast<BinaryOperator>(S)->getOpcode();
74 if (Op == BinaryOperator::LAnd || Op == BinaryOperator::LOr)
75 continue;
76 break;
77 }
78 default:
79 break;
80 }
Ted Kremenekb697b102009-02-23 22:44:26 +000081 return S;
Ted Kremenekf5ab8e62009-03-28 17:33:57 +000082 }
Ted Kremenekb697b102009-02-23 22:44:26 +000083
84 return 0;
85}
86
87static inline Stmt* GetCurrentOrPreviousStmt(const ExplodedNode<GRState>* N) {
88 if (Stmt *S = GetStmt(N->getLocation()))
89 return S;
90
91 return GetPreviousStmt(N);
92}
93
94static inline Stmt* GetCurrentOrNextStmt(const ExplodedNode<GRState>* N) {
95 if (Stmt *S = GetStmt(N->getLocation()))
96 return S;
97
98 return GetNextStmt(N);
99}
100
101//===----------------------------------------------------------------------===//
Ted Kremenek31061982009-03-31 23:00:32 +0000102// PathDiagnosticBuilder and its associated routines and helper objects.
Ted Kremenekb697b102009-02-23 22:44:26 +0000103//===----------------------------------------------------------------------===//
Ted Kremenekb479dad2009-02-23 23:13:51 +0000104
Ted Kremenek7dc86642009-03-31 20:22:36 +0000105typedef llvm::DenseMap<const ExplodedNode<GRState>*,
106const ExplodedNode<GRState>*> NodeBackMap;
107
Ted Kremenekbabdd7b2009-03-27 05:06:10 +0000108namespace {
Ted Kremenek7dc86642009-03-31 20:22:36 +0000109class VISIBILITY_HIDDEN NodeMapClosure : public BugReport::NodeResolver {
110 NodeBackMap& M;
111public:
112 NodeMapClosure(NodeBackMap *m) : M(*m) {}
113 ~NodeMapClosure() {}
114
115 const ExplodedNode<GRState>* getOriginalNode(const ExplodedNode<GRState>* N) {
116 NodeBackMap::iterator I = M.find(N);
117 return I == M.end() ? 0 : I->second;
118 }
119};
120
Ted Kremenekbabdd7b2009-03-27 05:06:10 +0000121class VISIBILITY_HIDDEN PathDiagnosticBuilder {
Ted Kremenek7dc86642009-03-31 20:22:36 +0000122 GRBugReporter &BR;
Ted Kremenekbabdd7b2009-03-27 05:06:10 +0000123 SourceManager &SMgr;
Ted Kremenek7dc86642009-03-31 20:22:36 +0000124 ExplodedGraph<GRState> *ReportGraph;
125 BugReport *R;
Ted Kremenekbabdd7b2009-03-27 05:06:10 +0000126 const Decl& CodeDecl;
127 PathDiagnosticClient *PDC;
Ted Kremenek00605e02009-03-27 20:55:39 +0000128 llvm::OwningPtr<ParentMap> PM;
Ted Kremenek7dc86642009-03-31 20:22:36 +0000129 NodeMapClosure NMC;
Ted Kremenekbabdd7b2009-03-27 05:06:10 +0000130public:
Ted Kremenek7dc86642009-03-31 20:22:36 +0000131 PathDiagnosticBuilder(GRBugReporter &br, ExplodedGraph<GRState> *reportGraph,
132 BugReport *r, NodeBackMap *Backmap,
133 const Decl& codedecl, PathDiagnosticClient *pdc)
134 : BR(br), SMgr(BR.getSourceManager()), ReportGraph(reportGraph), R(r),
135 CodeDecl(codedecl), PDC(pdc), NMC(Backmap) {}
Ted Kremenekbabdd7b2009-03-27 05:06:10 +0000136
Ted Kremenek00605e02009-03-27 20:55:39 +0000137 PathDiagnosticLocation ExecutionContinues(const ExplodedNode<GRState>* N);
Ted Kremenekbabdd7b2009-03-27 05:06:10 +0000138
Ted Kremenek00605e02009-03-27 20:55:39 +0000139 PathDiagnosticLocation ExecutionContinues(llvm::raw_string_ostream& os,
140 const ExplodedNode<GRState>* N);
141
142 ParentMap& getParentMap() {
143 if (PM.get() == 0) PM.reset(new ParentMap(CodeDecl.getBody()));
144 return *PM.get();
145 }
Ted Kremenekbabdd7b2009-03-27 05:06:10 +0000146
Ted Kremenek7dc86642009-03-31 20:22:36 +0000147 ExplodedGraph<GRState>& getGraph() { return *ReportGraph; }
148 NodeMapClosure& getNodeMapClosure() { return NMC; }
149 ASTContext& getContext() { return BR.getContext(); }
150 SourceManager& getSourceManager() { return SMgr; }
151 BugReport& getReport() { return *R; }
152 GRBugReporter& getBugReporter() { return BR; }
153 GRStateManager& getStateManager() { return BR.getStateManager(); }
154
Ted Kremenekd8c938b2009-03-27 21:16:25 +0000155 PathDiagnosticLocation getEnclosingStmtLocation(const Stmt *S);
156
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000157 PathDiagnosticLocation
158 getEnclosingStmtLocation(const PathDiagnosticLocation &L) {
159 if (const Stmt *S = L.asStmt())
160 return getEnclosingStmtLocation(S);
161
162 return L;
163 }
164
Ted Kremenek7dc86642009-03-31 20:22:36 +0000165 PathDiagnosticClient::PathGenerationScheme getGenerationScheme() const {
166 return PDC ? PDC->getGenerationScheme() : PathDiagnosticClient::Extensive;
167 }
168
Ted Kremenekbabdd7b2009-03-27 05:06:10 +0000169 bool supportsLogicalOpControlFlow() const {
170 return PDC ? PDC->supportsLogicalOpControlFlow() : true;
171 }
172};
173} // end anonymous namespace
174
Ted Kremenek00605e02009-03-27 20:55:39 +0000175PathDiagnosticLocation
176PathDiagnosticBuilder::ExecutionContinues(const ExplodedNode<GRState>* N) {
177 if (Stmt *S = GetNextStmt(N))
178 return PathDiagnosticLocation(S, SMgr);
179
180 return FullSourceLoc(CodeDecl.getBody()->getRBracLoc(), SMgr);
Ted Kremenek082cb8d2009-03-12 18:41:53 +0000181}
182
Ted Kremenek00605e02009-03-27 20:55:39 +0000183PathDiagnosticLocation
Ted Kremenekbabdd7b2009-03-27 05:06:10 +0000184PathDiagnosticBuilder::ExecutionContinues(llvm::raw_string_ostream& os,
185 const ExplodedNode<GRState>* N) {
186
Ted Kremenek143ca222008-05-06 18:11:09 +0000187 // Slow, but probably doesn't matter.
Ted Kremenekb697b102009-02-23 22:44:26 +0000188 if (os.str().empty())
189 os << ' ';
Ted Kremenek143ca222008-05-06 18:11:09 +0000190
Ted Kremenek00605e02009-03-27 20:55:39 +0000191 const PathDiagnosticLocation &Loc = ExecutionContinues(N);
Ted Kremenek082cb8d2009-03-12 18:41:53 +0000192
Ted Kremenek00605e02009-03-27 20:55:39 +0000193 if (Loc.asStmt())
Ted Kremenekb697b102009-02-23 22:44:26 +0000194 os << "Execution continues on line "
Ted Kremenek00605e02009-03-27 20:55:39 +0000195 << SMgr.getInstantiationLineNumber(Loc.asLocation()) << '.';
Ted Kremenekb697b102009-02-23 22:44:26 +0000196 else
Ted Kremenekb479dad2009-02-23 23:13:51 +0000197 os << "Execution jumps to the end of the "
Ted Kremenekbabdd7b2009-03-27 05:06:10 +0000198 << (isa<ObjCMethodDecl>(CodeDecl) ? "method" : "function") << '.';
Ted Kremenek082cb8d2009-03-12 18:41:53 +0000199
200 return Loc;
Ted Kremenek143ca222008-05-06 18:11:09 +0000201}
202
Ted Kremenekd8c938b2009-03-27 21:16:25 +0000203PathDiagnosticLocation
204PathDiagnosticBuilder::getEnclosingStmtLocation(const Stmt *S) {
205 assert(S && "Null Stmt* passed to getEnclosingStmtLocation");
206 ParentMap &P = getParentMap();
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000207
208 while (isa<DeclStmt>(S) || isa<Expr>(S)) {
Ted Kremenekd8c938b2009-03-27 21:16:25 +0000209 const Stmt *Parent = P.getParent(S);
210
Ted Kremenekaf3e3d52009-03-28 03:37:59 +0000211 if (!Parent)
212 break;
Ted Kremenekd8c938b2009-03-27 21:16:25 +0000213
Ted Kremenekaf3e3d52009-03-28 03:37:59 +0000214 switch (Parent->getStmtClass()) {
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000215 case Stmt::BinaryOperatorClass: {
216 const BinaryOperator *B = cast<BinaryOperator>(Parent);
217 if (B->isLogicalOp())
218 return PathDiagnosticLocation(S, SMgr);
219 break;
220 }
221
Ted Kremenekaf3e3d52009-03-28 03:37:59 +0000222 case Stmt::CompoundStmtClass:
223 case Stmt::StmtExprClass:
Ted Kremenek1d9a23a2009-03-28 04:08:14 +0000224 return PathDiagnosticLocation(S, SMgr);
225 case Stmt::ChooseExprClass:
226 // Similar to '?' if we are referring to condition, just have the edge
227 // point to the entire choose expression.
228 if (cast<ChooseExpr>(Parent)->getCond() == S)
229 return PathDiagnosticLocation(Parent, SMgr);
230 else
231 return PathDiagnosticLocation(S, SMgr);
232 case Stmt::ConditionalOperatorClass:
233 // For '?', if we are referring to condition, just have the edge point
234 // to the entire '?' expression.
235 if (cast<ConditionalOperator>(Parent)->getCond() == S)
236 return PathDiagnosticLocation(Parent, SMgr);
237 else
238 return PathDiagnosticLocation(S, SMgr);
Ted Kremenekaf3e3d52009-03-28 03:37:59 +0000239 case Stmt::DoStmtClass:
240 if (cast<DoStmt>(Parent)->getCond() != S)
241 return PathDiagnosticLocation(S, SMgr);
242 break;
243 case Stmt::ForStmtClass:
244 if (cast<ForStmt>(Parent)->getBody() == S)
245 return PathDiagnosticLocation(S, SMgr);
246 break;
247 case Stmt::IfStmtClass:
248 if (cast<IfStmt>(Parent)->getCond() != S)
249 return PathDiagnosticLocation(S, SMgr);
250 break;
251 case Stmt::ObjCForCollectionStmtClass:
252 if (cast<ObjCForCollectionStmt>(Parent)->getBody() == S)
253 return PathDiagnosticLocation(S, SMgr);
254 break;
255 case Stmt::WhileStmtClass:
256 if (cast<WhileStmt>(Parent)->getCond() != S)
257 return PathDiagnosticLocation(S, SMgr);
258 break;
259 default:
260 break;
261 }
262
Ted Kremenekd8c938b2009-03-27 21:16:25 +0000263 S = Parent;
264 }
265
266 assert(S && "Cannot have null Stmt for PathDiagnosticLocation");
267 return PathDiagnosticLocation(S, SMgr);
268}
269
Ted Kremenekcf118d42009-02-04 23:49:09 +0000270//===----------------------------------------------------------------------===//
Ted Kremenek31061982009-03-31 23:00:32 +0000271// ScanNotableSymbols: closure-like callback for scanning Store bindings.
272//===----------------------------------------------------------------------===//
273
274static const VarDecl*
275GetMostRecentVarDeclBinding(const ExplodedNode<GRState>* N,
276 GRStateManager& VMgr, SVal X) {
277
278 for ( ; N ; N = N->pred_empty() ? 0 : *N->pred_begin()) {
279
280 ProgramPoint P = N->getLocation();
281
282 if (!isa<PostStmt>(P))
283 continue;
284
285 DeclRefExpr* DR = dyn_cast<DeclRefExpr>(cast<PostStmt>(P).getStmt());
286
287 if (!DR)
288 continue;
289
290 SVal Y = VMgr.GetSVal(N->getState(), DR);
291
292 if (X != Y)
293 continue;
294
295 VarDecl* VD = dyn_cast<VarDecl>(DR->getDecl());
296
297 if (!VD)
298 continue;
299
300 return VD;
301 }
302
303 return 0;
304}
305
306namespace {
307class VISIBILITY_HIDDEN NotableSymbolHandler
308: public StoreManager::BindingsHandler {
309
310 SymbolRef Sym;
311 const GRState* PrevSt;
312 const Stmt* S;
313 GRStateManager& VMgr;
314 const ExplodedNode<GRState>* Pred;
315 PathDiagnostic& PD;
316 BugReporter& BR;
317
318public:
319
320 NotableSymbolHandler(SymbolRef sym, const GRState* prevst, const Stmt* s,
321 GRStateManager& vmgr, const ExplodedNode<GRState>* pred,
322 PathDiagnostic& pd, BugReporter& br)
323 : Sym(sym), PrevSt(prevst), S(s), VMgr(vmgr), Pred(pred), PD(pd), BR(br) {}
324
325 bool HandleBinding(StoreManager& SMgr, Store store, const MemRegion* R,
326 SVal V) {
327
328 SymbolRef ScanSym = V.getAsSymbol();
329
330 if (ScanSym != Sym)
331 return true;
332
333 // Check if the previous state has this binding.
334 SVal X = VMgr.GetSVal(PrevSt, loc::MemRegionVal(R));
335
336 if (X == V) // Same binding?
337 return true;
338
339 // Different binding. Only handle assignments for now. We don't pull
340 // this check out of the loop because we will eventually handle other
341 // cases.
342
343 VarDecl *VD = 0;
344
345 if (const BinaryOperator* B = dyn_cast<BinaryOperator>(S)) {
346 if (!B->isAssignmentOp())
347 return true;
348
349 // What variable did we assign to?
350 DeclRefExpr* DR = dyn_cast<DeclRefExpr>(B->getLHS()->IgnoreParenCasts());
351
352 if (!DR)
353 return true;
354
355 VD = dyn_cast<VarDecl>(DR->getDecl());
356 }
357 else if (const DeclStmt* DS = dyn_cast<DeclStmt>(S)) {
358 // FIXME: Eventually CFGs won't have DeclStmts. Right now we
359 // assume that each DeclStmt has a single Decl. This invariant
360 // holds by contruction in the CFG.
361 VD = dyn_cast<VarDecl>(*DS->decl_begin());
362 }
363
364 if (!VD)
365 return true;
366
367 // What is the most recently referenced variable with this binding?
368 const VarDecl* MostRecent = GetMostRecentVarDeclBinding(Pred, VMgr, V);
369
370 if (!MostRecent)
371 return true;
372
373 // Create the diagnostic.
374 FullSourceLoc L(S->getLocStart(), BR.getSourceManager());
375
376 if (Loc::IsLocType(VD->getType())) {
377 std::string msg = "'" + std::string(VD->getNameAsString()) +
378 "' now aliases '" + MostRecent->getNameAsString() + "'";
379
380 PD.push_front(new PathDiagnosticEventPiece(L, msg));
381 }
382
383 return true;
384 }
385};
386}
387
388static void HandleNotableSymbol(const ExplodedNode<GRState>* N,
389 const Stmt* S,
390 SymbolRef Sym, BugReporter& BR,
391 PathDiagnostic& PD) {
392
393 const ExplodedNode<GRState>* Pred = N->pred_empty() ? 0 : *N->pred_begin();
394 const GRState* PrevSt = Pred ? Pred->getState() : 0;
395
396 if (!PrevSt)
397 return;
398
399 // Look at the region bindings of the current state that map to the
400 // specified symbol. Are any of them not in the previous state?
401 GRStateManager& VMgr = cast<GRBugReporter>(BR).getStateManager();
402 NotableSymbolHandler H(Sym, PrevSt, S, VMgr, Pred, PD, BR);
403 cast<GRBugReporter>(BR).getStateManager().iterBindings(N->getState(), H);
404}
405
406namespace {
407class VISIBILITY_HIDDEN ScanNotableSymbols
408: public StoreManager::BindingsHandler {
409
410 llvm::SmallSet<SymbolRef, 10> AlreadyProcessed;
411 const ExplodedNode<GRState>* N;
412 Stmt* S;
413 GRBugReporter& BR;
414 PathDiagnostic& PD;
415
416public:
417 ScanNotableSymbols(const ExplodedNode<GRState>* n, Stmt* s, GRBugReporter& br,
418 PathDiagnostic& pd)
419 : N(n), S(s), BR(br), PD(pd) {}
420
421 bool HandleBinding(StoreManager& SMgr, Store store,
422 const MemRegion* R, SVal V) {
423
424 SymbolRef ScanSym = V.getAsSymbol();
425
426 if (!ScanSym)
427 return true;
428
429 if (!BR.isNotable(ScanSym))
430 return true;
431
432 if (AlreadyProcessed.count(ScanSym))
433 return true;
434
435 AlreadyProcessed.insert(ScanSym);
436
437 HandleNotableSymbol(N, S, ScanSym, BR, PD);
438 return true;
439 }
440};
441} // end anonymous namespace
442
443//===----------------------------------------------------------------------===//
444// "Minimal" path diagnostic generation algorithm.
445//===----------------------------------------------------------------------===//
446
447static void GenerateMinimalPathDiagnostic(PathDiagnostic& PD,
448 PathDiagnosticBuilder &PDB,
449 const ExplodedNode<GRState> *N) {
450 ASTContext& Ctx = PDB.getContext();
451 SourceManager& SMgr = PDB.getSourceManager();
452 const ExplodedNode<GRState>* NextNode = N->pred_empty()
453 ? NULL : *(N->pred_begin());
454 while (NextNode) {
455 N = NextNode;
456 NextNode = GetPredecessorNode(N);
457
458 ProgramPoint P = N->getLocation();
459
460 if (const BlockEdge* BE = dyn_cast<BlockEdge>(&P)) {
461 CFGBlock* Src = BE->getSrc();
462 CFGBlock* Dst = BE->getDst();
463 Stmt* T = Src->getTerminator();
464
465 if (!T)
466 continue;
467
468 FullSourceLoc Start(T->getLocStart(), SMgr);
469
470 switch (T->getStmtClass()) {
471 default:
472 break;
473
474 case Stmt::GotoStmtClass:
475 case Stmt::IndirectGotoStmtClass: {
476 Stmt* S = GetNextStmt(N);
477
478 if (!S)
479 continue;
480
481 std::string sbuf;
482 llvm::raw_string_ostream os(sbuf);
483 const PathDiagnosticLocation &End = PDB.getEnclosingStmtLocation(S);
484
485 os << "Control jumps to line "
486 << End.asLocation().getInstantiationLineNumber();
487 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
488 os.str()));
489 break;
490 }
491
492 case Stmt::SwitchStmtClass: {
493 // Figure out what case arm we took.
494 std::string sbuf;
495 llvm::raw_string_ostream os(sbuf);
496
497 if (Stmt* S = Dst->getLabel()) {
498 PathDiagnosticLocation End(S, SMgr);
499
500 switch (S->getStmtClass()) {
501 default:
502 os << "No cases match in the switch statement. "
503 "Control jumps to line "
504 << End.asLocation().getInstantiationLineNumber();
505 break;
506 case Stmt::DefaultStmtClass:
507 os << "Control jumps to the 'default' case at line "
508 << End.asLocation().getInstantiationLineNumber();
509 break;
510
511 case Stmt::CaseStmtClass: {
512 os << "Control jumps to 'case ";
513 CaseStmt* Case = cast<CaseStmt>(S);
514 Expr* LHS = Case->getLHS()->IgnoreParenCasts();
515
516 // Determine if it is an enum.
517 bool GetRawInt = true;
518
519 if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(LHS)) {
520 // FIXME: Maybe this should be an assertion. Are there cases
521 // were it is not an EnumConstantDecl?
522 EnumConstantDecl* D =
523 dyn_cast<EnumConstantDecl>(DR->getDecl());
524
525 if (D) {
526 GetRawInt = false;
527 os << D->getNameAsString();
528 }
529 }
530
531 if (GetRawInt) {
532
533 // Not an enum.
534 Expr* CondE = cast<SwitchStmt>(T)->getCond();
535 unsigned bits = Ctx.getTypeSize(CondE->getType());
536 llvm::APSInt V(bits, false);
537
538 if (!LHS->isIntegerConstantExpr(V, Ctx, 0, true)) {
539 assert (false && "Case condition must be constant.");
540 continue;
541 }
542
543 os << V;
544 }
545
546 os << ":' at line "
547 << End.asLocation().getInstantiationLineNumber();
548 break;
549 }
550 }
551 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
552 os.str()));
553 }
554 else {
555 os << "'Default' branch taken. ";
556 const PathDiagnosticLocation &End = PDB.ExecutionContinues(os, N);
557 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
558 os.str()));
559 }
560
561 break;
562 }
563
564 case Stmt::BreakStmtClass:
565 case Stmt::ContinueStmtClass: {
566 std::string sbuf;
567 llvm::raw_string_ostream os(sbuf);
568 PathDiagnosticLocation End = PDB.ExecutionContinues(os, N);
569 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
570 os.str()));
571 break;
572 }
573
574 // Determine control-flow for ternary '?'.
575 case Stmt::ConditionalOperatorClass: {
576 std::string sbuf;
577 llvm::raw_string_ostream os(sbuf);
578 os << "'?' condition is ";
579
580 if (*(Src->succ_begin()+1) == Dst)
581 os << "false";
582 else
583 os << "true";
584
585 PathDiagnosticLocation End = PDB.ExecutionContinues(N);
586
587 if (const Stmt *S = End.asStmt())
588 End = PDB.getEnclosingStmtLocation(S);
589
590 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
591 os.str()));
592 break;
593 }
594
595 // Determine control-flow for short-circuited '&&' and '||'.
596 case Stmt::BinaryOperatorClass: {
597 if (!PDB.supportsLogicalOpControlFlow())
598 break;
599
600 BinaryOperator *B = cast<BinaryOperator>(T);
601 std::string sbuf;
602 llvm::raw_string_ostream os(sbuf);
603 os << "Left side of '";
604
605 if (B->getOpcode() == BinaryOperator::LAnd) {
606 os << "&&" << "' is ";
607
608 if (*(Src->succ_begin()+1) == Dst) {
609 os << "false";
610 PathDiagnosticLocation End(B->getLHS(), SMgr);
611 PathDiagnosticLocation Start(B->getOperatorLoc(), SMgr);
612 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
613 os.str()));
614 }
615 else {
616 os << "true";
617 PathDiagnosticLocation Start(B->getLHS(), SMgr);
618 PathDiagnosticLocation End = PDB.ExecutionContinues(N);
619 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
620 os.str()));
621 }
622 }
623 else {
624 assert(B->getOpcode() == BinaryOperator::LOr);
625 os << "||" << "' is ";
626
627 if (*(Src->succ_begin()+1) == Dst) {
628 os << "false";
629 PathDiagnosticLocation Start(B->getLHS(), SMgr);
630 PathDiagnosticLocation End = PDB.ExecutionContinues(N);
631 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
632 os.str()));
633 }
634 else {
635 os << "true";
636 PathDiagnosticLocation End(B->getLHS(), SMgr);
637 PathDiagnosticLocation Start(B->getOperatorLoc(), SMgr);
638 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
639 os.str()));
640 }
641 }
642
643 break;
644 }
645
646 case Stmt::DoStmtClass: {
647 if (*(Src->succ_begin()) == Dst) {
648 std::string sbuf;
649 llvm::raw_string_ostream os(sbuf);
650
651 os << "Loop condition is true. ";
652 PathDiagnosticLocation End = PDB.ExecutionContinues(os, N);
653
654 if (const Stmt *S = End.asStmt())
655 End = PDB.getEnclosingStmtLocation(S);
656
657 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
658 os.str()));
659 }
660 else {
661 PathDiagnosticLocation End = PDB.ExecutionContinues(N);
662
663 if (const Stmt *S = End.asStmt())
664 End = PDB.getEnclosingStmtLocation(S);
665
666 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
667 "Loop condition is false. Exiting loop"));
668 }
669
670 break;
671 }
672
673 case Stmt::WhileStmtClass:
674 case Stmt::ForStmtClass: {
675 if (*(Src->succ_begin()+1) == Dst) {
676 std::string sbuf;
677 llvm::raw_string_ostream os(sbuf);
678
679 os << "Loop condition is false. ";
680 PathDiagnosticLocation End = PDB.ExecutionContinues(os, N);
681 if (const Stmt *S = End.asStmt())
682 End = PDB.getEnclosingStmtLocation(S);
683
684 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
685 os.str()));
686 }
687 else {
688 PathDiagnosticLocation End = PDB.ExecutionContinues(N);
689 if (const Stmt *S = End.asStmt())
690 End = PDB.getEnclosingStmtLocation(S);
691
692 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000693 "Loop condition is true. Entering loop body"));
Ted Kremenek31061982009-03-31 23:00:32 +0000694 }
695
696 break;
697 }
698
699 case Stmt::IfStmtClass: {
700 PathDiagnosticLocation End = PDB.ExecutionContinues(N);
701
702 if (const Stmt *S = End.asStmt())
703 End = PDB.getEnclosingStmtLocation(S);
704
705 if (*(Src->succ_begin()+1) == Dst)
706 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000707 "Taking false branch"));
Ted Kremenek31061982009-03-31 23:00:32 +0000708 else
709 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000710 "Taking true branch"));
Ted Kremenek31061982009-03-31 23:00:32 +0000711
712 break;
713 }
714 }
715 }
716
717 if (PathDiagnosticPiece* p =
718 PDB.getReport().VisitNode(N, NextNode, PDB.getGraph(),
719 PDB.getBugReporter(),
720 PDB.getNodeMapClosure())) {
721 PD.push_front(p);
722 }
723
724 if (const PostStmt* PS = dyn_cast<PostStmt>(&P)) {
725 // Scan the region bindings, and see if a "notable" symbol has a new
726 // lval binding.
727 ScanNotableSymbols SNS(N, PS->getStmt(), PDB.getBugReporter(), PD);
728 PDB.getStateManager().iterBindings(N->getState(), SNS);
729 }
730 }
731}
732
733//===----------------------------------------------------------------------===//
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000734// "Extensive" PathDiagnostic generation.
735//===----------------------------------------------------------------------===//
736
737static bool IsControlFlowExpr(const Stmt *S) {
738 const Expr *E = dyn_cast<Expr>(S);
739
740 if (!E)
741 return false;
742
743 E = E->IgnoreParenCasts();
744
745 if (isa<ConditionalOperator>(E))
746 return true;
747
748 if (const BinaryOperator *B = dyn_cast<BinaryOperator>(E))
749 if (B->isLogicalOp())
750 return true;
751
752 return false;
753}
754
755static void GenExtAddEdge(PathDiagnostic& PD,
756 PathDiagnosticBuilder &PDB,
757 PathDiagnosticLocation NewLoc,
758 PathDiagnosticLocation &PrevLoc,
759 PathDiagnosticLocation UpdateLoc) {
760
761 if (const Stmt *S = NewLoc.asStmt()) {
762 if (IsControlFlowExpr(S))
763 return;
764 }
765
766
767 if (!PrevLoc.isValid()) {
768 PrevLoc = NewLoc;
769 return;
770 }
771
772 if (NewLoc == PrevLoc)
773 return;
774
775 PD.push_front(new PathDiagnosticControlFlowPiece(NewLoc, PrevLoc));
776 PrevLoc = UpdateLoc;
777}
778
779static bool IsNestedDeclStmt(const Stmt *S, ParentMap &PM) {
780 const DeclStmt *DS = dyn_cast<DeclStmt>(S);
781
782 if (!DS)
783 return false;
784
785 const Stmt *Parent = PM.getParent(DS);
786 if (!Parent)
787 return false;
788
789 if (const ForStmt *FS = dyn_cast<ForStmt>(Parent))
790 return FS->getInit() == DS;
791
792 // FIXME: In the future IfStmt/WhileStmt may contain DeclStmts in their condition.
793// if (const IfStmt *IF = dyn_cast<IfStmt>(Parent))
794// return IF->getCond() == DS;
795//
796// if (const WhileStmt *WS = dyn_cast<WhileStmt>(Parent))
797// return WS->getCond() == DS;
798
799 return false;
800}
801
802static void GenExtAddEdge(PathDiagnostic& PD,
803 PathDiagnosticBuilder &PDB,
804 const PathDiagnosticLocation &NewLoc,
805 PathDiagnosticLocation &PrevLoc) {
806 GenExtAddEdge(PD, PDB, NewLoc, PrevLoc, NewLoc);
807}
808
809static void GenerateExtensivePathDiagnostic(PathDiagnostic& PD,
810 PathDiagnosticBuilder &PDB,
811 const ExplodedNode<GRState> *N) {
812
813 SourceManager& SMgr = PDB.getSourceManager();
814 const ExplodedNode<GRState>* NextNode = N->pred_empty()
815 ? NULL : *(N->pred_begin());
816
817 PathDiagnosticLocation PrevLoc;
818
819 while (NextNode) {
820 N = NextNode;
821 NextNode = GetPredecessorNode(N);
822 ProgramPoint P = N->getLocation();
823
824 // Block edges.
825 if (const BlockEdge *BE = dyn_cast<BlockEdge>(&P)) {
826 const CFGBlock &Blk = *BE->getSrc();
827 if (const Stmt *Term = Blk.getTerminator()) {
828 const Stmt *Cond = Blk.getTerminatorCondition();
829
830 if (!Cond || !IsControlFlowExpr(Cond)) {
831 GenExtAddEdge(PD, PDB, PathDiagnosticLocation(Term, SMgr), PrevLoc);
832 continue;
833 }
834 }
835
836 // Only handle blocks with more than 1 statement here, as the blocks
837 // with one statement are handled at BlockEntrances.
838 if (Blk.size() > 1) {
839 const Stmt *S = *Blk.rbegin();
840
841 // We don't add control-flow edges for DeclStmt's that appear in
842 // the condition of if/while/for or are control-flow merge expressions.
843 if (!IsControlFlowExpr(S) && !IsNestedDeclStmt(S, PDB.getParentMap())) {
844 GenExtAddEdge(PD, PDB, PathDiagnosticLocation(S, SMgr), PrevLoc);
845 }
846 }
847
848 continue;
849 }
850
851 if (const BlockEntrance *BE = dyn_cast<BlockEntrance>(&P)) {
852 if (const Stmt* S = BE->getFirstStmt()) {
853 if (!IsControlFlowExpr(S) && !IsNestedDeclStmt(S, PDB.getParentMap())) {
854 // Are we jumping with the same enclosing statement?
855 if (PrevLoc.isValid() && PDB.getEnclosingStmtLocation(S) ==
856 PDB.getEnclosingStmtLocation(PrevLoc)) {
857 continue;
858 }
859
860 GenExtAddEdge(PD, PDB, PDB.getEnclosingStmtLocation(S), PrevLoc);
861 }
862 }
863
864 continue;
865 }
866
867 PathDiagnosticPiece* p =
868 PDB.getReport().VisitNode(N, NextNode, PDB.getGraph(),
869 PDB.getBugReporter(), PDB.getNodeMapClosure());
870
871 if (p) {
872 GenExtAddEdge(PD, PDB, p->getLocation(), PrevLoc);
873 PD.push_front(p);
874 }
875 }
876}
877
878//===----------------------------------------------------------------------===//
Ted Kremenekcf118d42009-02-04 23:49:09 +0000879// Methods for BugType and subclasses.
880//===----------------------------------------------------------------------===//
881BugType::~BugType() {}
882void BugType::FlushReports(BugReporter &BR) {}
Ted Kremenekbb77e9b2008-05-01 22:50:36 +0000883
Ted Kremenekcf118d42009-02-04 23:49:09 +0000884//===----------------------------------------------------------------------===//
885// Methods for BugReport and subclasses.
886//===----------------------------------------------------------------------===//
887BugReport::~BugReport() {}
888RangedBugReport::~RangedBugReport() {}
889
890Stmt* BugReport::getStmt(BugReporter& BR) const {
Ted Kremenek200ed922008-05-02 23:21:21 +0000891 ProgramPoint ProgP = EndNode->getLocation();
Ted Kremenekbd7efa82008-04-17 23:44:37 +0000892 Stmt *S = NULL;
893
Ted Kremenekcf118d42009-02-04 23:49:09 +0000894 if (BlockEntrance* BE = dyn_cast<BlockEntrance>(&ProgP)) {
Ted Kremenekb697b102009-02-23 22:44:26 +0000895 if (BE->getBlock() == &BR.getCFG()->getExit()) S = GetPreviousStmt(EndNode);
Ted Kremenekcf118d42009-02-04 23:49:09 +0000896 }
897 if (!S) S = GetStmt(ProgP);
898
Ted Kremenekbb77e9b2008-05-01 22:50:36 +0000899 return S;
900}
901
902PathDiagnosticPiece*
903BugReport::getEndPath(BugReporter& BR,
Ted Kremenek3148eb42009-01-24 00:55:43 +0000904 const ExplodedNode<GRState>* EndPathNode) {
Ted Kremenekbb77e9b2008-05-01 22:50:36 +0000905
906 Stmt* S = getStmt(BR);
Ted Kremenek61f3e052008-04-03 04:42:52 +0000907
908 if (!S)
909 return NULL;
910
Ted Kremenekc9fa2f72008-05-01 23:13:35 +0000911 FullSourceLoc L(S->getLocStart(), BR.getContext().getSourceManager());
Ted Kremenek1fbfd5b2009-03-06 23:58:11 +0000912 PathDiagnosticPiece* P = new PathDiagnosticEventPiece(L, getDescription());
Ted Kremenek61f3e052008-04-03 04:42:52 +0000913
Ted Kremenekde7161f2008-04-03 18:00:37 +0000914 const SourceRange *Beg, *End;
Ted Kremenekbb77e9b2008-05-01 22:50:36 +0000915 getRanges(BR, Beg, End);
Ted Kremenekcf118d42009-02-04 23:49:09 +0000916
Ted Kremenekbb77e9b2008-05-01 22:50:36 +0000917 for (; Beg != End; ++Beg)
918 P->addRange(*Beg);
Ted Kremenek61f3e052008-04-03 04:42:52 +0000919
920 return P;
921}
922
Ted Kremenekbb77e9b2008-05-01 22:50:36 +0000923void BugReport::getRanges(BugReporter& BR, const SourceRange*& beg,
924 const SourceRange*& end) {
925
926 if (Expr* E = dyn_cast_or_null<Expr>(getStmt(BR))) {
927 R = E->getSourceRange();
Ted Kremenek9b5e5052009-02-27 20:05:10 +0000928 assert(R.isValid());
Ted Kremenekbb77e9b2008-05-01 22:50:36 +0000929 beg = &R;
930 end = beg+1;
931 }
932 else
933 beg = end = 0;
Ted Kremenekf1ae7052008-04-03 17:57:38 +0000934}
935
Ted Kremenekcf118d42009-02-04 23:49:09 +0000936SourceLocation BugReport::getLocation() const {
937 if (EndNode)
Ted Kremenek9b5e5052009-02-27 20:05:10 +0000938 if (Stmt* S = GetCurrentOrPreviousStmt(EndNode)) {
939 // For member expressions, return the location of the '.' or '->'.
940 if (MemberExpr* ME = dyn_cast<MemberExpr>(S))
941 return ME->getMemberLoc();
942
Ted Kremenekcf118d42009-02-04 23:49:09 +0000943 return S->getLocStart();
Ted Kremenek9b5e5052009-02-27 20:05:10 +0000944 }
Ted Kremenekcf118d42009-02-04 23:49:09 +0000945
946 return FullSourceLoc();
Ted Kremenekd2f642b2008-04-14 17:39:48 +0000947}
948
Ted Kremenek3148eb42009-01-24 00:55:43 +0000949PathDiagnosticPiece* BugReport::VisitNode(const ExplodedNode<GRState>* N,
950 const ExplodedNode<GRState>* PrevN,
951 const ExplodedGraph<GRState>& G,
Ted Kremenekfe9e5432009-02-18 03:48:14 +0000952 BugReporter& BR,
953 NodeResolver &NR) {
Ted Kremenek50a6d0c2008-04-09 21:41:14 +0000954 return NULL;
955}
956
Ted Kremenekcf118d42009-02-04 23:49:09 +0000957//===----------------------------------------------------------------------===//
958// Methods for BugReporter and subclasses.
959//===----------------------------------------------------------------------===//
960
961BugReportEquivClass::~BugReportEquivClass() {
962 for (iterator I=begin(), E=end(); I!=E; ++I) delete *I;
963}
964
965GRBugReporter::~GRBugReporter() { FlushReports(); }
966BugReporterData::~BugReporterData() {}
967
968ExplodedGraph<GRState>&
969GRBugReporter::getGraph() { return Eng.getGraph(); }
970
971GRStateManager&
972GRBugReporter::getStateManager() { return Eng.getStateManager(); }
973
974BugReporter::~BugReporter() { FlushReports(); }
975
976void BugReporter::FlushReports() {
977 if (BugTypes.isEmpty())
978 return;
979
980 // First flush the warnings for each BugType. This may end up creating new
981 // warnings and new BugTypes. Because ImmutableSet is a functional data
982 // structure, we do not need to worry about the iterators being invalidated.
983 for (BugTypesTy::iterator I=BugTypes.begin(), E=BugTypes.end(); I!=E; ++I)
984 const_cast<BugType*>(*I)->FlushReports(*this);
985
986 // Iterate through BugTypes a second time. BugTypes may have been updated
987 // with new BugType objects and new warnings.
988 for (BugTypesTy::iterator I=BugTypes.begin(), E=BugTypes.end(); I!=E; ++I) {
989 BugType *BT = const_cast<BugType*>(*I);
990
991 typedef llvm::FoldingSet<BugReportEquivClass> SetTy;
992 SetTy& EQClasses = BT->EQClasses;
993
994 for (SetTy::iterator EI=EQClasses.begin(), EE=EQClasses.end(); EI!=EE;++EI){
995 BugReportEquivClass& EQ = *EI;
996 FlushReport(EQ);
997 }
Ted Kremeneka43a1eb2008-04-23 23:02:12 +0000998
Ted Kremenekcf118d42009-02-04 23:49:09 +0000999 // Delete the BugType object. This will also delete the equivalence
1000 // classes.
1001 delete BT;
Ted Kremenek94826a72008-04-03 04:59:14 +00001002 }
Ted Kremenekcf118d42009-02-04 23:49:09 +00001003
1004 // Remove all references to the BugType objects.
1005 BugTypes = F.GetEmptySet();
1006}
1007
1008//===----------------------------------------------------------------------===//
1009// PathDiagnostics generation.
1010//===----------------------------------------------------------------------===//
1011
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001012static std::pair<std::pair<ExplodedGraph<GRState>*, NodeBackMap*>,
Ted Kremenekcf118d42009-02-04 23:49:09 +00001013 std::pair<ExplodedNode<GRState>*, unsigned> >
1014MakeReportGraph(const ExplodedGraph<GRState>* G,
1015 const ExplodedNode<GRState>** NStart,
1016 const ExplodedNode<GRState>** NEnd) {
Ted Kremenek94826a72008-04-03 04:59:14 +00001017
Ted Kremenekcf118d42009-02-04 23:49:09 +00001018 // Create the trimmed graph. It will contain the shortest paths from the
1019 // error nodes to the root. In the new graph we should only have one
1020 // error node unless there are two or more error nodes with the same minimum
1021 // path length.
1022 ExplodedGraph<GRState>* GTrim;
1023 InterExplodedGraphMap<GRState>* NMap;
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001024
1025 llvm::DenseMap<const void*, const void*> InverseMap;
1026 llvm::tie(GTrim, NMap) = G->Trim(NStart, NEnd, &InverseMap);
Ted Kremenekcf118d42009-02-04 23:49:09 +00001027
1028 // Create owning pointers for GTrim and NMap just to ensure that they are
1029 // released when this function exists.
1030 llvm::OwningPtr<ExplodedGraph<GRState> > AutoReleaseGTrim(GTrim);
1031 llvm::OwningPtr<InterExplodedGraphMap<GRState> > AutoReleaseNMap(NMap);
1032
1033 // Find the (first) error node in the trimmed graph. We just need to consult
1034 // the node map (NMap) which maps from nodes in the original graph to nodes
1035 // in the new graph.
1036 const ExplodedNode<GRState>* N = 0;
1037 unsigned NodeIndex = 0;
1038
1039 for (const ExplodedNode<GRState>** I = NStart; I != NEnd; ++I)
1040 if ((N = NMap->getMappedNode(*I))) {
1041 NodeIndex = (I - NStart) / sizeof(*I);
1042 break;
1043 }
1044
1045 assert(N && "No error node found in the trimmed graph.");
1046
1047 // Create a new (third!) graph with a single path. This is the graph
1048 // that will be returned to the caller.
Ted Kremenek3148eb42009-01-24 00:55:43 +00001049 ExplodedGraph<GRState> *GNew =
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001050 new ExplodedGraph<GRState>(GTrim->getCFG(), GTrim->getCodeDecl(),
1051 GTrim->getContext());
Ted Kremenekcf118d42009-02-04 23:49:09 +00001052
Ted Kremenek10aa5542009-03-12 23:41:59 +00001053 // Sometimes the trimmed graph can contain a cycle. Perform a reverse BFS
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001054 // to the root node, and then construct a new graph that contains only
1055 // a single path.
Ted Kremenek3148eb42009-01-24 00:55:43 +00001056 llvm::DenseMap<const void*,unsigned> Visited;
Ted Kremenek10aa5542009-03-12 23:41:59 +00001057 std::queue<const ExplodedNode<GRState>*> WS;
1058 WS.push(N);
1059
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001060 unsigned cnt = 0;
Ted Kremenek3148eb42009-01-24 00:55:43 +00001061 const ExplodedNode<GRState>* Root = 0;
Ted Kremenekc1da4412008-06-17 19:14:06 +00001062
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001063 while (!WS.empty()) {
Ted Kremenek10aa5542009-03-12 23:41:59 +00001064 const ExplodedNode<GRState>* Node = WS.front();
1065 WS.pop();
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001066
1067 if (Visited.find(Node) != Visited.end())
1068 continue;
1069
1070 Visited[Node] = cnt++;
1071
1072 if (Node->pred_empty()) {
1073 Root = Node;
1074 break;
1075 }
1076
Ted Kremenek3148eb42009-01-24 00:55:43 +00001077 for (ExplodedNode<GRState>::const_pred_iterator I=Node->pred_begin(),
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001078 E=Node->pred_end(); I!=E; ++I)
Ted Kremenek10aa5542009-03-12 23:41:59 +00001079 WS.push(*I);
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001080 }
Ted Kremenekcf118d42009-02-04 23:49:09 +00001081
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001082 assert (Root);
1083
Ted Kremenek10aa5542009-03-12 23:41:59 +00001084 // Now walk from the root down the BFS path, always taking the successor
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001085 // with the lowest number.
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001086 ExplodedNode<GRState> *Last = 0, *First = 0;
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001087 NodeBackMap *BM = new NodeBackMap();
Ted Kremenekcf118d42009-02-04 23:49:09 +00001088
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001089 for ( N = Root ;;) {
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001090 // Lookup the number associated with the current node.
Ted Kremenek3148eb42009-01-24 00:55:43 +00001091 llvm::DenseMap<const void*,unsigned>::iterator I = Visited.find(N);
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001092 assert (I != Visited.end());
1093
1094 // Create the equivalent node in the new graph with the same state
1095 // and location.
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001096 ExplodedNode<GRState>* NewN =
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001097 GNew->getNode(N->getLocation(), N->getState());
1098
1099 // Store the mapping to the original node.
1100 llvm::DenseMap<const void*, const void*>::iterator IMitr=InverseMap.find(N);
1101 assert(IMitr != InverseMap.end() && "No mapping to original node.");
1102 (*BM)[NewN] = (const ExplodedNode<GRState>*) IMitr->second;
Ted Kremenekcf118d42009-02-04 23:49:09 +00001103
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001104 // Link up the new node with the previous node.
1105 if (Last)
1106 NewN->addPredecessor(Last);
Ted Kremeneka43a1eb2008-04-23 23:02:12 +00001107
1108 Last = NewN;
Ted Kremenekcf118d42009-02-04 23:49:09 +00001109
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001110 // Are we at the final node?
1111 if (I->second == 0) {
1112 First = NewN;
Ted Kremenekc1da4412008-06-17 19:14:06 +00001113 break;
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001114 }
Ted Kremenekcf118d42009-02-04 23:49:09 +00001115
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001116 // Find the next successor node. We choose the node that is marked
1117 // with the lowest DFS number.
Ted Kremenek3148eb42009-01-24 00:55:43 +00001118 ExplodedNode<GRState>::const_succ_iterator SI = N->succ_begin();
1119 ExplodedNode<GRState>::const_succ_iterator SE = N->succ_end();
Ted Kremenekc1da4412008-06-17 19:14:06 +00001120 N = 0;
1121
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001122 for (unsigned MinVal = 0; SI != SE; ++SI) {
Ted Kremenekcf118d42009-02-04 23:49:09 +00001123
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001124 I = Visited.find(*SI);
1125
1126 if (I == Visited.end())
1127 continue;
1128
1129 if (!N || I->second < MinVal) {
1130 N = *SI;
1131 MinVal = I->second;
Ted Kremenekc1da4412008-06-17 19:14:06 +00001132 }
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001133 }
Ted Kremenekcf118d42009-02-04 23:49:09 +00001134
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001135 assert (N);
Ted Kremeneka43a1eb2008-04-23 23:02:12 +00001136 }
Ted Kremenekcf118d42009-02-04 23:49:09 +00001137
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001138 assert (First);
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001139 return std::make_pair(std::make_pair(GNew, BM),
1140 std::make_pair(First, NodeIndex));
Ted Kremeneka43a1eb2008-04-23 23:02:12 +00001141}
1142
Ted Kremenek0e5c8d42009-03-10 05:16:17 +00001143/// CompactPathDiagnostic - This function postprocesses a PathDiagnostic object
1144/// and collapses PathDiagosticPieces that are expanded by macros.
1145static void CompactPathDiagnostic(PathDiagnostic &PD, const SourceManager& SM) {
1146 typedef std::vector<std::pair<PathDiagnosticMacroPiece*, SourceLocation> >
1147 MacroStackTy;
1148
1149 typedef std::vector<PathDiagnosticPiece*>
1150 PiecesTy;
1151
1152 MacroStackTy MacroStack;
1153 PiecesTy Pieces;
1154
1155 for (PathDiagnostic::iterator I = PD.begin(), E = PD.end(); I!=E; ++I) {
1156 // Get the location of the PathDiagnosticPiece.
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +00001157 const FullSourceLoc Loc = I->getLocation().asLocation();
Ted Kremenek0e5c8d42009-03-10 05:16:17 +00001158
1159 // Determine the instantiation location, which is the location we group
1160 // related PathDiagnosticPieces.
1161 SourceLocation InstantiationLoc = Loc.isMacroID() ?
1162 SM.getInstantiationLoc(Loc) :
1163 SourceLocation();
1164
1165 if (Loc.isFileID()) {
1166 MacroStack.clear();
1167 Pieces.push_back(&*I);
1168 continue;
1169 }
1170
1171 assert(Loc.isMacroID());
1172
1173 // Is the PathDiagnosticPiece within the same macro group?
1174 if (!MacroStack.empty() && InstantiationLoc == MacroStack.back().second) {
1175 MacroStack.back().first->push_back(&*I);
1176 continue;
1177 }
1178
1179 // We aren't in the same group. Are we descending into a new macro
1180 // or are part of an old one?
1181 PathDiagnosticMacroPiece *MacroGroup = 0;
1182
1183 SourceLocation ParentInstantiationLoc = InstantiationLoc.isMacroID() ?
1184 SM.getInstantiationLoc(Loc) :
1185 SourceLocation();
1186
1187 // Walk the entire macro stack.
1188 while (!MacroStack.empty()) {
1189 if (InstantiationLoc == MacroStack.back().second) {
1190 MacroGroup = MacroStack.back().first;
1191 break;
1192 }
1193
1194 if (ParentInstantiationLoc == MacroStack.back().second) {
1195 MacroGroup = MacroStack.back().first;
1196 break;
1197 }
1198
1199 MacroStack.pop_back();
1200 }
1201
1202 if (!MacroGroup || ParentInstantiationLoc == MacroStack.back().second) {
1203 // Create a new macro group and add it to the stack.
1204 PathDiagnosticMacroPiece *NewGroup = new PathDiagnosticMacroPiece(Loc);
1205
1206 if (MacroGroup)
1207 MacroGroup->push_back(NewGroup);
1208 else {
1209 assert(InstantiationLoc.isFileID());
1210 Pieces.push_back(NewGroup);
1211 }
1212
1213 MacroGroup = NewGroup;
1214 MacroStack.push_back(std::make_pair(MacroGroup, InstantiationLoc));
1215 }
1216
1217 // Finally, add the PathDiagnosticPiece to the group.
1218 MacroGroup->push_back(&*I);
1219 }
1220
1221 // Now take the pieces and construct a new PathDiagnostic.
1222 PD.resetPath(false);
1223
1224 for (PiecesTy::iterator I=Pieces.begin(), E=Pieces.end(); I!=E; ++I) {
1225 if (PathDiagnosticMacroPiece *MP=dyn_cast<PathDiagnosticMacroPiece>(*I))
1226 if (!MP->containsEvent()) {
1227 delete MP;
1228 continue;
1229 }
1230
1231 PD.push_back(*I);
1232 }
1233}
1234
Ted Kremenek7dc86642009-03-31 20:22:36 +00001235void GRBugReporter::GeneratePathDiagnostic(PathDiagnostic& PD,
1236 BugReportEquivClass& EQ) {
1237
1238 std::vector<const ExplodedNode<GRState>*> Nodes;
1239
Ted Kremenekcf118d42009-02-04 23:49:09 +00001240 for (BugReportEquivClass::iterator I=EQ.begin(), E=EQ.end(); I!=E; ++I) {
1241 const ExplodedNode<GRState>* N = I->getEndNode();
1242 if (N) Nodes.push_back(N);
1243 }
1244
1245 if (Nodes.empty())
1246 return;
Ted Kremeneka43a1eb2008-04-23 23:02:12 +00001247
1248 // Construct a new graph that contains only a single path from the error
Ted Kremenekcf118d42009-02-04 23:49:09 +00001249 // node to a root.
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001250 const std::pair<std::pair<ExplodedGraph<GRState>*, NodeBackMap*>,
Ted Kremenek7dc86642009-03-31 20:22:36 +00001251 std::pair<ExplodedNode<GRState>*, unsigned> >&
1252 GPair = MakeReportGraph(&getGraph(), &Nodes[0], &Nodes[0] + Nodes.size());
Ted Kremeneka43a1eb2008-04-23 23:02:12 +00001253
Ted Kremenekcf118d42009-02-04 23:49:09 +00001254 // Find the BugReport with the original location.
1255 BugReport *R = 0;
1256 unsigned i = 0;
1257 for (BugReportEquivClass::iterator I=EQ.begin(), E=EQ.end(); I!=E; ++I, ++i)
1258 if (i == GPair.second.second) { R = *I; break; }
1259
1260 assert(R && "No original report found for sliced graph.");
Ted Kremeneka43a1eb2008-04-23 23:02:12 +00001261
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001262 llvm::OwningPtr<ExplodedGraph<GRState> > ReportGraph(GPair.first.first);
1263 llvm::OwningPtr<NodeBackMap> BackMap(GPair.first.second);
Ted Kremenekcf118d42009-02-04 23:49:09 +00001264 const ExplodedNode<GRState> *N = GPair.second.first;
Ted Kremenek7dc86642009-03-31 20:22:36 +00001265
Ted Kremenekcf118d42009-02-04 23:49:09 +00001266 // Start building the path diagnostic...
1267 if (PathDiagnosticPiece* Piece = R->getEndPath(*this, N))
Ted Kremenekbd7efa82008-04-17 23:44:37 +00001268 PD.push_back(Piece);
1269 else
1270 return;
Ted Kremenek7dc86642009-03-31 20:22:36 +00001271
1272 PathDiagnosticBuilder PDB(*this, ReportGraph.get(), R, BackMap.get(),
1273 getStateManager().getCodeDecl(),
Ted Kremenekbabdd7b2009-03-27 05:06:10 +00001274 getPathDiagnosticClient());
Ted Kremenekbd7efa82008-04-17 23:44:37 +00001275
Ted Kremenek7dc86642009-03-31 20:22:36 +00001276 switch (PDB.getGenerationScheme()) {
1277 case PathDiagnosticClient::Extensive:
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +00001278 GenerateExtensivePathDiagnostic(PD,PDB, N);
1279 break;
Ted Kremenek7dc86642009-03-31 20:22:36 +00001280 case PathDiagnosticClient::Minimal:
1281 GenerateMinimalPathDiagnostic(PD, PDB, N);
1282 break;
1283 }
1284
1285 // After constructing the full PathDiagnostic, do a pass over it to compact
1286 // PathDiagnosticPieces that occur within a macro.
1287 CompactPathDiagnostic(PD, PDB.getSourceManager());
1288}
1289
Ted Kremenekcf118d42009-02-04 23:49:09 +00001290void BugReporter::Register(BugType *BT) {
1291 BugTypes = F.Add(BugTypes, BT);
Ted Kremenek76d90c82008-05-16 18:33:14 +00001292}
1293
Ted Kremenekcf118d42009-02-04 23:49:09 +00001294void BugReporter::EmitReport(BugReport* R) {
1295 // Compute the bug report's hash to determine its equivalence class.
1296 llvm::FoldingSetNodeID ID;
1297 R->Profile(ID);
Ted Kremenek61f3e052008-04-03 04:42:52 +00001298
Ted Kremenekcf118d42009-02-04 23:49:09 +00001299 // Lookup the equivance class. If there isn't one, create it.
1300 BugType& BT = R->getBugType();
1301 Register(&BT);
1302 void *InsertPos;
1303 BugReportEquivClass* EQ = BT.EQClasses.FindNodeOrInsertPos(ID, InsertPos);
1304
1305 if (!EQ) {
1306 EQ = new BugReportEquivClass(R);
1307 BT.EQClasses.InsertNode(EQ, InsertPos);
1308 }
1309 else
1310 EQ->AddReport(R);
Ted Kremenek61f3e052008-04-03 04:42:52 +00001311}
1312
Ted Kremenekcf118d42009-02-04 23:49:09 +00001313void BugReporter::FlushReport(BugReportEquivClass& EQ) {
1314 assert(!EQ.Reports.empty());
1315 BugReport &R = **EQ.begin();
1316
1317 // FIXME: Make sure we use the 'R' for the path that was actually used.
1318 // Probably doesn't make a difference in practice.
1319 BugType& BT = R.getBugType();
1320
1321 llvm::OwningPtr<PathDiagnostic> D(new PathDiagnostic(R.getBugType().getName(),
1322 R.getDescription(),
1323 BT.getCategory()));
1324 GeneratePathDiagnostic(*D.get(), EQ);
Ted Kremenek072192b2008-04-30 23:47:44 +00001325
1326 // Get the meta data.
Ted Kremenek072192b2008-04-30 23:47:44 +00001327 std::pair<const char**, const char**> Meta = R.getExtraDescriptiveText();
Ted Kremenek3148eb42009-01-24 00:55:43 +00001328 for (const char** s = Meta.first; s != Meta.second; ++s) D->addMeta(*s);
Ted Kremenek75840e12008-04-18 01:56:37 +00001329
Ted Kremenek3148eb42009-01-24 00:55:43 +00001330 // Emit a summary diagnostic to the regular Diagnostics engine.
Ted Kremenekc0959972008-07-02 21:24:01 +00001331 PathDiagnosticClient* PD = getPathDiagnosticClient();
Ted Kremenek3148eb42009-01-24 00:55:43 +00001332 const SourceRange *Beg = 0, *End = 0;
1333 R.getRanges(*this, Beg, End);
1334 Diagnostic& Diag = getDiagnostic();
Ted Kremenekcf118d42009-02-04 23:49:09 +00001335 FullSourceLoc L(R.getLocation(), getSourceManager());
Ted Kremenekd90e7082009-02-07 22:36:41 +00001336 unsigned ErrorDiag = Diag.getCustomDiagID(Diagnostic::Warning,
1337 R.getDescription().c_str());
Ted Kremenek57202072008-07-14 17:40:50 +00001338
Ted Kremenek3148eb42009-01-24 00:55:43 +00001339 switch (End-Beg) {
Chris Lattner0a14eee2008-11-18 07:04:44 +00001340 default: assert(0 && "Don't handle this many ranges yet!");
1341 case 0: Diag.Report(L, ErrorDiag); break;
1342 case 1: Diag.Report(L, ErrorDiag) << Beg[0]; break;
1343 case 2: Diag.Report(L, ErrorDiag) << Beg[0] << Beg[1]; break;
1344 case 3: Diag.Report(L, ErrorDiag) << Beg[0] << Beg[1] << Beg[2]; break;
Ted Kremenek2f0e89e2008-04-18 22:56:53 +00001345 }
Ted Kremenek3148eb42009-01-24 00:55:43 +00001346
1347 // Emit a full diagnostic for the path if we have a PathDiagnosticClient.
1348 if (!PD)
1349 return;
1350
1351 if (D->empty()) {
Ted Kremenek1fbfd5b2009-03-06 23:58:11 +00001352 PathDiagnosticPiece* piece =
1353 new PathDiagnosticEventPiece(L, R.getDescription());
1354
Ted Kremenek3148eb42009-01-24 00:55:43 +00001355 for ( ; Beg != End; ++Beg) piece->addRange(*Beg);
1356 D->push_back(piece);
1357 }
1358
1359 PD->HandlePathDiagnostic(D.take());
Ted Kremenek61f3e052008-04-03 04:42:52 +00001360}
Ted Kremenek57202072008-07-14 17:40:50 +00001361
Ted Kremenek8c036c72008-09-20 04:23:38 +00001362void BugReporter::EmitBasicReport(const char* name, const char* str,
1363 SourceLocation Loc,
1364 SourceRange* RBeg, unsigned NumRanges) {
1365 EmitBasicReport(name, "", str, Loc, RBeg, NumRanges);
1366}
Ted Kremenekcf118d42009-02-04 23:49:09 +00001367
Ted Kremenek8c036c72008-09-20 04:23:38 +00001368void BugReporter::EmitBasicReport(const char* name, const char* category,
1369 const char* str, SourceLocation Loc,
1370 SourceRange* RBeg, unsigned NumRanges) {
1371
Ted Kremenekcf118d42009-02-04 23:49:09 +00001372 // 'BT' will be owned by BugReporter as soon as we call 'EmitReport'.
1373 BugType *BT = new BugType(name, category);
Chris Lattner0a14eee2008-11-18 07:04:44 +00001374 FullSourceLoc L = getContext().getFullLoc(Loc);
Ted Kremenekcf118d42009-02-04 23:49:09 +00001375 RangedBugReport *R = new DiagBugReport(*BT, str, L);
1376 for ( ; NumRanges > 0 ; --NumRanges, ++RBeg) R->addRange(*RBeg);
1377 EmitReport(R);
Ted Kremenek57202072008-07-14 17:40:50 +00001378}