blob: af4fd384e85ef049b7601f5d1ca26d06a6b949b4 [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
Ted Kremenek6c07bdb2009-06-26 00:05:51 +000011// PathDiagnostics.
Ted Kremenek61f3e052008-04-03 04:42:52 +000012//
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/AST/ASTContext.h"
Ted Kremeneke41611a2009-07-16 18:13:04 +000018#include "clang/Analysis/CFG.h"
Ted Kremenek61f3e052008-04-03 04:42:52 +000019#include "clang/AST/Expr.h"
Ted Kremenek00605e02009-03-27 20:55:39 +000020#include "clang/AST/ParentMap.h"
Chris Lattner16f00492009-04-26 01:32:48 +000021#include "clang/AST/StmtObjC.h"
22#include "clang/Basic/SourceManager.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 Kremenek8966bc12009-05-06 21:39:49 +000033BugReporterVisitor::~BugReporterVisitor() {}
34BugReporterContext::~BugReporterContext() {
35 for (visitor_iterator I = visitor_begin(), E = visitor_end(); I != E; ++I)
36 if ((*I)->isOwnedByReporterContext()) delete *I;
37}
38
Ted Kremenekcf118d42009-02-04 23:49:09 +000039//===----------------------------------------------------------------------===//
Ted Kremenek31061982009-03-31 23:00:32 +000040// Helper routines for walking the ExplodedGraph and fetching statements.
Ted Kremenekcf118d42009-02-04 23:49:09 +000041//===----------------------------------------------------------------------===//
Ted Kremenek61f3e052008-04-03 04:42:52 +000042
Ted Kremenek5f85e172009-07-22 22:35:28 +000043static inline const Stmt* GetStmt(ProgramPoint P) {
Ted Kremenekb697b102009-02-23 22:44:26 +000044 if (const PostStmt* PS = dyn_cast<PostStmt>(&P))
Ted Kremenek61f3e052008-04-03 04:42:52 +000045 return PS->getStmt();
Ted Kremenekb697b102009-02-23 22:44:26 +000046 else if (const BlockEdge* BE = dyn_cast<BlockEdge>(&P))
Ted Kremenek61f3e052008-04-03 04:42:52 +000047 return BE->getSrc()->getTerminator();
Ted Kremenek61f3e052008-04-03 04:42:52 +000048
Ted Kremenekb697b102009-02-23 22:44:26 +000049 return 0;
Ted Kremenek706e3cf2008-04-07 23:35:17 +000050}
51
Zhongxing Xuc5619d92009-08-06 01:32:16 +000052static inline const ExplodedNode*
53GetPredecessorNode(const ExplodedNode* N) {
Ted Kremenekbd7efa82008-04-17 23:44:37 +000054 return N->pred_empty() ? NULL : *(N->pred_begin());
55}
Ted Kremenek2673c9f2008-04-25 19:01:27 +000056
Zhongxing Xuc5619d92009-08-06 01:32:16 +000057static inline const ExplodedNode*
58GetSuccessorNode(const ExplodedNode* N) {
Ted Kremenekb697b102009-02-23 22:44:26 +000059 return N->succ_empty() ? NULL : *(N->succ_begin());
Ted Kremenekbd7efa82008-04-17 23:44:37 +000060}
61
Zhongxing Xuc5619d92009-08-06 01:32:16 +000062static const Stmt* GetPreviousStmt(const ExplodedNode* N) {
Ted Kremenekb697b102009-02-23 22:44:26 +000063 for (N = GetPredecessorNode(N); N; N = GetPredecessorNode(N))
Ted Kremenek5f85e172009-07-22 22:35:28 +000064 if (const Stmt *S = GetStmt(N->getLocation()))
Ted Kremenekb697b102009-02-23 22:44:26 +000065 return S;
66
67 return 0;
Ted Kremenek3148eb42009-01-24 00:55:43 +000068}
69
Zhongxing Xuc5619d92009-08-06 01:32:16 +000070static const Stmt* GetNextStmt(const ExplodedNode* N) {
Ted Kremenekb697b102009-02-23 22:44:26 +000071 for (N = GetSuccessorNode(N); N; N = GetSuccessorNode(N))
Ted Kremenek5f85e172009-07-22 22:35:28 +000072 if (const Stmt *S = GetStmt(N->getLocation())) {
Ted Kremenekf5ab8e62009-03-28 17:33:57 +000073 // Check if the statement is '?' or '&&'/'||'. These are "merges",
74 // not actual statement points.
75 switch (S->getStmtClass()) {
76 case Stmt::ChooseExprClass:
77 case Stmt::ConditionalOperatorClass: continue;
78 case Stmt::BinaryOperatorClass: {
79 BinaryOperator::Opcode Op = cast<BinaryOperator>(S)->getOpcode();
80 if (Op == BinaryOperator::LAnd || Op == BinaryOperator::LOr)
81 continue;
82 break;
83 }
84 default:
85 break;
86 }
Ted Kremenekb7c51522009-07-28 00:07:15 +000087
88 // Some expressions don't have locations.
89 if (S->getLocStart().isInvalid())
90 continue;
91
Ted Kremenekb697b102009-02-23 22:44:26 +000092 return S;
Ted Kremenekf5ab8e62009-03-28 17:33:57 +000093 }
Ted Kremenekb697b102009-02-23 22:44:26 +000094
95 return 0;
96}
97
Ted Kremenek5f85e172009-07-22 22:35:28 +000098static inline const Stmt*
Zhongxing Xuc5619d92009-08-06 01:32:16 +000099GetCurrentOrPreviousStmt(const ExplodedNode* N) {
Ted Kremenek5f85e172009-07-22 22:35:28 +0000100 if (const Stmt *S = GetStmt(N->getLocation()))
Ted Kremenekb697b102009-02-23 22:44:26 +0000101 return S;
102
103 return GetPreviousStmt(N);
104}
105
Ted Kremenek5f85e172009-07-22 22:35:28 +0000106static inline const Stmt*
Zhongxing Xuc5619d92009-08-06 01:32:16 +0000107GetCurrentOrNextStmt(const ExplodedNode* N) {
Ted Kremenek5f85e172009-07-22 22:35:28 +0000108 if (const Stmt *S = GetStmt(N->getLocation()))
Ted Kremenekb697b102009-02-23 22:44:26 +0000109 return S;
110
111 return GetNextStmt(N);
112}
113
114//===----------------------------------------------------------------------===//
Ted Kremenek31061982009-03-31 23:00:32 +0000115// PathDiagnosticBuilder and its associated routines and helper objects.
Ted Kremenekb697b102009-02-23 22:44:26 +0000116//===----------------------------------------------------------------------===//
Ted Kremenekb479dad2009-02-23 23:13:51 +0000117
Zhongxing Xuc5619d92009-08-06 01:32:16 +0000118typedef llvm::DenseMap<const ExplodedNode*,
119const ExplodedNode*> NodeBackMap;
Ted Kremenek7dc86642009-03-31 20:22:36 +0000120
Ted Kremenekbabdd7b2009-03-27 05:06:10 +0000121namespace {
Ted Kremenek7dc86642009-03-31 20:22:36 +0000122class VISIBILITY_HIDDEN NodeMapClosure : public BugReport::NodeResolver {
123 NodeBackMap& M;
124public:
125 NodeMapClosure(NodeBackMap *m) : M(*m) {}
126 ~NodeMapClosure() {}
127
Zhongxing Xuc5619d92009-08-06 01:32:16 +0000128 const ExplodedNode* getOriginalNode(const ExplodedNode* N) {
Ted Kremenek7dc86642009-03-31 20:22:36 +0000129 NodeBackMap::iterator I = M.find(N);
130 return I == M.end() ? 0 : I->second;
131 }
132};
133
Ted Kremenek8966bc12009-05-06 21:39:49 +0000134class VISIBILITY_HIDDEN PathDiagnosticBuilder : public BugReporterContext {
Ted Kremenek7dc86642009-03-31 20:22:36 +0000135 BugReport *R;
Ted Kremenekbabdd7b2009-03-27 05:06:10 +0000136 PathDiagnosticClient *PDC;
Ted Kremenek00605e02009-03-27 20:55:39 +0000137 llvm::OwningPtr<ParentMap> PM;
Ted Kremenek7dc86642009-03-31 20:22:36 +0000138 NodeMapClosure NMC;
Ted Kremenekbabdd7b2009-03-27 05:06:10 +0000139public:
Ted Kremenek8966bc12009-05-06 21:39:49 +0000140 PathDiagnosticBuilder(GRBugReporter &br,
Ted Kremenek7dc86642009-03-31 20:22:36 +0000141 BugReport *r, NodeBackMap *Backmap,
Ted Kremenek8966bc12009-05-06 21:39:49 +0000142 PathDiagnosticClient *pdc)
143 : BugReporterContext(br),
144 R(r), PDC(pdc), NMC(Backmap)
145 {
146 addVisitor(R);
147 }
Ted Kremenekbabdd7b2009-03-27 05:06:10 +0000148
Zhongxing Xuc5619d92009-08-06 01:32:16 +0000149 PathDiagnosticLocation ExecutionContinues(const ExplodedNode* N);
Ted Kremenekbabdd7b2009-03-27 05:06:10 +0000150
Ted Kremenek00605e02009-03-27 20:55:39 +0000151 PathDiagnosticLocation ExecutionContinues(llvm::raw_string_ostream& os,
Zhongxing Xuc5619d92009-08-06 01:32:16 +0000152 const ExplodedNode* N);
Ted Kremenek00605e02009-03-27 20:55:39 +0000153
154 ParentMap& getParentMap() {
Ted Kremenek8966bc12009-05-06 21:39:49 +0000155 if (PM.get() == 0)
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +0000156 PM.reset(new ParentMap(getCodeDecl().getBody()));
Ted Kremenek00605e02009-03-27 20:55:39 +0000157 return *PM.get();
158 }
Ted Kremenekbabdd7b2009-03-27 05:06:10 +0000159
Ted Kremenekc3f83ad2009-04-01 17:18:21 +0000160 const Stmt *getParent(const Stmt *S) {
161 return getParentMap().getParent(S);
162 }
Ted Kremenek8966bc12009-05-06 21:39:49 +0000163
164 virtual NodeMapClosure& getNodeResolver() { return NMC; }
Ted Kremenek7dc86642009-03-31 20:22:36 +0000165 BugReport& getReport() { return *R; }
Douglas Gregor72971342009-04-18 00:02:19 +0000166
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
Zhongxing Xuc5619d92009-08-06 01:32:16 +0000188PathDiagnosticBuilder::ExecutionContinues(const ExplodedNode* N) {
Ted Kremenek5f85e172009-07-22 22:35:28 +0000189 if (const Stmt *S = GetNextStmt(N))
Ted Kremenek8966bc12009-05-06 21:39:49 +0000190 return PathDiagnosticLocation(S, getSourceManager());
Ted Kremenek00605e02009-03-27 20:55:39 +0000191
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +0000192 return FullSourceLoc(getCodeDecl().getBodyRBrace(), getSourceManager());
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,
Zhongxing Xuc5619d92009-08-06 01:32:16 +0000197 const ExplodedNode* N) {
Ted Kremenekbabdd7b2009-03-27 05:06:10 +0000198
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 Kremenek8966bc12009-05-06 21:39:49 +0000207 << getSourceManager().getInstantiationLineNumber(Loc.asLocation())
208 << '.';
Ted Kremenekb697b102009-02-23 22:44:26 +0000209 else
Ted Kremenekb479dad2009-02-23 23:13:51 +0000210 os << "Execution jumps to the end of the "
Ted Kremenek8966bc12009-05-06 21:39:49 +0000211 << (isa<ObjCMethodDecl>(getCodeDecl()) ? "method" : "function") << '.';
Ted Kremenek082cb8d2009-03-12 18:41:53 +0000212
213 return Loc;
Ted Kremenek143ca222008-05-06 18:11:09 +0000214}
215
Ted Kremenekddb7bab2009-05-15 01:50:15 +0000216static bool IsNested(const Stmt *S, ParentMap &PM) {
217 if (isa<Expr>(S) && PM.isConsumedExpr(cast<Expr>(S)))
218 return true;
219
220 const Stmt *Parent = PM.getParentIgnoreParens(S);
221
222 if (Parent)
223 switch (Parent->getStmtClass()) {
224 case Stmt::ForStmtClass:
225 case Stmt::DoStmtClass:
226 case Stmt::WhileStmtClass:
227 return true;
228 default:
229 break;
230 }
231
232 return false;
233}
234
Ted Kremenekd8c938b2009-03-27 21:16:25 +0000235PathDiagnosticLocation
236PathDiagnosticBuilder::getEnclosingStmtLocation(const Stmt *S) {
237 assert(S && "Null Stmt* passed to getEnclosingStmtLocation");
Ted Kremenekc42e07e2009-05-05 22:19:17 +0000238 ParentMap &P = getParentMap();
Ted Kremenek8966bc12009-05-06 21:39:49 +0000239 SourceManager &SMgr = getSourceManager();
Ted Kremeneke88a1702009-05-11 22:19:32 +0000240
Ted Kremenekddb7bab2009-05-15 01:50:15 +0000241 while (IsNested(S, P)) {
Ted Kremenek8c8b0ad2009-05-11 19:50:47 +0000242 const Stmt *Parent = P.getParentIgnoreParens(S);
Ted Kremenekd8c938b2009-03-27 21:16:25 +0000243
Ted Kremenekaf3e3d52009-03-28 03:37:59 +0000244 if (!Parent)
245 break;
Ted Kremenekd8c938b2009-03-27 21:16:25 +0000246
Ted Kremenekaf3e3d52009-03-28 03:37:59 +0000247 switch (Parent->getStmtClass()) {
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000248 case Stmt::BinaryOperatorClass: {
249 const BinaryOperator *B = cast<BinaryOperator>(Parent);
250 if (B->isLogicalOp())
251 return PathDiagnosticLocation(S, SMgr);
252 break;
Ted Kremenek8c8b0ad2009-05-11 19:50:47 +0000253 }
Ted Kremenekaf3e3d52009-03-28 03:37:59 +0000254 case Stmt::CompoundStmtClass:
255 case Stmt::StmtExprClass:
Ted Kremenek1d9a23a2009-03-28 04:08:14 +0000256 return PathDiagnosticLocation(S, SMgr);
257 case Stmt::ChooseExprClass:
258 // Similar to '?' if we are referring to condition, just have the edge
259 // point to the entire choose expression.
260 if (cast<ChooseExpr>(Parent)->getCond() == S)
261 return PathDiagnosticLocation(Parent, SMgr);
262 else
263 return PathDiagnosticLocation(S, SMgr);
264 case Stmt::ConditionalOperatorClass:
265 // For '?', if we are referring to condition, just have the edge point
266 // to the entire '?' expression.
267 if (cast<ConditionalOperator>(Parent)->getCond() == S)
268 return PathDiagnosticLocation(Parent, SMgr);
269 else
270 return PathDiagnosticLocation(S, SMgr);
Ted Kremenekaf3e3d52009-03-28 03:37:59 +0000271 case Stmt::DoStmtClass:
Ted Kremenekaf3e3d52009-03-28 03:37:59 +0000272 return PathDiagnosticLocation(S, SMgr);
Ted Kremenekaf3e3d52009-03-28 03:37:59 +0000273 case Stmt::ForStmtClass:
274 if (cast<ForStmt>(Parent)->getBody() == S)
275 return PathDiagnosticLocation(S, SMgr);
276 break;
277 case Stmt::IfStmtClass:
278 if (cast<IfStmt>(Parent)->getCond() != S)
279 return PathDiagnosticLocation(S, SMgr);
Ted Kremenek8bd4d032009-04-28 04:23:15 +0000280 break;
Ted Kremenekaf3e3d52009-03-28 03:37:59 +0000281 case Stmt::ObjCForCollectionStmtClass:
282 if (cast<ObjCForCollectionStmt>(Parent)->getBody() == S)
283 return PathDiagnosticLocation(S, SMgr);
284 break;
285 case Stmt::WhileStmtClass:
286 if (cast<WhileStmt>(Parent)->getCond() != S)
287 return PathDiagnosticLocation(S, SMgr);
288 break;
289 default:
290 break;
291 }
292
Ted Kremenekd8c938b2009-03-27 21:16:25 +0000293 S = Parent;
294 }
295
296 assert(S && "Cannot have null Stmt for PathDiagnosticLocation");
Ted Kremeneke88a1702009-05-11 22:19:32 +0000297
298 // Special case: DeclStmts can appear in for statement declarations, in which
299 // case the ForStmt is the context.
300 if (isa<DeclStmt>(S)) {
301 if (const Stmt *Parent = P.getParent(S)) {
302 switch (Parent->getStmtClass()) {
303 case Stmt::ForStmtClass:
304 case Stmt::ObjCForCollectionStmtClass:
305 return PathDiagnosticLocation(Parent, SMgr);
306 default:
307 break;
308 }
309 }
310 }
311 else if (isa<BinaryOperator>(S)) {
312 // Special case: the binary operator represents the initialization
313 // code in a for statement (this can happen when the variable being
314 // initialized is an old variable.
315 if (const ForStmt *FS =
316 dyn_cast_or_null<ForStmt>(P.getParentIgnoreParens(S))) {
317 if (FS->getInit() == S)
318 return PathDiagnosticLocation(FS, SMgr);
319 }
320 }
321
Ted Kremenekd8c938b2009-03-27 21:16:25 +0000322 return PathDiagnosticLocation(S, SMgr);
323}
324
Ted Kremenekcf118d42009-02-04 23:49:09 +0000325//===----------------------------------------------------------------------===//
Ted Kremenek31061982009-03-31 23:00:32 +0000326// ScanNotableSymbols: closure-like callback for scanning Store bindings.
327//===----------------------------------------------------------------------===//
328
329static const VarDecl*
Zhongxing Xuc5619d92009-08-06 01:32:16 +0000330GetMostRecentVarDeclBinding(const ExplodedNode* N,
Ted Kremenek31061982009-03-31 23:00:32 +0000331 GRStateManager& VMgr, SVal X) {
332
333 for ( ; N ; N = N->pred_empty() ? 0 : *N->pred_begin()) {
334
335 ProgramPoint P = N->getLocation();
336
337 if (!isa<PostStmt>(P))
338 continue;
339
Ted Kremenek5f85e172009-07-22 22:35:28 +0000340 const DeclRefExpr* DR = dyn_cast<DeclRefExpr>(cast<PostStmt>(P).getStmt());
Ted Kremenek31061982009-03-31 23:00:32 +0000341
342 if (!DR)
343 continue;
344
Ted Kremenek23ec48c2009-06-18 23:58:37 +0000345 SVal Y = N->getState()->getSVal(DR);
Ted Kremenek31061982009-03-31 23:00:32 +0000346
347 if (X != Y)
348 continue;
349
Ted Kremenek5f85e172009-07-22 22:35:28 +0000350 const VarDecl* VD = dyn_cast<VarDecl>(DR->getDecl());
Ted Kremenek31061982009-03-31 23:00:32 +0000351
352 if (!VD)
353 continue;
354
355 return VD;
356 }
357
358 return 0;
359}
360
361namespace {
362class VISIBILITY_HIDDEN NotableSymbolHandler
363: public StoreManager::BindingsHandler {
364
365 SymbolRef Sym;
366 const GRState* PrevSt;
367 const Stmt* S;
368 GRStateManager& VMgr;
Zhongxing Xuc5619d92009-08-06 01:32:16 +0000369 const ExplodedNode* Pred;
Ted Kremenek31061982009-03-31 23:00:32 +0000370 PathDiagnostic& PD;
371 BugReporter& BR;
372
373public:
374
375 NotableSymbolHandler(SymbolRef sym, const GRState* prevst, const Stmt* s,
Zhongxing Xuc5619d92009-08-06 01:32:16 +0000376 GRStateManager& vmgr, const ExplodedNode* pred,
Ted Kremenek31061982009-03-31 23:00:32 +0000377 PathDiagnostic& pd, BugReporter& br)
378 : Sym(sym), PrevSt(prevst), S(s), VMgr(vmgr), Pred(pred), PD(pd), BR(br) {}
379
380 bool HandleBinding(StoreManager& SMgr, Store store, const MemRegion* R,
381 SVal V) {
382
383 SymbolRef ScanSym = V.getAsSymbol();
384
385 if (ScanSym != Sym)
386 return true;
387
388 // Check if the previous state has this binding.
Ted Kremenekdbc2afc2009-06-23 17:55:07 +0000389 SVal X = PrevSt->getSVal(loc::MemRegionVal(R));
Ted Kremenek31061982009-03-31 23:00:32 +0000390
391 if (X == V) // Same binding?
392 return true;
393
394 // Different binding. Only handle assignments for now. We don't pull
395 // this check out of the loop because we will eventually handle other
396 // cases.
397
398 VarDecl *VD = 0;
399
400 if (const BinaryOperator* B = dyn_cast<BinaryOperator>(S)) {
401 if (!B->isAssignmentOp())
402 return true;
403
404 // What variable did we assign to?
405 DeclRefExpr* DR = dyn_cast<DeclRefExpr>(B->getLHS()->IgnoreParenCasts());
406
407 if (!DR)
408 return true;
409
410 VD = dyn_cast<VarDecl>(DR->getDecl());
411 }
412 else if (const DeclStmt* DS = dyn_cast<DeclStmt>(S)) {
413 // FIXME: Eventually CFGs won't have DeclStmts. Right now we
414 // assume that each DeclStmt has a single Decl. This invariant
415 // holds by contruction in the CFG.
416 VD = dyn_cast<VarDecl>(*DS->decl_begin());
417 }
418
419 if (!VD)
420 return true;
421
422 // What is the most recently referenced variable with this binding?
423 const VarDecl* MostRecent = GetMostRecentVarDeclBinding(Pred, VMgr, V);
424
425 if (!MostRecent)
426 return true;
427
428 // Create the diagnostic.
429 FullSourceLoc L(S->getLocStart(), BR.getSourceManager());
430
431 if (Loc::IsLocType(VD->getType())) {
432 std::string msg = "'" + std::string(VD->getNameAsString()) +
433 "' now aliases '" + MostRecent->getNameAsString() + "'";
434
435 PD.push_front(new PathDiagnosticEventPiece(L, msg));
436 }
437
438 return true;
439 }
440};
441}
442
Zhongxing Xuc5619d92009-08-06 01:32:16 +0000443static void HandleNotableSymbol(const ExplodedNode* N,
Ted Kremenek31061982009-03-31 23:00:32 +0000444 const Stmt* S,
445 SymbolRef Sym, BugReporter& BR,
446 PathDiagnostic& PD) {
447
Zhongxing Xuc5619d92009-08-06 01:32:16 +0000448 const ExplodedNode* Pred = N->pred_empty() ? 0 : *N->pred_begin();
Ted Kremenek31061982009-03-31 23:00:32 +0000449 const GRState* PrevSt = Pred ? Pred->getState() : 0;
450
451 if (!PrevSt)
452 return;
453
454 // Look at the region bindings of the current state that map to the
455 // specified symbol. Are any of them not in the previous state?
456 GRStateManager& VMgr = cast<GRBugReporter>(BR).getStateManager();
457 NotableSymbolHandler H(Sym, PrevSt, S, VMgr, Pred, PD, BR);
458 cast<GRBugReporter>(BR).getStateManager().iterBindings(N->getState(), H);
459}
460
461namespace {
462class VISIBILITY_HIDDEN ScanNotableSymbols
463: public StoreManager::BindingsHandler {
464
465 llvm::SmallSet<SymbolRef, 10> AlreadyProcessed;
Zhongxing Xuc5619d92009-08-06 01:32:16 +0000466 const ExplodedNode* N;
Ted Kremenek5f85e172009-07-22 22:35:28 +0000467 const Stmt* S;
Ted Kremenek31061982009-03-31 23:00:32 +0000468 GRBugReporter& BR;
469 PathDiagnostic& PD;
470
471public:
Zhongxing Xuc5619d92009-08-06 01:32:16 +0000472 ScanNotableSymbols(const ExplodedNode* n, const Stmt* s,
Ted Kremenek5f85e172009-07-22 22:35:28 +0000473 GRBugReporter& br, PathDiagnostic& pd)
Ted Kremenek31061982009-03-31 23:00:32 +0000474 : N(n), S(s), BR(br), PD(pd) {}
475
476 bool HandleBinding(StoreManager& SMgr, Store store,
477 const MemRegion* R, SVal V) {
478
479 SymbolRef ScanSym = V.getAsSymbol();
480
481 if (!ScanSym)
482 return true;
483
484 if (!BR.isNotable(ScanSym))
485 return true;
486
487 if (AlreadyProcessed.count(ScanSym))
488 return true;
489
490 AlreadyProcessed.insert(ScanSym);
491
492 HandleNotableSymbol(N, S, ScanSym, BR, PD);
493 return true;
494 }
495};
496} // end anonymous namespace
497
498//===----------------------------------------------------------------------===//
499// "Minimal" path diagnostic generation algorithm.
500//===----------------------------------------------------------------------===//
501
Ted Kremenek14856d72009-04-06 23:06:54 +0000502static void CompactPathDiagnostic(PathDiagnostic &PD, const SourceManager& SM);
503
Ted Kremenek31061982009-03-31 23:00:32 +0000504static void GenerateMinimalPathDiagnostic(PathDiagnostic& PD,
505 PathDiagnosticBuilder &PDB,
Zhongxing Xuc5619d92009-08-06 01:32:16 +0000506 const ExplodedNode *N) {
Ted Kremenek8966bc12009-05-06 21:39:49 +0000507
Ted Kremenek31061982009-03-31 23:00:32 +0000508 SourceManager& SMgr = PDB.getSourceManager();
Zhongxing Xuc5619d92009-08-06 01:32:16 +0000509 const ExplodedNode* NextNode = N->pred_empty()
Ted Kremenek31061982009-03-31 23:00:32 +0000510 ? NULL : *(N->pred_begin());
511 while (NextNode) {
512 N = NextNode;
513 NextNode = GetPredecessorNode(N);
514
515 ProgramPoint P = N->getLocation();
516
517 if (const BlockEdge* BE = dyn_cast<BlockEdge>(&P)) {
518 CFGBlock* Src = BE->getSrc();
519 CFGBlock* Dst = BE->getDst();
520 Stmt* T = Src->getTerminator();
521
522 if (!T)
523 continue;
524
525 FullSourceLoc Start(T->getLocStart(), SMgr);
526
527 switch (T->getStmtClass()) {
528 default:
529 break;
530
531 case Stmt::GotoStmtClass:
532 case Stmt::IndirectGotoStmtClass: {
Ted Kremenek5f85e172009-07-22 22:35:28 +0000533 const Stmt* S = GetNextStmt(N);
Ted Kremenek31061982009-03-31 23:00:32 +0000534
535 if (!S)
536 continue;
537
538 std::string sbuf;
539 llvm::raw_string_ostream os(sbuf);
540 const PathDiagnosticLocation &End = PDB.getEnclosingStmtLocation(S);
541
542 os << "Control jumps to line "
543 << End.asLocation().getInstantiationLineNumber();
544 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
545 os.str()));
546 break;
547 }
548
549 case Stmt::SwitchStmtClass: {
550 // Figure out what case arm we took.
551 std::string sbuf;
552 llvm::raw_string_ostream os(sbuf);
553
554 if (Stmt* S = Dst->getLabel()) {
555 PathDiagnosticLocation End(S, SMgr);
556
557 switch (S->getStmtClass()) {
558 default:
559 os << "No cases match in the switch statement. "
560 "Control jumps to line "
561 << End.asLocation().getInstantiationLineNumber();
562 break;
563 case Stmt::DefaultStmtClass:
564 os << "Control jumps to the 'default' case at line "
565 << End.asLocation().getInstantiationLineNumber();
566 break;
567
568 case Stmt::CaseStmtClass: {
569 os << "Control jumps to 'case ";
570 CaseStmt* Case = cast<CaseStmt>(S);
571 Expr* LHS = Case->getLHS()->IgnoreParenCasts();
572
573 // Determine if it is an enum.
574 bool GetRawInt = true;
575
576 if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(LHS)) {
577 // FIXME: Maybe this should be an assertion. Are there cases
578 // were it is not an EnumConstantDecl?
579 EnumConstantDecl* D =
580 dyn_cast<EnumConstantDecl>(DR->getDecl());
581
582 if (D) {
583 GetRawInt = false;
584 os << D->getNameAsString();
585 }
586 }
Eli Friedman9ec64d62009-04-26 19:04:51 +0000587
588 if (GetRawInt)
Ted Kremenek8966bc12009-05-06 21:39:49 +0000589 os << LHS->EvaluateAsInt(PDB.getASTContext());
Eli Friedman9ec64d62009-04-26 19:04:51 +0000590
Ted Kremenek31061982009-03-31 23:00:32 +0000591 os << ":' at line "
592 << End.asLocation().getInstantiationLineNumber();
593 break;
594 }
595 }
596 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
597 os.str()));
598 }
599 else {
600 os << "'Default' branch taken. ";
601 const PathDiagnosticLocation &End = PDB.ExecutionContinues(os, N);
602 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
603 os.str()));
604 }
605
606 break;
607 }
608
609 case Stmt::BreakStmtClass:
610 case Stmt::ContinueStmtClass: {
611 std::string sbuf;
612 llvm::raw_string_ostream os(sbuf);
613 PathDiagnosticLocation End = PDB.ExecutionContinues(os, N);
614 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
615 os.str()));
616 break;
617 }
618
619 // Determine control-flow for ternary '?'.
620 case Stmt::ConditionalOperatorClass: {
621 std::string sbuf;
622 llvm::raw_string_ostream os(sbuf);
623 os << "'?' condition is ";
624
625 if (*(Src->succ_begin()+1) == Dst)
626 os << "false";
627 else
628 os << "true";
629
630 PathDiagnosticLocation End = PDB.ExecutionContinues(N);
631
632 if (const Stmt *S = End.asStmt())
633 End = PDB.getEnclosingStmtLocation(S);
634
635 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
636 os.str()));
637 break;
638 }
639
640 // Determine control-flow for short-circuited '&&' and '||'.
641 case Stmt::BinaryOperatorClass: {
642 if (!PDB.supportsLogicalOpControlFlow())
643 break;
644
645 BinaryOperator *B = cast<BinaryOperator>(T);
646 std::string sbuf;
647 llvm::raw_string_ostream os(sbuf);
648 os << "Left side of '";
649
650 if (B->getOpcode() == BinaryOperator::LAnd) {
651 os << "&&" << "' is ";
652
653 if (*(Src->succ_begin()+1) == Dst) {
654 os << "false";
655 PathDiagnosticLocation End(B->getLHS(), SMgr);
656 PathDiagnosticLocation Start(B->getOperatorLoc(), SMgr);
657 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
658 os.str()));
659 }
660 else {
661 os << "true";
662 PathDiagnosticLocation Start(B->getLHS(), SMgr);
663 PathDiagnosticLocation End = PDB.ExecutionContinues(N);
664 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
665 os.str()));
666 }
667 }
668 else {
669 assert(B->getOpcode() == BinaryOperator::LOr);
670 os << "||" << "' is ";
671
672 if (*(Src->succ_begin()+1) == Dst) {
673 os << "false";
674 PathDiagnosticLocation Start(B->getLHS(), SMgr);
675 PathDiagnosticLocation End = PDB.ExecutionContinues(N);
676 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
677 os.str()));
678 }
679 else {
680 os << "true";
681 PathDiagnosticLocation End(B->getLHS(), SMgr);
682 PathDiagnosticLocation Start(B->getOperatorLoc(), SMgr);
683 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
684 os.str()));
685 }
686 }
687
688 break;
689 }
690
691 case Stmt::DoStmtClass: {
692 if (*(Src->succ_begin()) == Dst) {
693 std::string sbuf;
694 llvm::raw_string_ostream os(sbuf);
695
696 os << "Loop condition is true. ";
697 PathDiagnosticLocation End = PDB.ExecutionContinues(os, N);
698
699 if (const Stmt *S = End.asStmt())
700 End = PDB.getEnclosingStmtLocation(S);
701
702 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
703 os.str()));
704 }
705 else {
706 PathDiagnosticLocation End = PDB.ExecutionContinues(N);
707
708 if (const Stmt *S = End.asStmt())
709 End = PDB.getEnclosingStmtLocation(S);
710
711 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
712 "Loop condition is false. Exiting loop"));
713 }
714
715 break;
716 }
717
718 case Stmt::WhileStmtClass:
719 case Stmt::ForStmtClass: {
720 if (*(Src->succ_begin()+1) == Dst) {
721 std::string sbuf;
722 llvm::raw_string_ostream os(sbuf);
723
724 os << "Loop condition is false. ";
725 PathDiagnosticLocation End = PDB.ExecutionContinues(os, N);
726 if (const Stmt *S = End.asStmt())
727 End = PDB.getEnclosingStmtLocation(S);
728
729 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
730 os.str()));
731 }
732 else {
733 PathDiagnosticLocation End = PDB.ExecutionContinues(N);
734 if (const Stmt *S = End.asStmt())
735 End = PDB.getEnclosingStmtLocation(S);
736
737 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000738 "Loop condition is true. Entering loop body"));
Ted Kremenek31061982009-03-31 23:00:32 +0000739 }
740
741 break;
742 }
743
744 case Stmt::IfStmtClass: {
745 PathDiagnosticLocation End = PDB.ExecutionContinues(N);
746
747 if (const Stmt *S = End.asStmt())
748 End = PDB.getEnclosingStmtLocation(S);
749
750 if (*(Src->succ_begin()+1) == Dst)
751 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000752 "Taking false branch"));
Ted Kremenek31061982009-03-31 23:00:32 +0000753 else
754 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000755 "Taking true branch"));
Ted Kremenek31061982009-03-31 23:00:32 +0000756
757 break;
758 }
759 }
760 }
761
Ted Kremenekdd986cc2009-05-07 00:45:33 +0000762 if (NextNode) {
763 for (BugReporterContext::visitor_iterator I = PDB.visitor_begin(),
764 E = PDB.visitor_end(); I!=E; ++I) {
765 if (PathDiagnosticPiece* p = (*I)->VisitNode(N, NextNode, PDB))
766 PD.push_front(p);
767 }
Ted Kremenek8966bc12009-05-06 21:39:49 +0000768 }
Ted Kremenek31061982009-03-31 23:00:32 +0000769
770 if (const PostStmt* PS = dyn_cast<PostStmt>(&P)) {
771 // Scan the region bindings, and see if a "notable" symbol has a new
772 // lval binding.
773 ScanNotableSymbols SNS(N, PS->getStmt(), PDB.getBugReporter(), PD);
774 PDB.getStateManager().iterBindings(N->getState(), SNS);
775 }
776 }
Ted Kremenek14856d72009-04-06 23:06:54 +0000777
778 // After constructing the full PathDiagnostic, do a pass over it to compact
779 // PathDiagnosticPieces that occur within a macro.
780 CompactPathDiagnostic(PD, PDB.getSourceManager());
Ted Kremenek31061982009-03-31 23:00:32 +0000781}
782
783//===----------------------------------------------------------------------===//
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000784// "Extensive" PathDiagnostic generation.
785//===----------------------------------------------------------------------===//
786
787static bool IsControlFlowExpr(const Stmt *S) {
788 const Expr *E = dyn_cast<Expr>(S);
Ted Kremenek14856d72009-04-06 23:06:54 +0000789
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000790 if (!E)
791 return false;
792
793 E = E->IgnoreParenCasts();
794
795 if (isa<ConditionalOperator>(E))
796 return true;
797
798 if (const BinaryOperator *B = dyn_cast<BinaryOperator>(E))
799 if (B->isLogicalOp())
800 return true;
801
802 return false;
803}
804
Ted Kremenek14856d72009-04-06 23:06:54 +0000805namespace {
Ted Kremenek8f9b1b32009-05-01 16:08:09 +0000806class VISIBILITY_HIDDEN ContextLocation : public PathDiagnosticLocation {
807 bool IsDead;
808public:
809 ContextLocation(const PathDiagnosticLocation &L, bool isdead = false)
810 : PathDiagnosticLocation(L), IsDead(isdead) {}
811
812 void markDead() { IsDead = true; }
813 bool isDead() const { return IsDead; }
814};
815
Ted Kremenek14856d72009-04-06 23:06:54 +0000816class VISIBILITY_HIDDEN EdgeBuilder {
Ted Kremenek8f9b1b32009-05-01 16:08:09 +0000817 std::vector<ContextLocation> CLocs;
818 typedef std::vector<ContextLocation>::iterator iterator;
Ted Kremenek14856d72009-04-06 23:06:54 +0000819 PathDiagnostic &PD;
820 PathDiagnosticBuilder &PDB;
821 PathDiagnosticLocation PrevLoc;
Ted Kremenek8f9b1b32009-05-01 16:08:09 +0000822
823 bool IsConsumedExpr(const PathDiagnosticLocation &L);
824
Ted Kremenek14856d72009-04-06 23:06:54 +0000825 bool containsLocation(const PathDiagnosticLocation &Container,
826 const PathDiagnosticLocation &Containee);
827
828 PathDiagnosticLocation getContextLocation(const PathDiagnosticLocation &L);
Ted Kremenek14856d72009-04-06 23:06:54 +0000829
Ted Kremenek9650cf32009-05-11 21:42:34 +0000830 PathDiagnosticLocation cleanUpLocation(PathDiagnosticLocation L,
831 bool firstCharOnly = false) {
Ted Kremenek8c8b0ad2009-05-11 19:50:47 +0000832 if (const Stmt *S = L.asStmt()) {
Ted Kremenek9650cf32009-05-11 21:42:34 +0000833 const Stmt *Original = S;
Ted Kremenek8c8b0ad2009-05-11 19:50:47 +0000834 while (1) {
835 // Adjust the location for some expressions that are best referenced
836 // by one of their subexpressions.
Ted Kremenek9650cf32009-05-11 21:42:34 +0000837 switch (S->getStmtClass()) {
838 default:
839 break;
840 case Stmt::ParenExprClass:
841 S = cast<ParenExpr>(S)->IgnoreParens();
842 firstCharOnly = true;
843 continue;
844 case Stmt::ConditionalOperatorClass:
845 S = cast<ConditionalOperator>(S)->getCond();
846 firstCharOnly = true;
847 continue;
848 case Stmt::ChooseExprClass:
849 S = cast<ChooseExpr>(S)->getCond();
850 firstCharOnly = true;
851 continue;
852 case Stmt::BinaryOperatorClass:
853 S = cast<BinaryOperator>(S)->getLHS();
854 firstCharOnly = true;
855 continue;
856 }
857
858 break;
Ted Kremenek8c8b0ad2009-05-11 19:50:47 +0000859 }
860
Ted Kremenek9650cf32009-05-11 21:42:34 +0000861 if (S != Original)
862 L = PathDiagnosticLocation(S, L.getManager());
Ted Kremenek8c8b0ad2009-05-11 19:50:47 +0000863 }
864
Ted Kremenek9650cf32009-05-11 21:42:34 +0000865 if (firstCharOnly)
866 L = PathDiagnosticLocation(L.asLocation());
867
Ted Kremenek8c8b0ad2009-05-11 19:50:47 +0000868 return L;
869 }
870
Ted Kremenek14856d72009-04-06 23:06:54 +0000871 void popLocation() {
Ted Kremenek8f9b1b32009-05-01 16:08:09 +0000872 if (!CLocs.back().isDead() && CLocs.back().asLocation().isFileID()) {
Ted Kremenek5c7168c2009-04-22 20:36:26 +0000873 // For contexts, we only one the first character as the range.
Ted Kremenek07c015c2009-05-15 02:46:13 +0000874 rawAddEdge(cleanUpLocation(CLocs.back(), true));
Ted Kremenek5c7168c2009-04-22 20:36:26 +0000875 }
Ted Kremenek14856d72009-04-06 23:06:54 +0000876 CLocs.pop_back();
877 }
878
879 PathDiagnosticLocation IgnoreParens(const PathDiagnosticLocation &L);
880
881public:
882 EdgeBuilder(PathDiagnostic &pd, PathDiagnosticBuilder &pdb)
883 : PD(pd), PDB(pdb) {
Ted Kremeneka301a672009-04-22 18:16:20 +0000884
885 // If the PathDiagnostic already has pieces, add the enclosing statement
886 // of the first piece as a context as well.
Ted Kremenek14856d72009-04-06 23:06:54 +0000887 if (!PD.empty()) {
888 PrevLoc = PD.begin()->getLocation();
889
890 if (const Stmt *S = PrevLoc.asStmt())
Ted Kremeneke1baed32009-05-05 23:13:38 +0000891 addExtendedContext(PDB.getEnclosingStmtLocation(S).asStmt());
Ted Kremenek14856d72009-04-06 23:06:54 +0000892 }
893 }
894
895 ~EdgeBuilder() {
896 while (!CLocs.empty()) popLocation();
Ted Kremeneka301a672009-04-22 18:16:20 +0000897
898 // Finally, add an initial edge from the start location of the first
899 // statement (if it doesn't already exist).
Sebastian Redld3a413d2009-04-26 20:35:05 +0000900 // FIXME: Should handle CXXTryStmt if analyser starts supporting C++.
901 if (const CompoundStmt *CS =
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +0000902 PDB.getCodeDecl().getCompoundBody())
Ted Kremeneka301a672009-04-22 18:16:20 +0000903 if (!CS->body_empty()) {
904 SourceLocation Loc = (*CS->body_begin())->getLocStart();
905 rawAddEdge(PathDiagnosticLocation(Loc, PDB.getSourceManager()));
906 }
907
Ted Kremenek14856d72009-04-06 23:06:54 +0000908 }
909
910 void addEdge(PathDiagnosticLocation NewLoc, bool alwaysAdd = false);
911
912 void addEdge(const Stmt *S, bool alwaysAdd = false) {
913 addEdge(PathDiagnosticLocation(S, PDB.getSourceManager()), alwaysAdd);
914 }
915
Ted Kremenek8bd4d032009-04-28 04:23:15 +0000916 void rawAddEdge(PathDiagnosticLocation NewLoc);
917
Ted Kremenek14856d72009-04-06 23:06:54 +0000918 void addContext(const Stmt *S);
Ted Kremeneke1baed32009-05-05 23:13:38 +0000919 void addExtendedContext(const Stmt *S);
Ted Kremenek14856d72009-04-06 23:06:54 +0000920};
921} // end anonymous namespace
922
923
924PathDiagnosticLocation
925EdgeBuilder::getContextLocation(const PathDiagnosticLocation &L) {
926 if (const Stmt *S = L.asStmt()) {
927 if (IsControlFlowExpr(S))
928 return L;
929
930 return PDB.getEnclosingStmtLocation(S);
931 }
932
933 return L;
934}
935
936bool EdgeBuilder::containsLocation(const PathDiagnosticLocation &Container,
937 const PathDiagnosticLocation &Containee) {
938
939 if (Container == Containee)
940 return true;
941
942 if (Container.asDecl())
943 return true;
944
945 if (const Stmt *S = Containee.asStmt())
946 if (const Stmt *ContainerS = Container.asStmt()) {
947 while (S) {
948 if (S == ContainerS)
949 return true;
950 S = PDB.getParent(S);
951 }
952 return false;
953 }
954
955 // Less accurate: compare using source ranges.
956 SourceRange ContainerR = Container.asRange();
957 SourceRange ContaineeR = Containee.asRange();
958
959 SourceManager &SM = PDB.getSourceManager();
960 SourceLocation ContainerRBeg = SM.getInstantiationLoc(ContainerR.getBegin());
961 SourceLocation ContainerREnd = SM.getInstantiationLoc(ContainerR.getEnd());
962 SourceLocation ContaineeRBeg = SM.getInstantiationLoc(ContaineeR.getBegin());
963 SourceLocation ContaineeREnd = SM.getInstantiationLoc(ContaineeR.getEnd());
964
965 unsigned ContainerBegLine = SM.getInstantiationLineNumber(ContainerRBeg);
966 unsigned ContainerEndLine = SM.getInstantiationLineNumber(ContainerREnd);
967 unsigned ContaineeBegLine = SM.getInstantiationLineNumber(ContaineeRBeg);
968 unsigned ContaineeEndLine = SM.getInstantiationLineNumber(ContaineeREnd);
969
970 assert(ContainerBegLine <= ContainerEndLine);
971 assert(ContaineeBegLine <= ContaineeEndLine);
972
973 return (ContainerBegLine <= ContaineeBegLine &&
974 ContainerEndLine >= ContaineeEndLine &&
975 (ContainerBegLine != ContaineeBegLine ||
976 SM.getInstantiationColumnNumber(ContainerRBeg) <=
977 SM.getInstantiationColumnNumber(ContaineeRBeg)) &&
978 (ContainerEndLine != ContaineeEndLine ||
979 SM.getInstantiationColumnNumber(ContainerREnd) >=
980 SM.getInstantiationColumnNumber(ContainerREnd)));
981}
982
983PathDiagnosticLocation
984EdgeBuilder::IgnoreParens(const PathDiagnosticLocation &L) {
985 if (const Expr* E = dyn_cast_or_null<Expr>(L.asStmt()))
986 return PathDiagnosticLocation(E->IgnoreParenCasts(),
987 PDB.getSourceManager());
988 return L;
989}
990
991void EdgeBuilder::rawAddEdge(PathDiagnosticLocation NewLoc) {
992 if (!PrevLoc.isValid()) {
993 PrevLoc = NewLoc;
994 return;
995 }
996
Ted Kremenek8c8b0ad2009-05-11 19:50:47 +0000997 const PathDiagnosticLocation &NewLocClean = cleanUpLocation(NewLoc);
998 const PathDiagnosticLocation &PrevLocClean = cleanUpLocation(PrevLoc);
999
1000 if (NewLocClean.asLocation() == PrevLocClean.asLocation())
Ted Kremenek14856d72009-04-06 23:06:54 +00001001 return;
1002
1003 // FIXME: Ignore intra-macro edges for now.
Ted Kremenek8c8b0ad2009-05-11 19:50:47 +00001004 if (NewLocClean.asLocation().getInstantiationLoc() ==
1005 PrevLocClean.asLocation().getInstantiationLoc())
Ted Kremenek14856d72009-04-06 23:06:54 +00001006 return;
1007
Ted Kremenek8c8b0ad2009-05-11 19:50:47 +00001008 PD.push_front(new PathDiagnosticControlFlowPiece(NewLocClean, PrevLocClean));
1009 PrevLoc = NewLoc;
Ted Kremenek14856d72009-04-06 23:06:54 +00001010}
1011
1012void EdgeBuilder::addEdge(PathDiagnosticLocation NewLoc, bool alwaysAdd) {
Ted Kremeneka301a672009-04-22 18:16:20 +00001013
1014 if (!alwaysAdd && NewLoc.asLocation().isMacroID())
1015 return;
1016
Ted Kremenek14856d72009-04-06 23:06:54 +00001017 const PathDiagnosticLocation &CLoc = getContextLocation(NewLoc);
1018
1019 while (!CLocs.empty()) {
Ted Kremenek8f9b1b32009-05-01 16:08:09 +00001020 ContextLocation &TopContextLoc = CLocs.back();
Ted Kremenek14856d72009-04-06 23:06:54 +00001021
1022 // Is the top location context the same as the one for the new location?
1023 if (TopContextLoc == CLoc) {
Ted Kremenek8f9b1b32009-05-01 16:08:09 +00001024 if (alwaysAdd) {
Ted Kremenek4c6f8d32009-05-04 18:15:17 +00001025 if (IsConsumedExpr(TopContextLoc) &&
1026 !IsControlFlowExpr(TopContextLoc.asStmt()))
Ted Kremenek8f9b1b32009-05-01 16:08:09 +00001027 TopContextLoc.markDead();
1028
Ted Kremenek14856d72009-04-06 23:06:54 +00001029 rawAddEdge(NewLoc);
Ted Kremenek8f9b1b32009-05-01 16:08:09 +00001030 }
Ted Kremenek14856d72009-04-06 23:06:54 +00001031
1032 return;
1033 }
1034
1035 if (containsLocation(TopContextLoc, CLoc)) {
Ted Kremenek8f9b1b32009-05-01 16:08:09 +00001036 if (alwaysAdd) {
Ted Kremenek14856d72009-04-06 23:06:54 +00001037 rawAddEdge(NewLoc);
Ted Kremenek8f9b1b32009-05-01 16:08:09 +00001038
Ted Kremenek4c6f8d32009-05-04 18:15:17 +00001039 if (IsConsumedExpr(CLoc) && !IsControlFlowExpr(CLoc.asStmt())) {
Ted Kremenek8f9b1b32009-05-01 16:08:09 +00001040 CLocs.push_back(ContextLocation(CLoc, true));
1041 return;
1042 }
1043 }
1044
Ted Kremenek14856d72009-04-06 23:06:54 +00001045 CLocs.push_back(CLoc);
1046 return;
1047 }
1048
1049 // Context does not contain the location. Flush it.
1050 popLocation();
1051 }
Ted Kremenek5c7168c2009-04-22 20:36:26 +00001052
1053 // If we reach here, there is no enclosing context. Just add the edge.
1054 rawAddEdge(NewLoc);
Ted Kremenek14856d72009-04-06 23:06:54 +00001055}
1056
Ted Kremenek8f9b1b32009-05-01 16:08:09 +00001057bool EdgeBuilder::IsConsumedExpr(const PathDiagnosticLocation &L) {
1058 if (const Expr *X = dyn_cast_or_null<Expr>(L.asStmt()))
1059 return PDB.getParentMap().isConsumedExpr(X) && !IsControlFlowExpr(X);
1060
1061 return false;
1062}
1063
Ted Kremeneke1baed32009-05-05 23:13:38 +00001064void EdgeBuilder::addExtendedContext(const Stmt *S) {
1065 if (!S)
1066 return;
1067
1068 const Stmt *Parent = PDB.getParent(S);
1069 while (Parent) {
1070 if (isa<CompoundStmt>(Parent))
1071 Parent = PDB.getParent(Parent);
1072 else
1073 break;
1074 }
1075
1076 if (Parent) {
1077 switch (Parent->getStmtClass()) {
1078 case Stmt::DoStmtClass:
1079 case Stmt::ObjCAtSynchronizedStmtClass:
1080 addContext(Parent);
1081 default:
1082 break;
1083 }
1084 }
1085
1086 addContext(S);
1087}
1088
Ted Kremenek14856d72009-04-06 23:06:54 +00001089void EdgeBuilder::addContext(const Stmt *S) {
1090 if (!S)
1091 return;
1092
1093 PathDiagnosticLocation L(S, PDB.getSourceManager());
1094
1095 while (!CLocs.empty()) {
1096 const PathDiagnosticLocation &TopContextLoc = CLocs.back();
1097
1098 // Is the top location context the same as the one for the new location?
1099 if (TopContextLoc == L)
1100 return;
1101
1102 if (containsLocation(TopContextLoc, L)) {
Ted Kremenek14856d72009-04-06 23:06:54 +00001103 CLocs.push_back(L);
1104 return;
1105 }
1106
1107 // Context does not contain the location. Flush it.
1108 popLocation();
1109 }
1110
1111 CLocs.push_back(L);
1112}
1113
1114static void GenerateExtensivePathDiagnostic(PathDiagnostic& PD,
1115 PathDiagnosticBuilder &PDB,
Zhongxing Xuc5619d92009-08-06 01:32:16 +00001116 const ExplodedNode *N) {
Ted Kremenek14856d72009-04-06 23:06:54 +00001117
1118
1119 EdgeBuilder EB(PD, PDB);
1120
Zhongxing Xuc5619d92009-08-06 01:32:16 +00001121 const ExplodedNode* NextNode = N->pred_empty()
Ted Kremenek14856d72009-04-06 23:06:54 +00001122 ? NULL : *(N->pred_begin());
Ted Kremenek14856d72009-04-06 23:06:54 +00001123 while (NextNode) {
1124 N = NextNode;
1125 NextNode = GetPredecessorNode(N);
1126 ProgramPoint P = N->getLocation();
1127
Ted Kremenekdd986cc2009-05-07 00:45:33 +00001128 do {
1129 // Block edges.
1130 if (const BlockEdge *BE = dyn_cast<BlockEdge>(&P)) {
1131 const CFGBlock &Blk = *BE->getSrc();
1132 const Stmt *Term = Blk.getTerminator();
1133
Ted Kremenekdd986cc2009-05-07 00:45:33 +00001134 // Are we jumping to the head of a loop? Add a special diagnostic.
Ted Kremenekddb7bab2009-05-15 01:50:15 +00001135 if (const Stmt *Loop = BE->getDst()->getLoopTarget()) {
Ted Kremenekdd986cc2009-05-07 00:45:33 +00001136 PathDiagnosticLocation L(Loop, PDB.getSourceManager());
Ted Kremenekddb7bab2009-05-15 01:50:15 +00001137 const CompoundStmt *CS = NULL;
1138
1139 if (!Term) {
1140 if (const ForStmt *FS = dyn_cast<ForStmt>(Loop))
1141 CS = dyn_cast<CompoundStmt>(FS->getBody());
1142 else if (const WhileStmt *WS = dyn_cast<WhileStmt>(Loop))
1143 CS = dyn_cast<CompoundStmt>(WS->getBody());
1144 }
1145
Ted Kremenekdd986cc2009-05-07 00:45:33 +00001146 PathDiagnosticEventPiece *p =
1147 new PathDiagnosticEventPiece(L,
Ted Kremenek07c015c2009-05-15 02:46:13 +00001148 "Looping back to the head of the loop");
Ted Kremenekdd986cc2009-05-07 00:45:33 +00001149
1150 EB.addEdge(p->getLocation(), true);
1151 PD.push_front(p);
1152
Ted Kremenekddb7bab2009-05-15 01:50:15 +00001153 if (CS) {
Ted Kremenek07c015c2009-05-15 02:46:13 +00001154 PathDiagnosticLocation BL(CS->getRBracLoc(),
1155 PDB.getSourceManager());
1156 BL = PathDiagnosticLocation(BL.asLocation());
1157 EB.addEdge(BL);
Ted Kremenekdd986cc2009-05-07 00:45:33 +00001158 }
Ted Kremenek8bd4d032009-04-28 04:23:15 +00001159 }
Ted Kremenekddb7bab2009-05-15 01:50:15 +00001160
1161 if (Term)
1162 EB.addContext(Term);
Ted Kremenekdd986cc2009-05-07 00:45:33 +00001163
1164 break;
Ted Kremenek14856d72009-04-06 23:06:54 +00001165 }
1166
Ted Kremenekdd986cc2009-05-07 00:45:33 +00001167 if (const BlockEntrance *BE = dyn_cast<BlockEntrance>(&P)) {
1168 if (const Stmt* S = BE->getFirstStmt()) {
1169 if (IsControlFlowExpr(S)) {
1170 // Add the proper context for '&&', '||', and '?'.
1171 EB.addContext(S);
1172 }
1173 else
1174 EB.addExtendedContext(PDB.getEnclosingStmtLocation(S).asStmt());
1175 }
1176
1177 break;
1178 }
1179 } while (0);
1180
1181 if (!NextNode)
Ted Kremenek14856d72009-04-06 23:06:54 +00001182 continue;
Ted Kremenek14856d72009-04-06 23:06:54 +00001183
Ted Kremenek8966bc12009-05-06 21:39:49 +00001184 for (BugReporterContext::visitor_iterator I = PDB.visitor_begin(),
1185 E = PDB.visitor_end(); I!=E; ++I) {
1186 if (PathDiagnosticPiece* p = (*I)->VisitNode(N, NextNode, PDB)) {
1187 const PathDiagnosticLocation &Loc = p->getLocation();
1188 EB.addEdge(Loc, true);
1189 PD.push_front(p);
1190 if (const Stmt *S = Loc.asStmt())
1191 EB.addExtendedContext(PDB.getEnclosingStmtLocation(S).asStmt());
1192 }
1193 }
Ted Kremenek14856d72009-04-06 23:06:54 +00001194 }
1195}
1196
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +00001197//===----------------------------------------------------------------------===//
Ted Kremenekcf118d42009-02-04 23:49:09 +00001198// Methods for BugType and subclasses.
1199//===----------------------------------------------------------------------===//
1200BugType::~BugType() {}
1201void BugType::FlushReports(BugReporter &BR) {}
Ted Kremenekbb77e9b2008-05-01 22:50:36 +00001202
Ted Kremenekcf118d42009-02-04 23:49:09 +00001203//===----------------------------------------------------------------------===//
1204// Methods for BugReport and subclasses.
1205//===----------------------------------------------------------------------===//
1206BugReport::~BugReport() {}
1207RangedBugReport::~RangedBugReport() {}
1208
Ted Kremenek5f85e172009-07-22 22:35:28 +00001209const Stmt* BugReport::getStmt(BugReporter& BR) const {
Ted Kremenek200ed922008-05-02 23:21:21 +00001210 ProgramPoint ProgP = EndNode->getLocation();
Ted Kremenek5f85e172009-07-22 22:35:28 +00001211 const Stmt *S = NULL;
Ted Kremenekbd7efa82008-04-17 23:44:37 +00001212
Ted Kremenekcf118d42009-02-04 23:49:09 +00001213 if (BlockEntrance* BE = dyn_cast<BlockEntrance>(&ProgP)) {
Ted Kremenekb697b102009-02-23 22:44:26 +00001214 if (BE->getBlock() == &BR.getCFG()->getExit()) S = GetPreviousStmt(EndNode);
Ted Kremenekcf118d42009-02-04 23:49:09 +00001215 }
Ted Kremenek5f85e172009-07-22 22:35:28 +00001216 if (!S)
1217 S = GetStmt(ProgP);
Ted Kremenekcf118d42009-02-04 23:49:09 +00001218
Ted Kremenekbb77e9b2008-05-01 22:50:36 +00001219 return S;
1220}
1221
1222PathDiagnosticPiece*
Ted Kremenek8966bc12009-05-06 21:39:49 +00001223BugReport::getEndPath(BugReporterContext& BRC,
Zhongxing Xuc5619d92009-08-06 01:32:16 +00001224 const ExplodedNode* EndPathNode) {
Ted Kremenekbb77e9b2008-05-01 22:50:36 +00001225
Ted Kremenek5f85e172009-07-22 22:35:28 +00001226 const Stmt* S = getStmt(BRC.getBugReporter());
Ted Kremenek61f3e052008-04-03 04:42:52 +00001227
1228 if (!S)
1229 return NULL;
Ted Kremenek3ef538d2009-05-11 23:50:59 +00001230
Ted Kremenekde7161f2008-04-03 18:00:37 +00001231 const SourceRange *Beg, *End;
Ted Kremenek3ef538d2009-05-11 23:50:59 +00001232 getRanges(BRC.getBugReporter(), Beg, End);
1233 PathDiagnosticLocation L(S, BRC.getSourceManager());
Ted Kremenekcf118d42009-02-04 23:49:09 +00001234
Ted Kremenek3ef538d2009-05-11 23:50:59 +00001235 // Only add the statement itself as a range if we didn't specify any
1236 // special ranges for this report.
1237 PathDiagnosticPiece* P = new PathDiagnosticEventPiece(L, getDescription(),
1238 Beg == End);
1239
Ted Kremenekbb77e9b2008-05-01 22:50:36 +00001240 for (; Beg != End; ++Beg)
1241 P->addRange(*Beg);
Ted Kremenek61f3e052008-04-03 04:42:52 +00001242
1243 return P;
1244}
1245
Ted Kremenekbb77e9b2008-05-01 22:50:36 +00001246void BugReport::getRanges(BugReporter& BR, const SourceRange*& beg,
1247 const SourceRange*& end) {
1248
Ted Kremenek5f85e172009-07-22 22:35:28 +00001249 if (const Expr* E = dyn_cast_or_null<Expr>(getStmt(BR))) {
Ted Kremenekbb77e9b2008-05-01 22:50:36 +00001250 R = E->getSourceRange();
Ted Kremenek9b5e5052009-02-27 20:05:10 +00001251 assert(R.isValid());
Ted Kremenekbb77e9b2008-05-01 22:50:36 +00001252 beg = &R;
1253 end = beg+1;
1254 }
1255 else
1256 beg = end = 0;
Ted Kremenekf1ae7052008-04-03 17:57:38 +00001257}
1258
Ted Kremenekcf118d42009-02-04 23:49:09 +00001259SourceLocation BugReport::getLocation() const {
1260 if (EndNode)
Ted Kremenek5f85e172009-07-22 22:35:28 +00001261 if (const Stmt* S = GetCurrentOrPreviousStmt(EndNode)) {
Ted Kremenek9b5e5052009-02-27 20:05:10 +00001262 // For member expressions, return the location of the '.' or '->'.
Ted Kremenek5f85e172009-07-22 22:35:28 +00001263 if (const MemberExpr* ME = dyn_cast<MemberExpr>(S))
Ted Kremenek9b5e5052009-02-27 20:05:10 +00001264 return ME->getMemberLoc();
1265
Ted Kremenekcf118d42009-02-04 23:49:09 +00001266 return S->getLocStart();
Ted Kremenek9b5e5052009-02-27 20:05:10 +00001267 }
Ted Kremenekcf118d42009-02-04 23:49:09 +00001268
1269 return FullSourceLoc();
Ted Kremenekd2f642b2008-04-14 17:39:48 +00001270}
1271
Zhongxing Xuc5619d92009-08-06 01:32:16 +00001272PathDiagnosticPiece* BugReport::VisitNode(const ExplodedNode* N,
1273 const ExplodedNode* PrevN,
Ted Kremenek8966bc12009-05-06 21:39:49 +00001274 BugReporterContext &BRC) {
Ted Kremenek50a6d0c2008-04-09 21:41:14 +00001275 return NULL;
1276}
1277
Ted Kremenekcf118d42009-02-04 23:49:09 +00001278//===----------------------------------------------------------------------===//
1279// Methods for BugReporter and subclasses.
1280//===----------------------------------------------------------------------===//
1281
1282BugReportEquivClass::~BugReportEquivClass() {
Ted Kremenek8966bc12009-05-06 21:39:49 +00001283 for (iterator I=begin(), E=end(); I!=E; ++I) delete *I;
Ted Kremenekcf118d42009-02-04 23:49:09 +00001284}
1285
1286GRBugReporter::~GRBugReporter() { FlushReports(); }
1287BugReporterData::~BugReporterData() {}
1288
Zhongxing Xu38b02b92009-08-06 06:28:40 +00001289ExplodedGraph &GRBugReporter::getGraph() { return Eng.getGraph(); }
Ted Kremenekcf118d42009-02-04 23:49:09 +00001290
1291GRStateManager&
1292GRBugReporter::getStateManager() { return Eng.getStateManager(); }
1293
1294BugReporter::~BugReporter() { FlushReports(); }
1295
1296void BugReporter::FlushReports() {
1297 if (BugTypes.isEmpty())
1298 return;
1299
1300 // First flush the warnings for each BugType. This may end up creating new
1301 // warnings and new BugTypes. Because ImmutableSet is a functional data
1302 // structure, we do not need to worry about the iterators being invalidated.
1303 for (BugTypesTy::iterator I=BugTypes.begin(), E=BugTypes.end(); I!=E; ++I)
1304 const_cast<BugType*>(*I)->FlushReports(*this);
1305
1306 // Iterate through BugTypes a second time. BugTypes may have been updated
1307 // with new BugType objects and new warnings.
1308 for (BugTypesTy::iterator I=BugTypes.begin(), E=BugTypes.end(); I!=E; ++I) {
1309 BugType *BT = const_cast<BugType*>(*I);
1310
1311 typedef llvm::FoldingSet<BugReportEquivClass> SetTy;
1312 SetTy& EQClasses = BT->EQClasses;
1313
1314 for (SetTy::iterator EI=EQClasses.begin(), EE=EQClasses.end(); EI!=EE;++EI){
1315 BugReportEquivClass& EQ = *EI;
1316 FlushReport(EQ);
1317 }
Ted Kremeneka43a1eb2008-04-23 23:02:12 +00001318
Zhongxing Xud9b401c2009-07-29 08:13:37 +00001319 // Delete the BugType object.
1320
1321 // FIXME: this will *not* delete the BugReportEquivClasses, since FoldingSet
1322 // only deletes the buckets, not the nodes themselves.
Ted Kremenekcf118d42009-02-04 23:49:09 +00001323 delete BT;
Ted Kremenek94826a72008-04-03 04:59:14 +00001324 }
Ted Kremenekcf118d42009-02-04 23:49:09 +00001325
1326 // Remove all references to the BugType objects.
1327 BugTypes = F.GetEmptySet();
1328}
1329
1330//===----------------------------------------------------------------------===//
1331// PathDiagnostics generation.
1332//===----------------------------------------------------------------------===//
1333
Zhongxing Xu38b02b92009-08-06 06:28:40 +00001334static std::pair<std::pair<ExplodedGraph*, NodeBackMap*>,
Zhongxing Xuc5619d92009-08-06 01:32:16 +00001335 std::pair<ExplodedNode*, unsigned> >
Zhongxing Xu38b02b92009-08-06 06:28:40 +00001336MakeReportGraph(const ExplodedGraph* G,
Zhongxing Xuc5619d92009-08-06 01:32:16 +00001337 const ExplodedNode** NStart,
1338 const ExplodedNode** NEnd) {
Ted Kremenek94826a72008-04-03 04:59:14 +00001339
Ted Kremenekcf118d42009-02-04 23:49:09 +00001340 // Create the trimmed graph. It will contain the shortest paths from the
1341 // error nodes to the root. In the new graph we should only have one
1342 // error node unless there are two or more error nodes with the same minimum
1343 // path length.
Zhongxing Xu38b02b92009-08-06 06:28:40 +00001344 ExplodedGraph* GTrim;
Zhongxing Xuc5619d92009-08-06 01:32:16 +00001345 InterExplodedGraphMap* NMap;
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001346
1347 llvm::DenseMap<const void*, const void*> InverseMap;
1348 llvm::tie(GTrim, NMap) = G->Trim(NStart, NEnd, &InverseMap);
Ted Kremenekcf118d42009-02-04 23:49:09 +00001349
1350 // Create owning pointers for GTrim and NMap just to ensure that they are
1351 // released when this function exists.
Zhongxing Xu38b02b92009-08-06 06:28:40 +00001352 llvm::OwningPtr<ExplodedGraph> AutoReleaseGTrim(GTrim);
Zhongxing Xuc5619d92009-08-06 01:32:16 +00001353 llvm::OwningPtr<InterExplodedGraphMap> AutoReleaseNMap(NMap);
Ted Kremenekcf118d42009-02-04 23:49:09 +00001354
1355 // Find the (first) error node in the trimmed graph. We just need to consult
1356 // the node map (NMap) which maps from nodes in the original graph to nodes
1357 // in the new graph.
Ted Kremenek938332c2009-05-16 01:11:58 +00001358
Zhongxing Xuc5619d92009-08-06 01:32:16 +00001359 std::queue<const ExplodedNode*> WS;
Zhongxing Xu38b02b92009-08-06 06:28:40 +00001360 typedef llvm::DenseMap<const ExplodedNode*, unsigned> IndexMapTy;
Ted Kremenek938332c2009-05-16 01:11:58 +00001361 IndexMapTy IndexMap;
Ted Kremenekcf118d42009-02-04 23:49:09 +00001362
Zhongxing Xuc5619d92009-08-06 01:32:16 +00001363 for (const ExplodedNode** I = NStart; I != NEnd; ++I)
1364 if (const ExplodedNode *N = NMap->getMappedNode(*I)) {
Ted Kremenek938332c2009-05-16 01:11:58 +00001365 unsigned NodeIndex = (I - NStart) / sizeof(*I);
1366 WS.push(N);
1367 IndexMap[*I] = NodeIndex;
Ted Kremenekcf118d42009-02-04 23:49:09 +00001368 }
1369
Ted Kremenek938332c2009-05-16 01:11:58 +00001370 assert(!WS.empty() && "No error node found in the trimmed graph.");
Ted Kremenekcf118d42009-02-04 23:49:09 +00001371
1372 // Create a new (third!) graph with a single path. This is the graph
1373 // that will be returned to the caller.
Zhongxing Xu38b02b92009-08-06 06:28:40 +00001374 ExplodedGraph *GNew = new ExplodedGraph(GTrim->getCFG(), GTrim->getCodeDecl(),
1375 GTrim->getContext());
Ted Kremenekcf118d42009-02-04 23:49:09 +00001376
Ted Kremenek10aa5542009-03-12 23:41:59 +00001377 // Sometimes the trimmed graph can contain a cycle. Perform a reverse BFS
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001378 // to the root node, and then construct a new graph that contains only
1379 // a single path.
Ted Kremenek3148eb42009-01-24 00:55:43 +00001380 llvm::DenseMap<const void*,unsigned> Visited;
Ted Kremenek10aa5542009-03-12 23:41:59 +00001381
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001382 unsigned cnt = 0;
Zhongxing Xuc5619d92009-08-06 01:32:16 +00001383 const ExplodedNode* Root = 0;
Ted Kremenekc1da4412008-06-17 19:14:06 +00001384
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001385 while (!WS.empty()) {
Zhongxing Xuc5619d92009-08-06 01:32:16 +00001386 const ExplodedNode* Node = WS.front();
Ted Kremenek10aa5542009-03-12 23:41:59 +00001387 WS.pop();
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001388
1389 if (Visited.find(Node) != Visited.end())
1390 continue;
1391
1392 Visited[Node] = cnt++;
1393
1394 if (Node->pred_empty()) {
1395 Root = Node;
1396 break;
1397 }
1398
Zhongxing Xuc5619d92009-08-06 01:32:16 +00001399 for (ExplodedNode::const_pred_iterator I=Node->pred_begin(),
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001400 E=Node->pred_end(); I!=E; ++I)
Ted Kremenek10aa5542009-03-12 23:41:59 +00001401 WS.push(*I);
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001402 }
Ted Kremenekcf118d42009-02-04 23:49:09 +00001403
Ted Kremenek938332c2009-05-16 01:11:58 +00001404 assert(Root);
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001405
Ted Kremenek10aa5542009-03-12 23:41:59 +00001406 // Now walk from the root down the BFS path, always taking the successor
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001407 // with the lowest number.
Zhongxing Xuc5619d92009-08-06 01:32:16 +00001408 ExplodedNode *Last = 0, *First = 0;
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001409 NodeBackMap *BM = new NodeBackMap();
Ted Kremenek938332c2009-05-16 01:11:58 +00001410 unsigned NodeIndex = 0;
Ted Kremenekcf118d42009-02-04 23:49:09 +00001411
Zhongxing Xuc5619d92009-08-06 01:32:16 +00001412 for ( const ExplodedNode *N = Root ;;) {
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001413 // Lookup the number associated with the current node.
Ted Kremenek3148eb42009-01-24 00:55:43 +00001414 llvm::DenseMap<const void*,unsigned>::iterator I = Visited.find(N);
Ted Kremenek938332c2009-05-16 01:11:58 +00001415 assert(I != Visited.end());
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001416
1417 // Create the equivalent node in the new graph with the same state
1418 // and location.
Zhongxing Xu38b02b92009-08-06 06:28:40 +00001419 ExplodedNode* NewN = GNew->getNode(N->getLocation(), N->getState());
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001420
1421 // Store the mapping to the original node.
1422 llvm::DenseMap<const void*, const void*>::iterator IMitr=InverseMap.find(N);
1423 assert(IMitr != InverseMap.end() && "No mapping to original node.");
Zhongxing Xuc5619d92009-08-06 01:32:16 +00001424 (*BM)[NewN] = (const ExplodedNode*) IMitr->second;
Ted Kremenekcf118d42009-02-04 23:49:09 +00001425
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001426 // Link up the new node with the previous node.
1427 if (Last)
1428 NewN->addPredecessor(Last);
Ted Kremeneka43a1eb2008-04-23 23:02:12 +00001429
1430 Last = NewN;
Ted Kremenekcf118d42009-02-04 23:49:09 +00001431
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001432 // Are we at the final node?
Ted Kremenek938332c2009-05-16 01:11:58 +00001433 IndexMapTy::iterator IMI =
Zhongxing Xuc5619d92009-08-06 01:32:16 +00001434 IndexMap.find((const ExplodedNode*)(IMitr->second));
Ted Kremenek938332c2009-05-16 01:11:58 +00001435 if (IMI != IndexMap.end()) {
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001436 First = NewN;
Ted Kremenek938332c2009-05-16 01:11:58 +00001437 NodeIndex = IMI->second;
Ted Kremenekc1da4412008-06-17 19:14:06 +00001438 break;
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001439 }
Ted Kremenekcf118d42009-02-04 23:49:09 +00001440
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001441 // Find the next successor node. We choose the node that is marked
1442 // with the lowest DFS number.
Zhongxing Xuc5619d92009-08-06 01:32:16 +00001443 ExplodedNode::const_succ_iterator SI = N->succ_begin();
1444 ExplodedNode::const_succ_iterator SE = N->succ_end();
Ted Kremenekc1da4412008-06-17 19:14:06 +00001445 N = 0;
1446
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001447 for (unsigned MinVal = 0; SI != SE; ++SI) {
Ted Kremenekcf118d42009-02-04 23:49:09 +00001448
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001449 I = Visited.find(*SI);
1450
1451 if (I == Visited.end())
1452 continue;
1453
1454 if (!N || I->second < MinVal) {
1455 N = *SI;
1456 MinVal = I->second;
Ted Kremenekc1da4412008-06-17 19:14:06 +00001457 }
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001458 }
Ted Kremenekcf118d42009-02-04 23:49:09 +00001459
Ted Kremenek938332c2009-05-16 01:11:58 +00001460 assert(N);
Ted Kremeneka43a1eb2008-04-23 23:02:12 +00001461 }
Ted Kremenekcf118d42009-02-04 23:49:09 +00001462
Ted Kremenek938332c2009-05-16 01:11:58 +00001463 assert(First);
1464
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001465 return std::make_pair(std::make_pair(GNew, BM),
1466 std::make_pair(First, NodeIndex));
Ted Kremeneka43a1eb2008-04-23 23:02:12 +00001467}
1468
Ted Kremenek0e5c8d42009-03-10 05:16:17 +00001469/// CompactPathDiagnostic - This function postprocesses a PathDiagnostic object
1470/// and collapses PathDiagosticPieces that are expanded by macros.
1471static void CompactPathDiagnostic(PathDiagnostic &PD, const SourceManager& SM) {
1472 typedef std::vector<std::pair<PathDiagnosticMacroPiece*, SourceLocation> >
1473 MacroStackTy;
1474
1475 typedef std::vector<PathDiagnosticPiece*>
1476 PiecesTy;
1477
1478 MacroStackTy MacroStack;
1479 PiecesTy Pieces;
1480
1481 for (PathDiagnostic::iterator I = PD.begin(), E = PD.end(); I!=E; ++I) {
1482 // Get the location of the PathDiagnosticPiece.
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +00001483 const FullSourceLoc Loc = I->getLocation().asLocation();
Ted Kremenek0e5c8d42009-03-10 05:16:17 +00001484
1485 // Determine the instantiation location, which is the location we group
1486 // related PathDiagnosticPieces.
1487 SourceLocation InstantiationLoc = Loc.isMacroID() ?
1488 SM.getInstantiationLoc(Loc) :
1489 SourceLocation();
1490
1491 if (Loc.isFileID()) {
1492 MacroStack.clear();
1493 Pieces.push_back(&*I);
1494 continue;
1495 }
1496
1497 assert(Loc.isMacroID());
1498
1499 // Is the PathDiagnosticPiece within the same macro group?
1500 if (!MacroStack.empty() && InstantiationLoc == MacroStack.back().second) {
1501 MacroStack.back().first->push_back(&*I);
1502 continue;
1503 }
1504
1505 // We aren't in the same group. Are we descending into a new macro
1506 // or are part of an old one?
1507 PathDiagnosticMacroPiece *MacroGroup = 0;
1508
1509 SourceLocation ParentInstantiationLoc = InstantiationLoc.isMacroID() ?
1510 SM.getInstantiationLoc(Loc) :
1511 SourceLocation();
1512
1513 // Walk the entire macro stack.
1514 while (!MacroStack.empty()) {
1515 if (InstantiationLoc == MacroStack.back().second) {
1516 MacroGroup = MacroStack.back().first;
1517 break;
1518 }
1519
1520 if (ParentInstantiationLoc == MacroStack.back().second) {
1521 MacroGroup = MacroStack.back().first;
1522 break;
1523 }
1524
1525 MacroStack.pop_back();
1526 }
1527
1528 if (!MacroGroup || ParentInstantiationLoc == MacroStack.back().second) {
1529 // Create a new macro group and add it to the stack.
1530 PathDiagnosticMacroPiece *NewGroup = new PathDiagnosticMacroPiece(Loc);
1531
1532 if (MacroGroup)
1533 MacroGroup->push_back(NewGroup);
1534 else {
1535 assert(InstantiationLoc.isFileID());
1536 Pieces.push_back(NewGroup);
1537 }
1538
1539 MacroGroup = NewGroup;
1540 MacroStack.push_back(std::make_pair(MacroGroup, InstantiationLoc));
1541 }
1542
1543 // Finally, add the PathDiagnosticPiece to the group.
1544 MacroGroup->push_back(&*I);
1545 }
1546
1547 // Now take the pieces and construct a new PathDiagnostic.
1548 PD.resetPath(false);
1549
1550 for (PiecesTy::iterator I=Pieces.begin(), E=Pieces.end(); I!=E; ++I) {
1551 if (PathDiagnosticMacroPiece *MP=dyn_cast<PathDiagnosticMacroPiece>(*I))
1552 if (!MP->containsEvent()) {
1553 delete MP;
1554 continue;
1555 }
1556
1557 PD.push_back(*I);
1558 }
1559}
1560
Ted Kremenek7dc86642009-03-31 20:22:36 +00001561void GRBugReporter::GeneratePathDiagnostic(PathDiagnostic& PD,
Ted Kremenek8966bc12009-05-06 21:39:49 +00001562 BugReportEquivClass& EQ) {
Ted Kremenek7dc86642009-03-31 20:22:36 +00001563
Zhongxing Xuc5619d92009-08-06 01:32:16 +00001564 std::vector<const ExplodedNode*> Nodes;
Ted Kremenek7dc86642009-03-31 20:22:36 +00001565
Ted Kremenekcf118d42009-02-04 23:49:09 +00001566 for (BugReportEquivClass::iterator I=EQ.begin(), E=EQ.end(); I!=E; ++I) {
Zhongxing Xuc5619d92009-08-06 01:32:16 +00001567 const ExplodedNode* N = I->getEndNode();
Ted Kremenekcf118d42009-02-04 23:49:09 +00001568 if (N) Nodes.push_back(N);
1569 }
1570
1571 if (Nodes.empty())
1572 return;
Ted Kremeneka43a1eb2008-04-23 23:02:12 +00001573
1574 // Construct a new graph that contains only a single path from the error
Ted Kremenekcf118d42009-02-04 23:49:09 +00001575 // node to a root.
Zhongxing Xu38b02b92009-08-06 06:28:40 +00001576 const std::pair<std::pair<ExplodedGraph*, NodeBackMap*>,
Zhongxing Xuc5619d92009-08-06 01:32:16 +00001577 std::pair<ExplodedNode*, unsigned> >&
Ted Kremenek7dc86642009-03-31 20:22:36 +00001578 GPair = MakeReportGraph(&getGraph(), &Nodes[0], &Nodes[0] + Nodes.size());
Ted Kremeneka43a1eb2008-04-23 23:02:12 +00001579
Ted Kremenekcf118d42009-02-04 23:49:09 +00001580 // Find the BugReport with the original location.
1581 BugReport *R = 0;
1582 unsigned i = 0;
1583 for (BugReportEquivClass::iterator I=EQ.begin(), E=EQ.end(); I!=E; ++I, ++i)
1584 if (i == GPair.second.second) { R = *I; break; }
1585
1586 assert(R && "No original report found for sliced graph.");
Ted Kremeneka43a1eb2008-04-23 23:02:12 +00001587
Zhongxing Xu38b02b92009-08-06 06:28:40 +00001588 llvm::OwningPtr<ExplodedGraph> ReportGraph(GPair.first.first);
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001589 llvm::OwningPtr<NodeBackMap> BackMap(GPair.first.second);
Zhongxing Xuc5619d92009-08-06 01:32:16 +00001590 const ExplodedNode *N = GPair.second.first;
Ted Kremenek7dc86642009-03-31 20:22:36 +00001591
Ted Kremenek8966bc12009-05-06 21:39:49 +00001592 // Start building the path diagnostic...
1593 PathDiagnosticBuilder PDB(*this, R, BackMap.get(), getPathDiagnosticClient());
1594
1595 if (PathDiagnosticPiece* Piece = R->getEndPath(PDB, N))
Ted Kremenekbd7efa82008-04-17 23:44:37 +00001596 PD.push_back(Piece);
1597 else
1598 return;
Ted Kremenekdd986cc2009-05-07 00:45:33 +00001599
1600 R->registerInitialVisitors(PDB, N);
Ted Kremenekbd7efa82008-04-17 23:44:37 +00001601
Ted Kremenek7dc86642009-03-31 20:22:36 +00001602 switch (PDB.getGenerationScheme()) {
1603 case PathDiagnosticClient::Extensive:
Ted Kremenek8966bc12009-05-06 21:39:49 +00001604 GenerateExtensivePathDiagnostic(PD, PDB, N);
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +00001605 break;
Ted Kremenek7dc86642009-03-31 20:22:36 +00001606 case PathDiagnosticClient::Minimal:
1607 GenerateMinimalPathDiagnostic(PD, PDB, N);
1608 break;
1609 }
Ted Kremenek7dc86642009-03-31 20:22:36 +00001610}
1611
Ted Kremenekcf118d42009-02-04 23:49:09 +00001612void BugReporter::Register(BugType *BT) {
1613 BugTypes = F.Add(BugTypes, BT);
Ted Kremenek76d90c82008-05-16 18:33:14 +00001614}
1615
Ted Kremenekcf118d42009-02-04 23:49:09 +00001616void BugReporter::EmitReport(BugReport* R) {
1617 // Compute the bug report's hash to determine its equivalence class.
1618 llvm::FoldingSetNodeID ID;
1619 R->Profile(ID);
Ted Kremenek61f3e052008-04-03 04:42:52 +00001620
Ted Kremenekcf118d42009-02-04 23:49:09 +00001621 // Lookup the equivance class. If there isn't one, create it.
1622 BugType& BT = R->getBugType();
1623 Register(&BT);
1624 void *InsertPos;
1625 BugReportEquivClass* EQ = BT.EQClasses.FindNodeOrInsertPos(ID, InsertPos);
1626
1627 if (!EQ) {
1628 EQ = new BugReportEquivClass(R);
1629 BT.EQClasses.InsertNode(EQ, InsertPos);
1630 }
1631 else
1632 EQ->AddReport(R);
Ted Kremenek61f3e052008-04-03 04:42:52 +00001633}
1634
Ted Kremenekcf118d42009-02-04 23:49:09 +00001635void BugReporter::FlushReport(BugReportEquivClass& EQ) {
1636 assert(!EQ.Reports.empty());
1637 BugReport &R = **EQ.begin();
Ted Kremenekd49967f2009-04-29 21:58:13 +00001638 PathDiagnosticClient* PD = getPathDiagnosticClient();
Ted Kremenekcf118d42009-02-04 23:49:09 +00001639
1640 // FIXME: Make sure we use the 'R' for the path that was actually used.
1641 // Probably doesn't make a difference in practice.
1642 BugType& BT = R.getBugType();
1643
Ted Kremenekd49967f2009-04-29 21:58:13 +00001644 llvm::OwningPtr<PathDiagnostic>
1645 D(new PathDiagnostic(R.getBugType().getName(),
Ted Kremenekda0e8422009-04-29 22:05:03 +00001646 !PD || PD->useVerboseDescription()
Ted Kremenekd49967f2009-04-29 21:58:13 +00001647 ? R.getDescription() : R.getShortDescription(),
1648 BT.getCategory()));
1649
Ted Kremenekcf118d42009-02-04 23:49:09 +00001650 GeneratePathDiagnostic(*D.get(), EQ);
Ted Kremenek072192b2008-04-30 23:47:44 +00001651
1652 // Get the meta data.
Ted Kremenek072192b2008-04-30 23:47:44 +00001653 std::pair<const char**, const char**> Meta = R.getExtraDescriptiveText();
Ted Kremenek3148eb42009-01-24 00:55:43 +00001654 for (const char** s = Meta.first; s != Meta.second; ++s) D->addMeta(*s);
Ted Kremenek75840e12008-04-18 01:56:37 +00001655
Ted Kremenek3148eb42009-01-24 00:55:43 +00001656 // Emit a summary diagnostic to the regular Diagnostics engine.
Ted Kremenek3148eb42009-01-24 00:55:43 +00001657 const SourceRange *Beg = 0, *End = 0;
1658 R.getRanges(*this, Beg, End);
1659 Diagnostic& Diag = getDiagnostic();
Ted Kremenekcf118d42009-02-04 23:49:09 +00001660 FullSourceLoc L(R.getLocation(), getSourceManager());
Ted Kremenekd90e7082009-02-07 22:36:41 +00001661 unsigned ErrorDiag = Diag.getCustomDiagID(Diagnostic::Warning,
Ted Kremenekeaedfea2009-05-10 05:11:21 +00001662 R.getShortDescription().c_str());
Ted Kremenek57202072008-07-14 17:40:50 +00001663
Ted Kremenek3148eb42009-01-24 00:55:43 +00001664 switch (End-Beg) {
Chris Lattner0a14eee2008-11-18 07:04:44 +00001665 default: assert(0 && "Don't handle this many ranges yet!");
1666 case 0: Diag.Report(L, ErrorDiag); break;
1667 case 1: Diag.Report(L, ErrorDiag) << Beg[0]; break;
1668 case 2: Diag.Report(L, ErrorDiag) << Beg[0] << Beg[1]; break;
1669 case 3: Diag.Report(L, ErrorDiag) << Beg[0] << Beg[1] << Beg[2]; break;
Ted Kremenek2f0e89e2008-04-18 22:56:53 +00001670 }
Ted Kremenek3148eb42009-01-24 00:55:43 +00001671
1672 // Emit a full diagnostic for the path if we have a PathDiagnosticClient.
1673 if (!PD)
1674 return;
1675
1676 if (D->empty()) {
Ted Kremenek1fbfd5b2009-03-06 23:58:11 +00001677 PathDiagnosticPiece* piece =
1678 new PathDiagnosticEventPiece(L, R.getDescription());
1679
Ted Kremenek3148eb42009-01-24 00:55:43 +00001680 for ( ; Beg != End; ++Beg) piece->addRange(*Beg);
1681 D->push_back(piece);
1682 }
1683
1684 PD->HandlePathDiagnostic(D.take());
Ted Kremenek61f3e052008-04-03 04:42:52 +00001685}
Ted Kremenek57202072008-07-14 17:40:50 +00001686
Ted Kremenek8c036c72008-09-20 04:23:38 +00001687void BugReporter::EmitBasicReport(const char* name, const char* str,
1688 SourceLocation Loc,
1689 SourceRange* RBeg, unsigned NumRanges) {
1690 EmitBasicReport(name, "", str, Loc, RBeg, NumRanges);
1691}
Ted Kremenekcf118d42009-02-04 23:49:09 +00001692
Ted Kremenek8c036c72008-09-20 04:23:38 +00001693void BugReporter::EmitBasicReport(const char* name, const char* category,
1694 const char* str, SourceLocation Loc,
1695 SourceRange* RBeg, unsigned NumRanges) {
1696
Ted Kremenekcf118d42009-02-04 23:49:09 +00001697 // 'BT' will be owned by BugReporter as soon as we call 'EmitReport'.
1698 BugType *BT = new BugType(name, category);
Chris Lattner0a14eee2008-11-18 07:04:44 +00001699 FullSourceLoc L = getContext().getFullLoc(Loc);
Ted Kremenekcf118d42009-02-04 23:49:09 +00001700 RangedBugReport *R = new DiagBugReport(*BT, str, L);
1701 for ( ; NumRanges > 0 ; --NumRanges, ++RBeg) R->addRange(*RBeg);
1702 EmitReport(R);
Ted Kremenek57202072008-07-14 17:40:50 +00001703}