blob: 2baef5e4bfe174d24db5a72efe145045493c7d0f [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 Kremenekc3f83ad2009-04-01 17:18:21 +0000147 const Stmt *getParent(const Stmt *S) {
148 return getParentMap().getParent(S);
149 }
150
Ted Kremenek51a735c2009-04-01 17:52:26 +0000151 const CFG& getCFG() {
152 return *BR.getCFG();
153 }
154
155 const Decl& getCodeDecl() {
156 return BR.getStateManager().getCodeDecl();
157 }
158
Ted Kremenek7dc86642009-03-31 20:22:36 +0000159 ExplodedGraph<GRState>& getGraph() { return *ReportGraph; }
160 NodeMapClosure& getNodeMapClosure() { return NMC; }
161 ASTContext& getContext() { return BR.getContext(); }
162 SourceManager& getSourceManager() { return SMgr; }
163 BugReport& getReport() { return *R; }
164 GRBugReporter& getBugReporter() { return BR; }
165 GRStateManager& getStateManager() { return BR.getStateManager(); }
166
Ted Kremenekd8c938b2009-03-27 21:16:25 +0000167 PathDiagnosticLocation getEnclosingStmtLocation(const Stmt *S);
168
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000169 PathDiagnosticLocation
170 getEnclosingStmtLocation(const PathDiagnosticLocation &L) {
171 if (const Stmt *S = L.asStmt())
172 return getEnclosingStmtLocation(S);
173
174 return L;
175 }
176
Ted Kremenek7dc86642009-03-31 20:22:36 +0000177 PathDiagnosticClient::PathGenerationScheme getGenerationScheme() const {
178 return PDC ? PDC->getGenerationScheme() : PathDiagnosticClient::Extensive;
179 }
180
Ted Kremenekbabdd7b2009-03-27 05:06:10 +0000181 bool supportsLogicalOpControlFlow() const {
182 return PDC ? PDC->supportsLogicalOpControlFlow() : true;
183 }
184};
185} // end anonymous namespace
186
Ted Kremenek00605e02009-03-27 20:55:39 +0000187PathDiagnosticLocation
188PathDiagnosticBuilder::ExecutionContinues(const ExplodedNode<GRState>* N) {
189 if (Stmt *S = GetNextStmt(N))
190 return PathDiagnosticLocation(S, SMgr);
191
192 return FullSourceLoc(CodeDecl.getBody()->getRBracLoc(), SMgr);
Ted Kremenek082cb8d2009-03-12 18:41:53 +0000193}
194
Ted Kremenek00605e02009-03-27 20:55:39 +0000195PathDiagnosticLocation
Ted Kremenekbabdd7b2009-03-27 05:06:10 +0000196PathDiagnosticBuilder::ExecutionContinues(llvm::raw_string_ostream& os,
197 const ExplodedNode<GRState>* N) {
198
Ted Kremenek143ca222008-05-06 18:11:09 +0000199 // Slow, but probably doesn't matter.
Ted Kremenekb697b102009-02-23 22:44:26 +0000200 if (os.str().empty())
201 os << ' ';
Ted Kremenek143ca222008-05-06 18:11:09 +0000202
Ted Kremenek00605e02009-03-27 20:55:39 +0000203 const PathDiagnosticLocation &Loc = ExecutionContinues(N);
Ted Kremenek082cb8d2009-03-12 18:41:53 +0000204
Ted Kremenek00605e02009-03-27 20:55:39 +0000205 if (Loc.asStmt())
Ted Kremenekb697b102009-02-23 22:44:26 +0000206 os << "Execution continues on line "
Ted Kremenek00605e02009-03-27 20:55:39 +0000207 << SMgr.getInstantiationLineNumber(Loc.asLocation()) << '.';
Ted Kremenekb697b102009-02-23 22:44:26 +0000208 else
Ted Kremenekb479dad2009-02-23 23:13:51 +0000209 os << "Execution jumps to the end of the "
Ted Kremenekbabdd7b2009-03-27 05:06:10 +0000210 << (isa<ObjCMethodDecl>(CodeDecl) ? "method" : "function") << '.';
Ted Kremenek082cb8d2009-03-12 18:41:53 +0000211
212 return Loc;
Ted Kremenek143ca222008-05-06 18:11:09 +0000213}
214
Ted Kremenekd8c938b2009-03-27 21:16:25 +0000215PathDiagnosticLocation
216PathDiagnosticBuilder::getEnclosingStmtLocation(const Stmt *S) {
217 assert(S && "Null Stmt* passed to getEnclosingStmtLocation");
218 ParentMap &P = getParentMap();
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000219
220 while (isa<DeclStmt>(S) || isa<Expr>(S)) {
Ted Kremenekd8c938b2009-03-27 21:16:25 +0000221 const Stmt *Parent = P.getParent(S);
222
Ted Kremenekaf3e3d52009-03-28 03:37:59 +0000223 if (!Parent)
224 break;
Ted Kremenekd8c938b2009-03-27 21:16:25 +0000225
Ted Kremenekaf3e3d52009-03-28 03:37:59 +0000226 switch (Parent->getStmtClass()) {
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000227 case Stmt::BinaryOperatorClass: {
228 const BinaryOperator *B = cast<BinaryOperator>(Parent);
229 if (B->isLogicalOp())
230 return PathDiagnosticLocation(S, SMgr);
231 break;
232 }
233
Ted Kremenekaf3e3d52009-03-28 03:37:59 +0000234 case Stmt::CompoundStmtClass:
235 case Stmt::StmtExprClass:
Ted Kremenek1d9a23a2009-03-28 04:08:14 +0000236 return PathDiagnosticLocation(S, SMgr);
237 case Stmt::ChooseExprClass:
238 // Similar to '?' if we are referring to condition, just have the edge
239 // point to the entire choose expression.
240 if (cast<ChooseExpr>(Parent)->getCond() == S)
241 return PathDiagnosticLocation(Parent, SMgr);
242 else
243 return PathDiagnosticLocation(S, SMgr);
244 case Stmt::ConditionalOperatorClass:
245 // For '?', if we are referring to condition, just have the edge point
246 // to the entire '?' expression.
247 if (cast<ConditionalOperator>(Parent)->getCond() == S)
248 return PathDiagnosticLocation(Parent, SMgr);
249 else
250 return PathDiagnosticLocation(S, SMgr);
Ted Kremenekaf3e3d52009-03-28 03:37:59 +0000251 case Stmt::DoStmtClass:
252 if (cast<DoStmt>(Parent)->getCond() != S)
253 return PathDiagnosticLocation(S, SMgr);
254 break;
255 case Stmt::ForStmtClass:
256 if (cast<ForStmt>(Parent)->getBody() == S)
257 return PathDiagnosticLocation(S, SMgr);
258 break;
259 case Stmt::IfStmtClass:
260 if (cast<IfStmt>(Parent)->getCond() != S)
261 return PathDiagnosticLocation(S, SMgr);
262 break;
263 case Stmt::ObjCForCollectionStmtClass:
264 if (cast<ObjCForCollectionStmt>(Parent)->getBody() == S)
265 return PathDiagnosticLocation(S, SMgr);
266 break;
267 case Stmt::WhileStmtClass:
268 if (cast<WhileStmt>(Parent)->getCond() != S)
269 return PathDiagnosticLocation(S, SMgr);
270 break;
271 default:
272 break;
273 }
274
Ted Kremenekd8c938b2009-03-27 21:16:25 +0000275 S = Parent;
276 }
277
278 assert(S && "Cannot have null Stmt for PathDiagnosticLocation");
279 return PathDiagnosticLocation(S, SMgr);
280}
281
Ted Kremenekcf118d42009-02-04 23:49:09 +0000282//===----------------------------------------------------------------------===//
Ted Kremenek31061982009-03-31 23:00:32 +0000283// ScanNotableSymbols: closure-like callback for scanning Store bindings.
284//===----------------------------------------------------------------------===//
285
286static const VarDecl*
287GetMostRecentVarDeclBinding(const ExplodedNode<GRState>* N,
288 GRStateManager& VMgr, SVal X) {
289
290 for ( ; N ; N = N->pred_empty() ? 0 : *N->pred_begin()) {
291
292 ProgramPoint P = N->getLocation();
293
294 if (!isa<PostStmt>(P))
295 continue;
296
297 DeclRefExpr* DR = dyn_cast<DeclRefExpr>(cast<PostStmt>(P).getStmt());
298
299 if (!DR)
300 continue;
301
302 SVal Y = VMgr.GetSVal(N->getState(), DR);
303
304 if (X != Y)
305 continue;
306
307 VarDecl* VD = dyn_cast<VarDecl>(DR->getDecl());
308
309 if (!VD)
310 continue;
311
312 return VD;
313 }
314
315 return 0;
316}
317
318namespace {
319class VISIBILITY_HIDDEN NotableSymbolHandler
320: public StoreManager::BindingsHandler {
321
322 SymbolRef Sym;
323 const GRState* PrevSt;
324 const Stmt* S;
325 GRStateManager& VMgr;
326 const ExplodedNode<GRState>* Pred;
327 PathDiagnostic& PD;
328 BugReporter& BR;
329
330public:
331
332 NotableSymbolHandler(SymbolRef sym, const GRState* prevst, const Stmt* s,
333 GRStateManager& vmgr, const ExplodedNode<GRState>* pred,
334 PathDiagnostic& pd, BugReporter& br)
335 : Sym(sym), PrevSt(prevst), S(s), VMgr(vmgr), Pred(pred), PD(pd), BR(br) {}
336
337 bool HandleBinding(StoreManager& SMgr, Store store, const MemRegion* R,
338 SVal V) {
339
340 SymbolRef ScanSym = V.getAsSymbol();
341
342 if (ScanSym != Sym)
343 return true;
344
345 // Check if the previous state has this binding.
346 SVal X = VMgr.GetSVal(PrevSt, loc::MemRegionVal(R));
347
348 if (X == V) // Same binding?
349 return true;
350
351 // Different binding. Only handle assignments for now. We don't pull
352 // this check out of the loop because we will eventually handle other
353 // cases.
354
355 VarDecl *VD = 0;
356
357 if (const BinaryOperator* B = dyn_cast<BinaryOperator>(S)) {
358 if (!B->isAssignmentOp())
359 return true;
360
361 // What variable did we assign to?
362 DeclRefExpr* DR = dyn_cast<DeclRefExpr>(B->getLHS()->IgnoreParenCasts());
363
364 if (!DR)
365 return true;
366
367 VD = dyn_cast<VarDecl>(DR->getDecl());
368 }
369 else if (const DeclStmt* DS = dyn_cast<DeclStmt>(S)) {
370 // FIXME: Eventually CFGs won't have DeclStmts. Right now we
371 // assume that each DeclStmt has a single Decl. This invariant
372 // holds by contruction in the CFG.
373 VD = dyn_cast<VarDecl>(*DS->decl_begin());
374 }
375
376 if (!VD)
377 return true;
378
379 // What is the most recently referenced variable with this binding?
380 const VarDecl* MostRecent = GetMostRecentVarDeclBinding(Pred, VMgr, V);
381
382 if (!MostRecent)
383 return true;
384
385 // Create the diagnostic.
386 FullSourceLoc L(S->getLocStart(), BR.getSourceManager());
387
388 if (Loc::IsLocType(VD->getType())) {
389 std::string msg = "'" + std::string(VD->getNameAsString()) +
390 "' now aliases '" + MostRecent->getNameAsString() + "'";
391
392 PD.push_front(new PathDiagnosticEventPiece(L, msg));
393 }
394
395 return true;
396 }
397};
398}
399
400static void HandleNotableSymbol(const ExplodedNode<GRState>* N,
401 const Stmt* S,
402 SymbolRef Sym, BugReporter& BR,
403 PathDiagnostic& PD) {
404
405 const ExplodedNode<GRState>* Pred = N->pred_empty() ? 0 : *N->pred_begin();
406 const GRState* PrevSt = Pred ? Pred->getState() : 0;
407
408 if (!PrevSt)
409 return;
410
411 // Look at the region bindings of the current state that map to the
412 // specified symbol. Are any of them not in the previous state?
413 GRStateManager& VMgr = cast<GRBugReporter>(BR).getStateManager();
414 NotableSymbolHandler H(Sym, PrevSt, S, VMgr, Pred, PD, BR);
415 cast<GRBugReporter>(BR).getStateManager().iterBindings(N->getState(), H);
416}
417
418namespace {
419class VISIBILITY_HIDDEN ScanNotableSymbols
420: public StoreManager::BindingsHandler {
421
422 llvm::SmallSet<SymbolRef, 10> AlreadyProcessed;
423 const ExplodedNode<GRState>* N;
424 Stmt* S;
425 GRBugReporter& BR;
426 PathDiagnostic& PD;
427
428public:
429 ScanNotableSymbols(const ExplodedNode<GRState>* n, Stmt* s, GRBugReporter& br,
430 PathDiagnostic& pd)
431 : N(n), S(s), BR(br), PD(pd) {}
432
433 bool HandleBinding(StoreManager& SMgr, Store store,
434 const MemRegion* R, SVal V) {
435
436 SymbolRef ScanSym = V.getAsSymbol();
437
438 if (!ScanSym)
439 return true;
440
441 if (!BR.isNotable(ScanSym))
442 return true;
443
444 if (AlreadyProcessed.count(ScanSym))
445 return true;
446
447 AlreadyProcessed.insert(ScanSym);
448
449 HandleNotableSymbol(N, S, ScanSym, BR, PD);
450 return true;
451 }
452};
453} // end anonymous namespace
454
455//===----------------------------------------------------------------------===//
456// "Minimal" path diagnostic generation algorithm.
457//===----------------------------------------------------------------------===//
458
459static void GenerateMinimalPathDiagnostic(PathDiagnostic& PD,
460 PathDiagnosticBuilder &PDB,
461 const ExplodedNode<GRState> *N) {
462 ASTContext& Ctx = PDB.getContext();
463 SourceManager& SMgr = PDB.getSourceManager();
464 const ExplodedNode<GRState>* NextNode = N->pred_empty()
465 ? NULL : *(N->pred_begin());
466 while (NextNode) {
467 N = NextNode;
468 NextNode = GetPredecessorNode(N);
469
470 ProgramPoint P = N->getLocation();
471
472 if (const BlockEdge* BE = dyn_cast<BlockEdge>(&P)) {
473 CFGBlock* Src = BE->getSrc();
474 CFGBlock* Dst = BE->getDst();
475 Stmt* T = Src->getTerminator();
476
477 if (!T)
478 continue;
479
480 FullSourceLoc Start(T->getLocStart(), SMgr);
481
482 switch (T->getStmtClass()) {
483 default:
484 break;
485
486 case Stmt::GotoStmtClass:
487 case Stmt::IndirectGotoStmtClass: {
488 Stmt* S = GetNextStmt(N);
489
490 if (!S)
491 continue;
492
493 std::string sbuf;
494 llvm::raw_string_ostream os(sbuf);
495 const PathDiagnosticLocation &End = PDB.getEnclosingStmtLocation(S);
496
497 os << "Control jumps to line "
498 << End.asLocation().getInstantiationLineNumber();
499 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
500 os.str()));
501 break;
502 }
503
504 case Stmt::SwitchStmtClass: {
505 // Figure out what case arm we took.
506 std::string sbuf;
507 llvm::raw_string_ostream os(sbuf);
508
509 if (Stmt* S = Dst->getLabel()) {
510 PathDiagnosticLocation End(S, SMgr);
511
512 switch (S->getStmtClass()) {
513 default:
514 os << "No cases match in the switch statement. "
515 "Control jumps to line "
516 << End.asLocation().getInstantiationLineNumber();
517 break;
518 case Stmt::DefaultStmtClass:
519 os << "Control jumps to the 'default' case at line "
520 << End.asLocation().getInstantiationLineNumber();
521 break;
522
523 case Stmt::CaseStmtClass: {
524 os << "Control jumps to 'case ";
525 CaseStmt* Case = cast<CaseStmt>(S);
526 Expr* LHS = Case->getLHS()->IgnoreParenCasts();
527
528 // Determine if it is an enum.
529 bool GetRawInt = true;
530
531 if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(LHS)) {
532 // FIXME: Maybe this should be an assertion. Are there cases
533 // were it is not an EnumConstantDecl?
534 EnumConstantDecl* D =
535 dyn_cast<EnumConstantDecl>(DR->getDecl());
536
537 if (D) {
538 GetRawInt = false;
539 os << D->getNameAsString();
540 }
541 }
542
543 if (GetRawInt) {
544
545 // Not an enum.
546 Expr* CondE = cast<SwitchStmt>(T)->getCond();
547 unsigned bits = Ctx.getTypeSize(CondE->getType());
548 llvm::APSInt V(bits, false);
549
550 if (!LHS->isIntegerConstantExpr(V, Ctx, 0, true)) {
551 assert (false && "Case condition must be constant.");
552 continue;
553 }
554
555 os << V;
556 }
557
558 os << ":' at line "
559 << End.asLocation().getInstantiationLineNumber();
560 break;
561 }
562 }
563 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
564 os.str()));
565 }
566 else {
567 os << "'Default' branch taken. ";
568 const PathDiagnosticLocation &End = PDB.ExecutionContinues(os, N);
569 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
570 os.str()));
571 }
572
573 break;
574 }
575
576 case Stmt::BreakStmtClass:
577 case Stmt::ContinueStmtClass: {
578 std::string sbuf;
579 llvm::raw_string_ostream os(sbuf);
580 PathDiagnosticLocation End = PDB.ExecutionContinues(os, N);
581 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
582 os.str()));
583 break;
584 }
585
586 // Determine control-flow for ternary '?'.
587 case Stmt::ConditionalOperatorClass: {
588 std::string sbuf;
589 llvm::raw_string_ostream os(sbuf);
590 os << "'?' condition is ";
591
592 if (*(Src->succ_begin()+1) == Dst)
593 os << "false";
594 else
595 os << "true";
596
597 PathDiagnosticLocation End = PDB.ExecutionContinues(N);
598
599 if (const Stmt *S = End.asStmt())
600 End = PDB.getEnclosingStmtLocation(S);
601
602 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
603 os.str()));
604 break;
605 }
606
607 // Determine control-flow for short-circuited '&&' and '||'.
608 case Stmt::BinaryOperatorClass: {
609 if (!PDB.supportsLogicalOpControlFlow())
610 break;
611
612 BinaryOperator *B = cast<BinaryOperator>(T);
613 std::string sbuf;
614 llvm::raw_string_ostream os(sbuf);
615 os << "Left side of '";
616
617 if (B->getOpcode() == BinaryOperator::LAnd) {
618 os << "&&" << "' is ";
619
620 if (*(Src->succ_begin()+1) == Dst) {
621 os << "false";
622 PathDiagnosticLocation End(B->getLHS(), SMgr);
623 PathDiagnosticLocation Start(B->getOperatorLoc(), SMgr);
624 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
625 os.str()));
626 }
627 else {
628 os << "true";
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 }
635 else {
636 assert(B->getOpcode() == BinaryOperator::LOr);
637 os << "||" << "' is ";
638
639 if (*(Src->succ_begin()+1) == Dst) {
640 os << "false";
641 PathDiagnosticLocation Start(B->getLHS(), SMgr);
642 PathDiagnosticLocation End = PDB.ExecutionContinues(N);
643 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
644 os.str()));
645 }
646 else {
647 os << "true";
648 PathDiagnosticLocation End(B->getLHS(), SMgr);
649 PathDiagnosticLocation Start(B->getOperatorLoc(), SMgr);
650 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
651 os.str()));
652 }
653 }
654
655 break;
656 }
657
658 case Stmt::DoStmtClass: {
659 if (*(Src->succ_begin()) == Dst) {
660 std::string sbuf;
661 llvm::raw_string_ostream os(sbuf);
662
663 os << "Loop condition is true. ";
664 PathDiagnosticLocation End = PDB.ExecutionContinues(os, N);
665
666 if (const Stmt *S = End.asStmt())
667 End = PDB.getEnclosingStmtLocation(S);
668
669 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
670 os.str()));
671 }
672 else {
673 PathDiagnosticLocation End = PDB.ExecutionContinues(N);
674
675 if (const Stmt *S = End.asStmt())
676 End = PDB.getEnclosingStmtLocation(S);
677
678 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
679 "Loop condition is false. Exiting loop"));
680 }
681
682 break;
683 }
684
685 case Stmt::WhileStmtClass:
686 case Stmt::ForStmtClass: {
687 if (*(Src->succ_begin()+1) == Dst) {
688 std::string sbuf;
689 llvm::raw_string_ostream os(sbuf);
690
691 os << "Loop condition is false. ";
692 PathDiagnosticLocation End = PDB.ExecutionContinues(os, N);
693 if (const Stmt *S = End.asStmt())
694 End = PDB.getEnclosingStmtLocation(S);
695
696 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
697 os.str()));
698 }
699 else {
700 PathDiagnosticLocation End = PDB.ExecutionContinues(N);
701 if (const Stmt *S = End.asStmt())
702 End = PDB.getEnclosingStmtLocation(S);
703
704 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000705 "Loop condition is true. Entering loop body"));
Ted Kremenek31061982009-03-31 23:00:32 +0000706 }
707
708 break;
709 }
710
711 case Stmt::IfStmtClass: {
712 PathDiagnosticLocation End = PDB.ExecutionContinues(N);
713
714 if (const Stmt *S = End.asStmt())
715 End = PDB.getEnclosingStmtLocation(S);
716
717 if (*(Src->succ_begin()+1) == Dst)
718 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000719 "Taking false branch"));
Ted Kremenek31061982009-03-31 23:00:32 +0000720 else
721 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000722 "Taking true branch"));
Ted Kremenek31061982009-03-31 23:00:32 +0000723
724 break;
725 }
726 }
727 }
728
729 if (PathDiagnosticPiece* p =
730 PDB.getReport().VisitNode(N, NextNode, PDB.getGraph(),
731 PDB.getBugReporter(),
732 PDB.getNodeMapClosure())) {
733 PD.push_front(p);
734 }
735
736 if (const PostStmt* PS = dyn_cast<PostStmt>(&P)) {
737 // Scan the region bindings, and see if a "notable" symbol has a new
738 // lval binding.
739 ScanNotableSymbols SNS(N, PS->getStmt(), PDB.getBugReporter(), PD);
740 PDB.getStateManager().iterBindings(N->getState(), SNS);
741 }
742 }
743}
744
745//===----------------------------------------------------------------------===//
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000746// "Extensive" PathDiagnostic generation.
747//===----------------------------------------------------------------------===//
748
749static bool IsControlFlowExpr(const Stmt *S) {
750 const Expr *E = dyn_cast<Expr>(S);
751
752 if (!E)
753 return false;
754
755 E = E->IgnoreParenCasts();
756
757 if (isa<ConditionalOperator>(E))
758 return true;
759
760 if (const BinaryOperator *B = dyn_cast<BinaryOperator>(E))
761 if (B->isLogicalOp())
762 return true;
763
764 return false;
765}
766
767static void GenExtAddEdge(PathDiagnostic& PD,
768 PathDiagnosticBuilder &PDB,
769 PathDiagnosticLocation NewLoc,
770 PathDiagnosticLocation &PrevLoc,
Ted Kremenekc3f83ad2009-04-01 17:18:21 +0000771 bool allowBlockJump = false) {
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000772
773 if (const Stmt *S = NewLoc.asStmt()) {
774 if (IsControlFlowExpr(S))
775 return;
776 }
777
778
779 if (!PrevLoc.isValid()) {
780 PrevLoc = NewLoc;
781 return;
782 }
783
784 if (NewLoc == PrevLoc)
785 return;
Ted Kremenekc3f83ad2009-04-01 17:18:21 +0000786
Ted Kremenek0dc65be2009-04-01 19:43:28 +0000787 // Are we jumping between statements within the same compound statement?
Ted Kremenekc3f83ad2009-04-01 17:18:21 +0000788 if (!allowBlockJump)
789 if (const Stmt *PS = PrevLoc.asStmt())
790 if (const Stmt *NS = NewLoc.asStmt()) {
791 const Stmt *parentPS = PDB.getParent(PS);
Ted Kremenek28de78b2009-04-02 03:30:55 +0000792 if (parentPS && isa<CompoundStmt>(parentPS) &&
793 parentPS == PDB.getParent(NS))
Ted Kremenekc3f83ad2009-04-01 17:18:21 +0000794 return;
795 }
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000796
Ted Kremenek9e2d98d2009-04-01 21:12:06 +0000797 // Add an extra edge when jumping between contexts.
798 while (1) {
799 if (const Stmt *PS = PrevLoc.asStmt())
800 if (const Stmt *NS = NewLoc.asStmt()) {
801 PathDiagnosticLocation X = PDB.getEnclosingStmtLocation(PS);
802 // FIXME: We need a version of getParent that ignores '()' and casts.
803 const Stmt *parentX = PDB.getParent(X.asStmt());
804
805 const PathDiagnosticLocation &Y = PDB.getEnclosingStmtLocation(NS);
806 // FIXME: We need a version of getParent that ignores '()' and casts.
807 const Stmt *parentY = PDB.getParent(Y.asStmt());
808
Ted Kremenek0ddaff32009-04-02 03:44:00 +0000809 if (parentX && IsControlFlowExpr(parentX)) {
810 if (parentX == parentY)
Ted Kremenek9e2d98d2009-04-01 21:12:06 +0000811 break;
Ted Kremenek9e2d98d2009-04-01 21:12:06 +0000812 else {
Ted Kremenek0ddaff32009-04-02 03:44:00 +0000813 if (const Stmt *grandparentX = PDB.getParent(parentX)) {
814 const PathDiagnosticLocation &W =
815 PDB.getEnclosingStmtLocation(grandparentX);
816
817 if (W != Y) X = W;
818 }
Ted Kremenek9e2d98d2009-04-01 21:12:06 +0000819 }
820 }
821
822 if (X != Y && PrevLoc.asLocation() != X.asLocation()) {
823 PD.push_front(new PathDiagnosticControlFlowPiece(X, PrevLoc));
824 PrevLoc = X;
825 }
826 }
827 break;
828 }
829
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000830 PD.push_front(new PathDiagnosticControlFlowPiece(NewLoc, PrevLoc));
Ted Kremenekc3f83ad2009-04-01 17:18:21 +0000831 PrevLoc = NewLoc;
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000832}
833
834static bool IsNestedDeclStmt(const Stmt *S, ParentMap &PM) {
835 const DeclStmt *DS = dyn_cast<DeclStmt>(S);
836
837 if (!DS)
838 return false;
839
840 const Stmt *Parent = PM.getParent(DS);
841 if (!Parent)
842 return false;
843
844 if (const ForStmt *FS = dyn_cast<ForStmt>(Parent))
845 return FS->getInit() == DS;
846
Ted Kremeneka42c4c92009-04-01 18:48:52 +0000847 // FIXME: In the future IfStmt/WhileStmt may contain DeclStmts in their
848 // condition.
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000849
850 return false;
851}
852
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000853static void GenerateExtensivePathDiagnostic(PathDiagnostic& PD,
854 PathDiagnosticBuilder &PDB,
855 const ExplodedNode<GRState> *N) {
856
857 SourceManager& SMgr = PDB.getSourceManager();
858 const ExplodedNode<GRState>* NextNode = N->pred_empty()
859 ? NULL : *(N->pred_begin());
860
861 PathDiagnosticLocation PrevLoc;
862
863 while (NextNode) {
864 N = NextNode;
865 NextNode = GetPredecessorNode(N);
866 ProgramPoint P = N->getLocation();
867
868 // Block edges.
869 if (const BlockEdge *BE = dyn_cast<BlockEdge>(&P)) {
870 const CFGBlock &Blk = *BE->getSrc();
Ted Kremenek51a735c2009-04-01 17:52:26 +0000871
872 // Add a special edge for the entrance into the function/method.
873 if (&Blk == &PDB.getCFG().getEntry()) {
874 FullSourceLoc L = FullSourceLoc(PDB.getCodeDecl().getLocation(), SMgr);
875 GenExtAddEdge(PD, PDB, L.getSpellingLoc(), PrevLoc);
876 continue;
877 }
878
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000879 if (const Stmt *Term = Blk.getTerminator()) {
Ted Kremeneka42c4c92009-04-01 18:48:52 +0000880 const Stmt *Cond = Blk.getTerminatorCondition();
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000881 if (!Cond || !IsControlFlowExpr(Cond)) {
Ted Kremeneka42c4c92009-04-01 18:48:52 +0000882 // For terminators that are control-flow expressions like '&&', '?',
883 // have the condition be the anchor point for the control-flow edge
884 // instead of the terminator.
885 const Stmt *X = isa<Expr>(Term) ? (Cond ? Cond : Term) : Term;
886 GenExtAddEdge(PD, PDB, PathDiagnosticLocation(X, SMgr), PrevLoc,true);
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000887 continue;
888 }
889 }
890
891 // Only handle blocks with more than 1 statement here, as the blocks
892 // with one statement are handled at BlockEntrances.
893 if (Blk.size() > 1) {
894 const Stmt *S = *Blk.rbegin();
895
896 // We don't add control-flow edges for DeclStmt's that appear in
897 // the condition of if/while/for or are control-flow merge expressions.
898 if (!IsControlFlowExpr(S) && !IsNestedDeclStmt(S, PDB.getParentMap())) {
899 GenExtAddEdge(PD, PDB, PathDiagnosticLocation(S, SMgr), PrevLoc);
900 }
901 }
902
903 continue;
904 }
905
906 if (const BlockEntrance *BE = dyn_cast<BlockEntrance>(&P)) {
907 if (const Stmt* S = BE->getFirstStmt()) {
908 if (!IsControlFlowExpr(S) && !IsNestedDeclStmt(S, PDB.getParentMap())) {
Ted Kremenekc3f83ad2009-04-01 17:18:21 +0000909 if (PrevLoc.isValid()) {
Ted Kremenek51a735c2009-04-01 17:52:26 +0000910 // Are we jumping within the same enclosing statement?
Ted Kremenekc3f83ad2009-04-01 17:18:21 +0000911 if (PDB.getEnclosingStmtLocation(S) ==
912 PDB.getEnclosingStmtLocation(PrevLoc))
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000913 continue;
914 }
915
916 GenExtAddEdge(PD, PDB, PDB.getEnclosingStmtLocation(S), PrevLoc);
917 }
918 }
919
920 continue;
921 }
922
923 PathDiagnosticPiece* p =
924 PDB.getReport().VisitNode(N, NextNode, PDB.getGraph(),
925 PDB.getBugReporter(), PDB.getNodeMapClosure());
926
927 if (p) {
Ted Kremeneka42c4c92009-04-01 18:48:52 +0000928 GenExtAddEdge(PD, PDB, p->getLocation(), PrevLoc, true);
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000929 PD.push_front(p);
930 }
931 }
932}
933
934//===----------------------------------------------------------------------===//
Ted Kremenekcf118d42009-02-04 23:49:09 +0000935// Methods for BugType and subclasses.
936//===----------------------------------------------------------------------===//
937BugType::~BugType() {}
938void BugType::FlushReports(BugReporter &BR) {}
Ted Kremenekbb77e9b2008-05-01 22:50:36 +0000939
Ted Kremenekcf118d42009-02-04 23:49:09 +0000940//===----------------------------------------------------------------------===//
941// Methods for BugReport and subclasses.
942//===----------------------------------------------------------------------===//
943BugReport::~BugReport() {}
944RangedBugReport::~RangedBugReport() {}
945
946Stmt* BugReport::getStmt(BugReporter& BR) const {
Ted Kremenek200ed922008-05-02 23:21:21 +0000947 ProgramPoint ProgP = EndNode->getLocation();
Ted Kremenekbd7efa82008-04-17 23:44:37 +0000948 Stmt *S = NULL;
949
Ted Kremenekcf118d42009-02-04 23:49:09 +0000950 if (BlockEntrance* BE = dyn_cast<BlockEntrance>(&ProgP)) {
Ted Kremenekb697b102009-02-23 22:44:26 +0000951 if (BE->getBlock() == &BR.getCFG()->getExit()) S = GetPreviousStmt(EndNode);
Ted Kremenekcf118d42009-02-04 23:49:09 +0000952 }
953 if (!S) S = GetStmt(ProgP);
954
Ted Kremenekbb77e9b2008-05-01 22:50:36 +0000955 return S;
956}
957
958PathDiagnosticPiece*
959BugReport::getEndPath(BugReporter& BR,
Ted Kremenek3148eb42009-01-24 00:55:43 +0000960 const ExplodedNode<GRState>* EndPathNode) {
Ted Kremenekbb77e9b2008-05-01 22:50:36 +0000961
962 Stmt* S = getStmt(BR);
Ted Kremenek61f3e052008-04-03 04:42:52 +0000963
964 if (!S)
965 return NULL;
966
Ted Kremenekc9fa2f72008-05-01 23:13:35 +0000967 FullSourceLoc L(S->getLocStart(), BR.getContext().getSourceManager());
Ted Kremenek1fbfd5b2009-03-06 23:58:11 +0000968 PathDiagnosticPiece* P = new PathDiagnosticEventPiece(L, getDescription());
Ted Kremenek61f3e052008-04-03 04:42:52 +0000969
Ted Kremenekde7161f2008-04-03 18:00:37 +0000970 const SourceRange *Beg, *End;
Ted Kremenekbb77e9b2008-05-01 22:50:36 +0000971 getRanges(BR, Beg, End);
Ted Kremenekcf118d42009-02-04 23:49:09 +0000972
Ted Kremenekbb77e9b2008-05-01 22:50:36 +0000973 for (; Beg != End; ++Beg)
974 P->addRange(*Beg);
Ted Kremenek61f3e052008-04-03 04:42:52 +0000975
976 return P;
977}
978
Ted Kremenekbb77e9b2008-05-01 22:50:36 +0000979void BugReport::getRanges(BugReporter& BR, const SourceRange*& beg,
980 const SourceRange*& end) {
981
982 if (Expr* E = dyn_cast_or_null<Expr>(getStmt(BR))) {
983 R = E->getSourceRange();
Ted Kremenek9b5e5052009-02-27 20:05:10 +0000984 assert(R.isValid());
Ted Kremenekbb77e9b2008-05-01 22:50:36 +0000985 beg = &R;
986 end = beg+1;
987 }
988 else
989 beg = end = 0;
Ted Kremenekf1ae7052008-04-03 17:57:38 +0000990}
991
Ted Kremenekcf118d42009-02-04 23:49:09 +0000992SourceLocation BugReport::getLocation() const {
993 if (EndNode)
Ted Kremenek9b5e5052009-02-27 20:05:10 +0000994 if (Stmt* S = GetCurrentOrPreviousStmt(EndNode)) {
995 // For member expressions, return the location of the '.' or '->'.
996 if (MemberExpr* ME = dyn_cast<MemberExpr>(S))
997 return ME->getMemberLoc();
998
Ted Kremenekcf118d42009-02-04 23:49:09 +0000999 return S->getLocStart();
Ted Kremenek9b5e5052009-02-27 20:05:10 +00001000 }
Ted Kremenekcf118d42009-02-04 23:49:09 +00001001
1002 return FullSourceLoc();
Ted Kremenekd2f642b2008-04-14 17:39:48 +00001003}
1004
Ted Kremenek3148eb42009-01-24 00:55:43 +00001005PathDiagnosticPiece* BugReport::VisitNode(const ExplodedNode<GRState>* N,
1006 const ExplodedNode<GRState>* PrevN,
1007 const ExplodedGraph<GRState>& G,
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001008 BugReporter& BR,
1009 NodeResolver &NR) {
Ted Kremenek50a6d0c2008-04-09 21:41:14 +00001010 return NULL;
1011}
1012
Ted Kremenekcf118d42009-02-04 23:49:09 +00001013//===----------------------------------------------------------------------===//
1014// Methods for BugReporter and subclasses.
1015//===----------------------------------------------------------------------===//
1016
1017BugReportEquivClass::~BugReportEquivClass() {
1018 for (iterator I=begin(), E=end(); I!=E; ++I) delete *I;
1019}
1020
1021GRBugReporter::~GRBugReporter() { FlushReports(); }
1022BugReporterData::~BugReporterData() {}
1023
1024ExplodedGraph<GRState>&
1025GRBugReporter::getGraph() { return Eng.getGraph(); }
1026
1027GRStateManager&
1028GRBugReporter::getStateManager() { return Eng.getStateManager(); }
1029
1030BugReporter::~BugReporter() { FlushReports(); }
1031
1032void BugReporter::FlushReports() {
1033 if (BugTypes.isEmpty())
1034 return;
1035
1036 // First flush the warnings for each BugType. This may end up creating new
1037 // warnings and new BugTypes. Because ImmutableSet is a functional data
1038 // structure, we do not need to worry about the iterators being invalidated.
1039 for (BugTypesTy::iterator I=BugTypes.begin(), E=BugTypes.end(); I!=E; ++I)
1040 const_cast<BugType*>(*I)->FlushReports(*this);
1041
1042 // Iterate through BugTypes a second time. BugTypes may have been updated
1043 // with new BugType objects and new warnings.
1044 for (BugTypesTy::iterator I=BugTypes.begin(), E=BugTypes.end(); I!=E; ++I) {
1045 BugType *BT = const_cast<BugType*>(*I);
1046
1047 typedef llvm::FoldingSet<BugReportEquivClass> SetTy;
1048 SetTy& EQClasses = BT->EQClasses;
1049
1050 for (SetTy::iterator EI=EQClasses.begin(), EE=EQClasses.end(); EI!=EE;++EI){
1051 BugReportEquivClass& EQ = *EI;
1052 FlushReport(EQ);
1053 }
Ted Kremeneka43a1eb2008-04-23 23:02:12 +00001054
Ted Kremenekcf118d42009-02-04 23:49:09 +00001055 // Delete the BugType object. This will also delete the equivalence
1056 // classes.
1057 delete BT;
Ted Kremenek94826a72008-04-03 04:59:14 +00001058 }
Ted Kremenekcf118d42009-02-04 23:49:09 +00001059
1060 // Remove all references to the BugType objects.
1061 BugTypes = F.GetEmptySet();
1062}
1063
1064//===----------------------------------------------------------------------===//
1065// PathDiagnostics generation.
1066//===----------------------------------------------------------------------===//
1067
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001068static std::pair<std::pair<ExplodedGraph<GRState>*, NodeBackMap*>,
Ted Kremenekcf118d42009-02-04 23:49:09 +00001069 std::pair<ExplodedNode<GRState>*, unsigned> >
1070MakeReportGraph(const ExplodedGraph<GRState>* G,
1071 const ExplodedNode<GRState>** NStart,
1072 const ExplodedNode<GRState>** NEnd) {
Ted Kremenek94826a72008-04-03 04:59:14 +00001073
Ted Kremenekcf118d42009-02-04 23:49:09 +00001074 // Create the trimmed graph. It will contain the shortest paths from the
1075 // error nodes to the root. In the new graph we should only have one
1076 // error node unless there are two or more error nodes with the same minimum
1077 // path length.
1078 ExplodedGraph<GRState>* GTrim;
1079 InterExplodedGraphMap<GRState>* NMap;
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001080
1081 llvm::DenseMap<const void*, const void*> InverseMap;
1082 llvm::tie(GTrim, NMap) = G->Trim(NStart, NEnd, &InverseMap);
Ted Kremenekcf118d42009-02-04 23:49:09 +00001083
1084 // Create owning pointers for GTrim and NMap just to ensure that they are
1085 // released when this function exists.
1086 llvm::OwningPtr<ExplodedGraph<GRState> > AutoReleaseGTrim(GTrim);
1087 llvm::OwningPtr<InterExplodedGraphMap<GRState> > AutoReleaseNMap(NMap);
1088
1089 // Find the (first) error node in the trimmed graph. We just need to consult
1090 // the node map (NMap) which maps from nodes in the original graph to nodes
1091 // in the new graph.
1092 const ExplodedNode<GRState>* N = 0;
1093 unsigned NodeIndex = 0;
1094
1095 for (const ExplodedNode<GRState>** I = NStart; I != NEnd; ++I)
1096 if ((N = NMap->getMappedNode(*I))) {
1097 NodeIndex = (I - NStart) / sizeof(*I);
1098 break;
1099 }
1100
1101 assert(N && "No error node found in the trimmed graph.");
1102
1103 // Create a new (third!) graph with a single path. This is the graph
1104 // that will be returned to the caller.
Ted Kremenek3148eb42009-01-24 00:55:43 +00001105 ExplodedGraph<GRState> *GNew =
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001106 new ExplodedGraph<GRState>(GTrim->getCFG(), GTrim->getCodeDecl(),
1107 GTrim->getContext());
Ted Kremenekcf118d42009-02-04 23:49:09 +00001108
Ted Kremenek10aa5542009-03-12 23:41:59 +00001109 // Sometimes the trimmed graph can contain a cycle. Perform a reverse BFS
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001110 // to the root node, and then construct a new graph that contains only
1111 // a single path.
Ted Kremenek3148eb42009-01-24 00:55:43 +00001112 llvm::DenseMap<const void*,unsigned> Visited;
Ted Kremenek10aa5542009-03-12 23:41:59 +00001113 std::queue<const ExplodedNode<GRState>*> WS;
1114 WS.push(N);
1115
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001116 unsigned cnt = 0;
Ted Kremenek3148eb42009-01-24 00:55:43 +00001117 const ExplodedNode<GRState>* Root = 0;
Ted Kremenekc1da4412008-06-17 19:14:06 +00001118
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001119 while (!WS.empty()) {
Ted Kremenek10aa5542009-03-12 23:41:59 +00001120 const ExplodedNode<GRState>* Node = WS.front();
1121 WS.pop();
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001122
1123 if (Visited.find(Node) != Visited.end())
1124 continue;
1125
1126 Visited[Node] = cnt++;
1127
1128 if (Node->pred_empty()) {
1129 Root = Node;
1130 break;
1131 }
1132
Ted Kremenek3148eb42009-01-24 00:55:43 +00001133 for (ExplodedNode<GRState>::const_pred_iterator I=Node->pred_begin(),
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001134 E=Node->pred_end(); I!=E; ++I)
Ted Kremenek10aa5542009-03-12 23:41:59 +00001135 WS.push(*I);
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001136 }
Ted Kremenekcf118d42009-02-04 23:49:09 +00001137
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001138 assert (Root);
1139
Ted Kremenek10aa5542009-03-12 23:41:59 +00001140 // Now walk from the root down the BFS path, always taking the successor
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001141 // with the lowest number.
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001142 ExplodedNode<GRState> *Last = 0, *First = 0;
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001143 NodeBackMap *BM = new NodeBackMap();
Ted Kremenekcf118d42009-02-04 23:49:09 +00001144
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001145 for ( N = Root ;;) {
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001146 // Lookup the number associated with the current node.
Ted Kremenek3148eb42009-01-24 00:55:43 +00001147 llvm::DenseMap<const void*,unsigned>::iterator I = Visited.find(N);
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001148 assert (I != Visited.end());
1149
1150 // Create the equivalent node in the new graph with the same state
1151 // and location.
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001152 ExplodedNode<GRState>* NewN =
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001153 GNew->getNode(N->getLocation(), N->getState());
1154
1155 // Store the mapping to the original node.
1156 llvm::DenseMap<const void*, const void*>::iterator IMitr=InverseMap.find(N);
1157 assert(IMitr != InverseMap.end() && "No mapping to original node.");
1158 (*BM)[NewN] = (const ExplodedNode<GRState>*) IMitr->second;
Ted Kremenekcf118d42009-02-04 23:49:09 +00001159
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001160 // Link up the new node with the previous node.
1161 if (Last)
1162 NewN->addPredecessor(Last);
Ted Kremeneka43a1eb2008-04-23 23:02:12 +00001163
1164 Last = NewN;
Ted Kremenekcf118d42009-02-04 23:49:09 +00001165
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001166 // Are we at the final node?
1167 if (I->second == 0) {
1168 First = NewN;
Ted Kremenekc1da4412008-06-17 19:14:06 +00001169 break;
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001170 }
Ted Kremenekcf118d42009-02-04 23:49:09 +00001171
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001172 // Find the next successor node. We choose the node that is marked
1173 // with the lowest DFS number.
Ted Kremenek3148eb42009-01-24 00:55:43 +00001174 ExplodedNode<GRState>::const_succ_iterator SI = N->succ_begin();
1175 ExplodedNode<GRState>::const_succ_iterator SE = N->succ_end();
Ted Kremenekc1da4412008-06-17 19:14:06 +00001176 N = 0;
1177
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001178 for (unsigned MinVal = 0; SI != SE; ++SI) {
Ted Kremenekcf118d42009-02-04 23:49:09 +00001179
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001180 I = Visited.find(*SI);
1181
1182 if (I == Visited.end())
1183 continue;
1184
1185 if (!N || I->second < MinVal) {
1186 N = *SI;
1187 MinVal = I->second;
Ted Kremenekc1da4412008-06-17 19:14:06 +00001188 }
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001189 }
Ted Kremenekcf118d42009-02-04 23:49:09 +00001190
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001191 assert (N);
Ted Kremeneka43a1eb2008-04-23 23:02:12 +00001192 }
Ted Kremenekcf118d42009-02-04 23:49:09 +00001193
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001194 assert (First);
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001195 return std::make_pair(std::make_pair(GNew, BM),
1196 std::make_pair(First, NodeIndex));
Ted Kremeneka43a1eb2008-04-23 23:02:12 +00001197}
1198
Ted Kremenek0e5c8d42009-03-10 05:16:17 +00001199/// CompactPathDiagnostic - This function postprocesses a PathDiagnostic object
1200/// and collapses PathDiagosticPieces that are expanded by macros.
1201static void CompactPathDiagnostic(PathDiagnostic &PD, const SourceManager& SM) {
1202 typedef std::vector<std::pair<PathDiagnosticMacroPiece*, SourceLocation> >
1203 MacroStackTy;
1204
1205 typedef std::vector<PathDiagnosticPiece*>
1206 PiecesTy;
1207
1208 MacroStackTy MacroStack;
1209 PiecesTy Pieces;
1210
1211 for (PathDiagnostic::iterator I = PD.begin(), E = PD.end(); I!=E; ++I) {
1212 // Get the location of the PathDiagnosticPiece.
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +00001213 const FullSourceLoc Loc = I->getLocation().asLocation();
Ted Kremenek0e5c8d42009-03-10 05:16:17 +00001214
1215 // Determine the instantiation location, which is the location we group
1216 // related PathDiagnosticPieces.
1217 SourceLocation InstantiationLoc = Loc.isMacroID() ?
1218 SM.getInstantiationLoc(Loc) :
1219 SourceLocation();
1220
1221 if (Loc.isFileID()) {
1222 MacroStack.clear();
1223 Pieces.push_back(&*I);
1224 continue;
1225 }
1226
1227 assert(Loc.isMacroID());
1228
1229 // Is the PathDiagnosticPiece within the same macro group?
1230 if (!MacroStack.empty() && InstantiationLoc == MacroStack.back().second) {
1231 MacroStack.back().first->push_back(&*I);
1232 continue;
1233 }
1234
1235 // We aren't in the same group. Are we descending into a new macro
1236 // or are part of an old one?
1237 PathDiagnosticMacroPiece *MacroGroup = 0;
1238
1239 SourceLocation ParentInstantiationLoc = InstantiationLoc.isMacroID() ?
1240 SM.getInstantiationLoc(Loc) :
1241 SourceLocation();
1242
1243 // Walk the entire macro stack.
1244 while (!MacroStack.empty()) {
1245 if (InstantiationLoc == MacroStack.back().second) {
1246 MacroGroup = MacroStack.back().first;
1247 break;
1248 }
1249
1250 if (ParentInstantiationLoc == MacroStack.back().second) {
1251 MacroGroup = MacroStack.back().first;
1252 break;
1253 }
1254
1255 MacroStack.pop_back();
1256 }
1257
1258 if (!MacroGroup || ParentInstantiationLoc == MacroStack.back().second) {
1259 // Create a new macro group and add it to the stack.
1260 PathDiagnosticMacroPiece *NewGroup = new PathDiagnosticMacroPiece(Loc);
1261
1262 if (MacroGroup)
1263 MacroGroup->push_back(NewGroup);
1264 else {
1265 assert(InstantiationLoc.isFileID());
1266 Pieces.push_back(NewGroup);
1267 }
1268
1269 MacroGroup = NewGroup;
1270 MacroStack.push_back(std::make_pair(MacroGroup, InstantiationLoc));
1271 }
1272
1273 // Finally, add the PathDiagnosticPiece to the group.
1274 MacroGroup->push_back(&*I);
1275 }
1276
1277 // Now take the pieces and construct a new PathDiagnostic.
1278 PD.resetPath(false);
1279
1280 for (PiecesTy::iterator I=Pieces.begin(), E=Pieces.end(); I!=E; ++I) {
1281 if (PathDiagnosticMacroPiece *MP=dyn_cast<PathDiagnosticMacroPiece>(*I))
1282 if (!MP->containsEvent()) {
1283 delete MP;
1284 continue;
1285 }
1286
1287 PD.push_back(*I);
1288 }
1289}
1290
Ted Kremenek7dc86642009-03-31 20:22:36 +00001291void GRBugReporter::GeneratePathDiagnostic(PathDiagnostic& PD,
1292 BugReportEquivClass& EQ) {
1293
1294 std::vector<const ExplodedNode<GRState>*> Nodes;
1295
Ted Kremenekcf118d42009-02-04 23:49:09 +00001296 for (BugReportEquivClass::iterator I=EQ.begin(), E=EQ.end(); I!=E; ++I) {
1297 const ExplodedNode<GRState>* N = I->getEndNode();
1298 if (N) Nodes.push_back(N);
1299 }
1300
1301 if (Nodes.empty())
1302 return;
Ted Kremeneka43a1eb2008-04-23 23:02:12 +00001303
1304 // Construct a new graph that contains only a single path from the error
Ted Kremenekcf118d42009-02-04 23:49:09 +00001305 // node to a root.
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001306 const std::pair<std::pair<ExplodedGraph<GRState>*, NodeBackMap*>,
Ted Kremenek7dc86642009-03-31 20:22:36 +00001307 std::pair<ExplodedNode<GRState>*, unsigned> >&
1308 GPair = MakeReportGraph(&getGraph(), &Nodes[0], &Nodes[0] + Nodes.size());
Ted Kremeneka43a1eb2008-04-23 23:02:12 +00001309
Ted Kremenekcf118d42009-02-04 23:49:09 +00001310 // Find the BugReport with the original location.
1311 BugReport *R = 0;
1312 unsigned i = 0;
1313 for (BugReportEquivClass::iterator I=EQ.begin(), E=EQ.end(); I!=E; ++I, ++i)
1314 if (i == GPair.second.second) { R = *I; break; }
1315
1316 assert(R && "No original report found for sliced graph.");
Ted Kremeneka43a1eb2008-04-23 23:02:12 +00001317
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001318 llvm::OwningPtr<ExplodedGraph<GRState> > ReportGraph(GPair.first.first);
1319 llvm::OwningPtr<NodeBackMap> BackMap(GPair.first.second);
Ted Kremenekcf118d42009-02-04 23:49:09 +00001320 const ExplodedNode<GRState> *N = GPair.second.first;
Ted Kremenek7dc86642009-03-31 20:22:36 +00001321
Ted Kremenekcf118d42009-02-04 23:49:09 +00001322 // Start building the path diagnostic...
1323 if (PathDiagnosticPiece* Piece = R->getEndPath(*this, N))
Ted Kremenekbd7efa82008-04-17 23:44:37 +00001324 PD.push_back(Piece);
1325 else
1326 return;
Ted Kremenek7dc86642009-03-31 20:22:36 +00001327
1328 PathDiagnosticBuilder PDB(*this, ReportGraph.get(), R, BackMap.get(),
1329 getStateManager().getCodeDecl(),
Ted Kremenekbabdd7b2009-03-27 05:06:10 +00001330 getPathDiagnosticClient());
Ted Kremenekbd7efa82008-04-17 23:44:37 +00001331
Ted Kremenek7dc86642009-03-31 20:22:36 +00001332 switch (PDB.getGenerationScheme()) {
1333 case PathDiagnosticClient::Extensive:
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +00001334 GenerateExtensivePathDiagnostic(PD,PDB, N);
1335 break;
Ted Kremenek7dc86642009-03-31 20:22:36 +00001336 case PathDiagnosticClient::Minimal:
1337 GenerateMinimalPathDiagnostic(PD, PDB, N);
1338 break;
1339 }
1340
1341 // After constructing the full PathDiagnostic, do a pass over it to compact
1342 // PathDiagnosticPieces that occur within a macro.
1343 CompactPathDiagnostic(PD, PDB.getSourceManager());
1344}
1345
Ted Kremenekcf118d42009-02-04 23:49:09 +00001346void BugReporter::Register(BugType *BT) {
1347 BugTypes = F.Add(BugTypes, BT);
Ted Kremenek76d90c82008-05-16 18:33:14 +00001348}
1349
Ted Kremenekcf118d42009-02-04 23:49:09 +00001350void BugReporter::EmitReport(BugReport* R) {
1351 // Compute the bug report's hash to determine its equivalence class.
1352 llvm::FoldingSetNodeID ID;
1353 R->Profile(ID);
Ted Kremenek61f3e052008-04-03 04:42:52 +00001354
Ted Kremenekcf118d42009-02-04 23:49:09 +00001355 // Lookup the equivance class. If there isn't one, create it.
1356 BugType& BT = R->getBugType();
1357 Register(&BT);
1358 void *InsertPos;
1359 BugReportEquivClass* EQ = BT.EQClasses.FindNodeOrInsertPos(ID, InsertPos);
1360
1361 if (!EQ) {
1362 EQ = new BugReportEquivClass(R);
1363 BT.EQClasses.InsertNode(EQ, InsertPos);
1364 }
1365 else
1366 EQ->AddReport(R);
Ted Kremenek61f3e052008-04-03 04:42:52 +00001367}
1368
Ted Kremenekcf118d42009-02-04 23:49:09 +00001369void BugReporter::FlushReport(BugReportEquivClass& EQ) {
1370 assert(!EQ.Reports.empty());
1371 BugReport &R = **EQ.begin();
1372
1373 // FIXME: Make sure we use the 'R' for the path that was actually used.
1374 // Probably doesn't make a difference in practice.
1375 BugType& BT = R.getBugType();
1376
1377 llvm::OwningPtr<PathDiagnostic> D(new PathDiagnostic(R.getBugType().getName(),
1378 R.getDescription(),
1379 BT.getCategory()));
1380 GeneratePathDiagnostic(*D.get(), EQ);
Ted Kremenek072192b2008-04-30 23:47:44 +00001381
1382 // Get the meta data.
Ted Kremenek072192b2008-04-30 23:47:44 +00001383 std::pair<const char**, const char**> Meta = R.getExtraDescriptiveText();
Ted Kremenek3148eb42009-01-24 00:55:43 +00001384 for (const char** s = Meta.first; s != Meta.second; ++s) D->addMeta(*s);
Ted Kremenek75840e12008-04-18 01:56:37 +00001385
Ted Kremenek3148eb42009-01-24 00:55:43 +00001386 // Emit a summary diagnostic to the regular Diagnostics engine.
Ted Kremenekc0959972008-07-02 21:24:01 +00001387 PathDiagnosticClient* PD = getPathDiagnosticClient();
Ted Kremenek3148eb42009-01-24 00:55:43 +00001388 const SourceRange *Beg = 0, *End = 0;
1389 R.getRanges(*this, Beg, End);
1390 Diagnostic& Diag = getDiagnostic();
Ted Kremenekcf118d42009-02-04 23:49:09 +00001391 FullSourceLoc L(R.getLocation(), getSourceManager());
Ted Kremenekd90e7082009-02-07 22:36:41 +00001392 unsigned ErrorDiag = Diag.getCustomDiagID(Diagnostic::Warning,
1393 R.getDescription().c_str());
Ted Kremenek57202072008-07-14 17:40:50 +00001394
Ted Kremenek3148eb42009-01-24 00:55:43 +00001395 switch (End-Beg) {
Chris Lattner0a14eee2008-11-18 07:04:44 +00001396 default: assert(0 && "Don't handle this many ranges yet!");
1397 case 0: Diag.Report(L, ErrorDiag); break;
1398 case 1: Diag.Report(L, ErrorDiag) << Beg[0]; break;
1399 case 2: Diag.Report(L, ErrorDiag) << Beg[0] << Beg[1]; break;
1400 case 3: Diag.Report(L, ErrorDiag) << Beg[0] << Beg[1] << Beg[2]; break;
Ted Kremenek2f0e89e2008-04-18 22:56:53 +00001401 }
Ted Kremenek3148eb42009-01-24 00:55:43 +00001402
1403 // Emit a full diagnostic for the path if we have a PathDiagnosticClient.
1404 if (!PD)
1405 return;
1406
1407 if (D->empty()) {
Ted Kremenek1fbfd5b2009-03-06 23:58:11 +00001408 PathDiagnosticPiece* piece =
1409 new PathDiagnosticEventPiece(L, R.getDescription());
1410
Ted Kremenek3148eb42009-01-24 00:55:43 +00001411 for ( ; Beg != End; ++Beg) piece->addRange(*Beg);
1412 D->push_back(piece);
1413 }
1414
1415 PD->HandlePathDiagnostic(D.take());
Ted Kremenek61f3e052008-04-03 04:42:52 +00001416}
Ted Kremenek57202072008-07-14 17:40:50 +00001417
Ted Kremenek8c036c72008-09-20 04:23:38 +00001418void BugReporter::EmitBasicReport(const char* name, const char* str,
1419 SourceLocation Loc,
1420 SourceRange* RBeg, unsigned NumRanges) {
1421 EmitBasicReport(name, "", str, Loc, RBeg, NumRanges);
1422}
Ted Kremenekcf118d42009-02-04 23:49:09 +00001423
Ted Kremenek8c036c72008-09-20 04:23:38 +00001424void BugReporter::EmitBasicReport(const char* name, const char* category,
1425 const char* str, SourceLocation Loc,
1426 SourceRange* RBeg, unsigned NumRanges) {
1427
Ted Kremenekcf118d42009-02-04 23:49:09 +00001428 // 'BT' will be owned by BugReporter as soon as we call 'EmitReport'.
1429 BugType *BT = new BugType(name, category);
Chris Lattner0a14eee2008-11-18 07:04:44 +00001430 FullSourceLoc L = getContext().getFullLoc(Loc);
Ted Kremenekcf118d42009-02-04 23:49:09 +00001431 RangedBugReport *R = new DiagBugReport(*BT, str, L);
1432 for ( ; NumRanges > 0 ; --NumRanges, ++RBeg) R->addRange(*RBeg);
1433 EmitReport(R);
Ted Kremenek57202072008-07-14 17:40:50 +00001434}