blob: a691bb67aa67a6ae8a253f2a6e766abb6fd5dee8 [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 Kremenekb697b102009-02-23 22:44:26 +000043static inline Stmt* GetStmt(ProgramPoint P) {
44 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
Ted Kremenek3148eb42009-01-24 00:55:43 +000052static inline const ExplodedNode<GRState>*
Ted Kremenekb697b102009-02-23 22:44:26 +000053GetPredecessorNode(const ExplodedNode<GRState>* 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
Ted Kremenekb697b102009-02-23 22:44:26 +000057static inline const ExplodedNode<GRState>*
58GetSuccessorNode(const ExplodedNode<GRState>* N) {
59 return N->succ_empty() ? NULL : *(N->succ_begin());
Ted Kremenekbd7efa82008-04-17 23:44:37 +000060}
61
Ted Kremenekb697b102009-02-23 22:44:26 +000062static Stmt* GetPreviousStmt(const ExplodedNode<GRState>* N) {
63 for (N = GetPredecessorNode(N); N; N = GetPredecessorNode(N))
64 if (Stmt *S = GetStmt(N->getLocation()))
65 return S;
66
67 return 0;
Ted Kremenek3148eb42009-01-24 00:55:43 +000068}
69
Ted Kremenekb697b102009-02-23 22:44:26 +000070static Stmt* GetNextStmt(const ExplodedNode<GRState>* N) {
71 for (N = GetSuccessorNode(N); N; N = GetSuccessorNode(N))
Ted Kremenekf5ab8e62009-03-28 17:33:57 +000072 if (Stmt *S = GetStmt(N->getLocation())) {
73 // 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 Kremenekb697b102009-02-23 22:44:26 +000087 return S;
Ted Kremenekf5ab8e62009-03-28 17:33:57 +000088 }
Ted Kremenekb697b102009-02-23 22:44:26 +000089
90 return 0;
91}
92
93static inline Stmt* GetCurrentOrPreviousStmt(const ExplodedNode<GRState>* N) {
94 if (Stmt *S = GetStmt(N->getLocation()))
95 return S;
96
97 return GetPreviousStmt(N);
98}
99
100static inline Stmt* GetCurrentOrNextStmt(const ExplodedNode<GRState>* N) {
101 if (Stmt *S = GetStmt(N->getLocation()))
102 return S;
103
104 return GetNextStmt(N);
105}
106
107//===----------------------------------------------------------------------===//
Ted Kremenek31061982009-03-31 23:00:32 +0000108// PathDiagnosticBuilder and its associated routines and helper objects.
Ted Kremenekb697b102009-02-23 22:44:26 +0000109//===----------------------------------------------------------------------===//
Ted Kremenekb479dad2009-02-23 23:13:51 +0000110
Ted Kremenek7dc86642009-03-31 20:22:36 +0000111typedef llvm::DenseMap<const ExplodedNode<GRState>*,
112const ExplodedNode<GRState>*> NodeBackMap;
113
Ted Kremenekbabdd7b2009-03-27 05:06:10 +0000114namespace {
Ted Kremenek7dc86642009-03-31 20:22:36 +0000115class VISIBILITY_HIDDEN NodeMapClosure : public BugReport::NodeResolver {
116 NodeBackMap& M;
117public:
118 NodeMapClosure(NodeBackMap *m) : M(*m) {}
119 ~NodeMapClosure() {}
120
121 const ExplodedNode<GRState>* getOriginalNode(const ExplodedNode<GRState>* N) {
122 NodeBackMap::iterator I = M.find(N);
123 return I == M.end() ? 0 : I->second;
124 }
125};
126
Ted Kremenek8966bc12009-05-06 21:39:49 +0000127class VISIBILITY_HIDDEN PathDiagnosticBuilder : public BugReporterContext {
Ted Kremenek7dc86642009-03-31 20:22:36 +0000128 BugReport *R;
Ted Kremenekbabdd7b2009-03-27 05:06:10 +0000129 PathDiagnosticClient *PDC;
Ted Kremenek00605e02009-03-27 20:55:39 +0000130 llvm::OwningPtr<ParentMap> PM;
Ted Kremenek7dc86642009-03-31 20:22:36 +0000131 NodeMapClosure NMC;
Ted Kremenekbabdd7b2009-03-27 05:06:10 +0000132public:
Ted Kremenek8966bc12009-05-06 21:39:49 +0000133 PathDiagnosticBuilder(GRBugReporter &br,
Ted Kremenek7dc86642009-03-31 20:22:36 +0000134 BugReport *r, NodeBackMap *Backmap,
Ted Kremenek8966bc12009-05-06 21:39:49 +0000135 PathDiagnosticClient *pdc)
136 : BugReporterContext(br),
137 R(r), PDC(pdc), NMC(Backmap)
138 {
139 addVisitor(R);
140 }
Ted Kremenekbabdd7b2009-03-27 05:06:10 +0000141
Ted Kremenek00605e02009-03-27 20:55:39 +0000142 PathDiagnosticLocation ExecutionContinues(const ExplodedNode<GRState>* N);
Ted Kremenekbabdd7b2009-03-27 05:06:10 +0000143
Ted Kremenek00605e02009-03-27 20:55:39 +0000144 PathDiagnosticLocation ExecutionContinues(llvm::raw_string_ostream& os,
145 const ExplodedNode<GRState>* N);
146
147 ParentMap& getParentMap() {
Ted Kremenek8966bc12009-05-06 21:39:49 +0000148 if (PM.get() == 0)
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +0000149 PM.reset(new ParentMap(getCodeDecl().getBody()));
Ted Kremenek00605e02009-03-27 20:55:39 +0000150 return *PM.get();
151 }
Ted Kremenekbabdd7b2009-03-27 05:06:10 +0000152
Ted Kremenekc3f83ad2009-04-01 17:18:21 +0000153 const Stmt *getParent(const Stmt *S) {
154 return getParentMap().getParent(S);
155 }
Ted Kremenek8966bc12009-05-06 21:39:49 +0000156
157 virtual NodeMapClosure& getNodeResolver() { return NMC; }
Ted Kremenek7dc86642009-03-31 20:22:36 +0000158 BugReport& getReport() { return *R; }
Douglas Gregor72971342009-04-18 00:02:19 +0000159
Ted Kremenekd8c938b2009-03-27 21:16:25 +0000160 PathDiagnosticLocation getEnclosingStmtLocation(const Stmt *S);
161
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000162 PathDiagnosticLocation
163 getEnclosingStmtLocation(const PathDiagnosticLocation &L) {
164 if (const Stmt *S = L.asStmt())
165 return getEnclosingStmtLocation(S);
166
167 return L;
168 }
169
Ted Kremenek7dc86642009-03-31 20:22:36 +0000170 PathDiagnosticClient::PathGenerationScheme getGenerationScheme() const {
171 return PDC ? PDC->getGenerationScheme() : PathDiagnosticClient::Extensive;
172 }
173
Ted Kremenekbabdd7b2009-03-27 05:06:10 +0000174 bool supportsLogicalOpControlFlow() const {
175 return PDC ? PDC->supportsLogicalOpControlFlow() : true;
176 }
177};
178} // end anonymous namespace
179
Ted Kremenek00605e02009-03-27 20:55:39 +0000180PathDiagnosticLocation
181PathDiagnosticBuilder::ExecutionContinues(const ExplodedNode<GRState>* N) {
182 if (Stmt *S = GetNextStmt(N))
Ted Kremenek8966bc12009-05-06 21:39:49 +0000183 return PathDiagnosticLocation(S, getSourceManager());
Ted Kremenek00605e02009-03-27 20:55:39 +0000184
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +0000185 return FullSourceLoc(getCodeDecl().getBodyRBrace(), getSourceManager());
Ted Kremenek082cb8d2009-03-12 18:41:53 +0000186}
187
Ted Kremenek00605e02009-03-27 20:55:39 +0000188PathDiagnosticLocation
Ted Kremenekbabdd7b2009-03-27 05:06:10 +0000189PathDiagnosticBuilder::ExecutionContinues(llvm::raw_string_ostream& os,
190 const ExplodedNode<GRState>* N) {
191
Ted Kremenek143ca222008-05-06 18:11:09 +0000192 // Slow, but probably doesn't matter.
Ted Kremenekb697b102009-02-23 22:44:26 +0000193 if (os.str().empty())
194 os << ' ';
Ted Kremenek143ca222008-05-06 18:11:09 +0000195
Ted Kremenek00605e02009-03-27 20:55:39 +0000196 const PathDiagnosticLocation &Loc = ExecutionContinues(N);
Ted Kremenek082cb8d2009-03-12 18:41:53 +0000197
Ted Kremenek00605e02009-03-27 20:55:39 +0000198 if (Loc.asStmt())
Ted Kremenekb697b102009-02-23 22:44:26 +0000199 os << "Execution continues on line "
Ted Kremenek8966bc12009-05-06 21:39:49 +0000200 << getSourceManager().getInstantiationLineNumber(Loc.asLocation())
201 << '.';
Ted Kremenekb697b102009-02-23 22:44:26 +0000202 else
Ted Kremenekb479dad2009-02-23 23:13:51 +0000203 os << "Execution jumps to the end of the "
Ted Kremenek8966bc12009-05-06 21:39:49 +0000204 << (isa<ObjCMethodDecl>(getCodeDecl()) ? "method" : "function") << '.';
Ted Kremenek082cb8d2009-03-12 18:41:53 +0000205
206 return Loc;
Ted Kremenek143ca222008-05-06 18:11:09 +0000207}
208
Ted Kremenekddb7bab2009-05-15 01:50:15 +0000209static bool IsNested(const Stmt *S, ParentMap &PM) {
210 if (isa<Expr>(S) && PM.isConsumedExpr(cast<Expr>(S)))
211 return true;
212
213 const Stmt *Parent = PM.getParentIgnoreParens(S);
214
215 if (Parent)
216 switch (Parent->getStmtClass()) {
217 case Stmt::ForStmtClass:
218 case Stmt::DoStmtClass:
219 case Stmt::WhileStmtClass:
220 return true;
221 default:
222 break;
223 }
224
225 return false;
226}
227
Ted Kremenekd8c938b2009-03-27 21:16:25 +0000228PathDiagnosticLocation
229PathDiagnosticBuilder::getEnclosingStmtLocation(const Stmt *S) {
230 assert(S && "Null Stmt* passed to getEnclosingStmtLocation");
Ted Kremenekc42e07e2009-05-05 22:19:17 +0000231 ParentMap &P = getParentMap();
Ted Kremenek8966bc12009-05-06 21:39:49 +0000232 SourceManager &SMgr = getSourceManager();
Ted Kremeneke88a1702009-05-11 22:19:32 +0000233
Ted Kremenekddb7bab2009-05-15 01:50:15 +0000234 while (IsNested(S, P)) {
Ted Kremenek8c8b0ad2009-05-11 19:50:47 +0000235 const Stmt *Parent = P.getParentIgnoreParens(S);
Ted Kremenekd8c938b2009-03-27 21:16:25 +0000236
Ted Kremenekaf3e3d52009-03-28 03:37:59 +0000237 if (!Parent)
238 break;
Ted Kremenekd8c938b2009-03-27 21:16:25 +0000239
Ted Kremenekaf3e3d52009-03-28 03:37:59 +0000240 switch (Parent->getStmtClass()) {
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000241 case Stmt::BinaryOperatorClass: {
242 const BinaryOperator *B = cast<BinaryOperator>(Parent);
243 if (B->isLogicalOp())
244 return PathDiagnosticLocation(S, SMgr);
245 break;
Ted Kremenek8c8b0ad2009-05-11 19:50:47 +0000246 }
Ted Kremenekaf3e3d52009-03-28 03:37:59 +0000247 case Stmt::CompoundStmtClass:
248 case Stmt::StmtExprClass:
Ted Kremenek1d9a23a2009-03-28 04:08:14 +0000249 return PathDiagnosticLocation(S, SMgr);
250 case Stmt::ChooseExprClass:
251 // Similar to '?' if we are referring to condition, just have the edge
252 // point to the entire choose expression.
253 if (cast<ChooseExpr>(Parent)->getCond() == S)
254 return PathDiagnosticLocation(Parent, SMgr);
255 else
256 return PathDiagnosticLocation(S, SMgr);
257 case Stmt::ConditionalOperatorClass:
258 // For '?', if we are referring to condition, just have the edge point
259 // to the entire '?' expression.
260 if (cast<ConditionalOperator>(Parent)->getCond() == S)
261 return PathDiagnosticLocation(Parent, SMgr);
262 else
263 return PathDiagnosticLocation(S, SMgr);
Ted Kremenekaf3e3d52009-03-28 03:37:59 +0000264 case Stmt::DoStmtClass:
Ted Kremenekaf3e3d52009-03-28 03:37:59 +0000265 return PathDiagnosticLocation(S, SMgr);
Ted Kremenekaf3e3d52009-03-28 03:37:59 +0000266 case Stmt::ForStmtClass:
267 if (cast<ForStmt>(Parent)->getBody() == S)
268 return PathDiagnosticLocation(S, SMgr);
269 break;
270 case Stmt::IfStmtClass:
271 if (cast<IfStmt>(Parent)->getCond() != S)
272 return PathDiagnosticLocation(S, SMgr);
Ted Kremenek8bd4d032009-04-28 04:23:15 +0000273 break;
Ted Kremenekaf3e3d52009-03-28 03:37:59 +0000274 case Stmt::ObjCForCollectionStmtClass:
275 if (cast<ObjCForCollectionStmt>(Parent)->getBody() == S)
276 return PathDiagnosticLocation(S, SMgr);
277 break;
278 case Stmt::WhileStmtClass:
279 if (cast<WhileStmt>(Parent)->getCond() != S)
280 return PathDiagnosticLocation(S, SMgr);
281 break;
282 default:
283 break;
284 }
285
Ted Kremenekd8c938b2009-03-27 21:16:25 +0000286 S = Parent;
287 }
288
289 assert(S && "Cannot have null Stmt for PathDiagnosticLocation");
Ted Kremeneke88a1702009-05-11 22:19:32 +0000290
291 // Special case: DeclStmts can appear in for statement declarations, in which
292 // case the ForStmt is the context.
293 if (isa<DeclStmt>(S)) {
294 if (const Stmt *Parent = P.getParent(S)) {
295 switch (Parent->getStmtClass()) {
296 case Stmt::ForStmtClass:
297 case Stmt::ObjCForCollectionStmtClass:
298 return PathDiagnosticLocation(Parent, SMgr);
299 default:
300 break;
301 }
302 }
303 }
304 else if (isa<BinaryOperator>(S)) {
305 // Special case: the binary operator represents the initialization
306 // code in a for statement (this can happen when the variable being
307 // initialized is an old variable.
308 if (const ForStmt *FS =
309 dyn_cast_or_null<ForStmt>(P.getParentIgnoreParens(S))) {
310 if (FS->getInit() == S)
311 return PathDiagnosticLocation(FS, SMgr);
312 }
313 }
314
Ted Kremenekd8c938b2009-03-27 21:16:25 +0000315 return PathDiagnosticLocation(S, SMgr);
316}
317
Ted Kremenekcf118d42009-02-04 23:49:09 +0000318//===----------------------------------------------------------------------===//
Ted Kremenek31061982009-03-31 23:00:32 +0000319// ScanNotableSymbols: closure-like callback for scanning Store bindings.
320//===----------------------------------------------------------------------===//
321
322static const VarDecl*
323GetMostRecentVarDeclBinding(const ExplodedNode<GRState>* N,
324 GRStateManager& VMgr, SVal X) {
325
326 for ( ; N ; N = N->pred_empty() ? 0 : *N->pred_begin()) {
327
328 ProgramPoint P = N->getLocation();
329
330 if (!isa<PostStmt>(P))
331 continue;
332
333 DeclRefExpr* DR = dyn_cast<DeclRefExpr>(cast<PostStmt>(P).getStmt());
334
335 if (!DR)
336 continue;
337
Ted Kremenek23ec48c2009-06-18 23:58:37 +0000338 SVal Y = N->getState()->getSVal(DR);
Ted Kremenek31061982009-03-31 23:00:32 +0000339
340 if (X != Y)
341 continue;
342
343 VarDecl* VD = dyn_cast<VarDecl>(DR->getDecl());
344
345 if (!VD)
346 continue;
347
348 return VD;
349 }
350
351 return 0;
352}
353
354namespace {
355class VISIBILITY_HIDDEN NotableSymbolHandler
356: public StoreManager::BindingsHandler {
357
358 SymbolRef Sym;
359 const GRState* PrevSt;
360 const Stmt* S;
361 GRStateManager& VMgr;
362 const ExplodedNode<GRState>* Pred;
363 PathDiagnostic& PD;
364 BugReporter& BR;
365
366public:
367
368 NotableSymbolHandler(SymbolRef sym, const GRState* prevst, const Stmt* s,
369 GRStateManager& vmgr, const ExplodedNode<GRState>* pred,
370 PathDiagnostic& pd, BugReporter& br)
371 : Sym(sym), PrevSt(prevst), S(s), VMgr(vmgr), Pred(pred), PD(pd), BR(br) {}
372
373 bool HandleBinding(StoreManager& SMgr, Store store, const MemRegion* R,
374 SVal V) {
375
376 SymbolRef ScanSym = V.getAsSymbol();
377
378 if (ScanSym != Sym)
379 return true;
380
381 // Check if the previous state has this binding.
Ted Kremenekdbc2afc2009-06-23 17:55:07 +0000382 SVal X = PrevSt->getSVal(loc::MemRegionVal(R));
Ted Kremenek31061982009-03-31 23:00:32 +0000383
384 if (X == V) // Same binding?
385 return true;
386
387 // Different binding. Only handle assignments for now. We don't pull
388 // this check out of the loop because we will eventually handle other
389 // cases.
390
391 VarDecl *VD = 0;
392
393 if (const BinaryOperator* B = dyn_cast<BinaryOperator>(S)) {
394 if (!B->isAssignmentOp())
395 return true;
396
397 // What variable did we assign to?
398 DeclRefExpr* DR = dyn_cast<DeclRefExpr>(B->getLHS()->IgnoreParenCasts());
399
400 if (!DR)
401 return true;
402
403 VD = dyn_cast<VarDecl>(DR->getDecl());
404 }
405 else if (const DeclStmt* DS = dyn_cast<DeclStmt>(S)) {
406 // FIXME: Eventually CFGs won't have DeclStmts. Right now we
407 // assume that each DeclStmt has a single Decl. This invariant
408 // holds by contruction in the CFG.
409 VD = dyn_cast<VarDecl>(*DS->decl_begin());
410 }
411
412 if (!VD)
413 return true;
414
415 // What is the most recently referenced variable with this binding?
416 const VarDecl* MostRecent = GetMostRecentVarDeclBinding(Pred, VMgr, V);
417
418 if (!MostRecent)
419 return true;
420
421 // Create the diagnostic.
422 FullSourceLoc L(S->getLocStart(), BR.getSourceManager());
423
424 if (Loc::IsLocType(VD->getType())) {
425 std::string msg = "'" + std::string(VD->getNameAsString()) +
426 "' now aliases '" + MostRecent->getNameAsString() + "'";
427
428 PD.push_front(new PathDiagnosticEventPiece(L, msg));
429 }
430
431 return true;
432 }
433};
434}
435
436static void HandleNotableSymbol(const ExplodedNode<GRState>* N,
437 const Stmt* S,
438 SymbolRef Sym, BugReporter& BR,
439 PathDiagnostic& PD) {
440
441 const ExplodedNode<GRState>* Pred = N->pred_empty() ? 0 : *N->pred_begin();
442 const GRState* PrevSt = Pred ? Pred->getState() : 0;
443
444 if (!PrevSt)
445 return;
446
447 // Look at the region bindings of the current state that map to the
448 // specified symbol. Are any of them not in the previous state?
449 GRStateManager& VMgr = cast<GRBugReporter>(BR).getStateManager();
450 NotableSymbolHandler H(Sym, PrevSt, S, VMgr, Pred, PD, BR);
451 cast<GRBugReporter>(BR).getStateManager().iterBindings(N->getState(), H);
452}
453
454namespace {
455class VISIBILITY_HIDDEN ScanNotableSymbols
456: public StoreManager::BindingsHandler {
457
458 llvm::SmallSet<SymbolRef, 10> AlreadyProcessed;
459 const ExplodedNode<GRState>* N;
460 Stmt* S;
461 GRBugReporter& BR;
462 PathDiagnostic& PD;
463
464public:
465 ScanNotableSymbols(const ExplodedNode<GRState>* n, Stmt* s, GRBugReporter& br,
466 PathDiagnostic& pd)
467 : N(n), S(s), BR(br), PD(pd) {}
468
469 bool HandleBinding(StoreManager& SMgr, Store store,
470 const MemRegion* R, SVal V) {
471
472 SymbolRef ScanSym = V.getAsSymbol();
473
474 if (!ScanSym)
475 return true;
476
477 if (!BR.isNotable(ScanSym))
478 return true;
479
480 if (AlreadyProcessed.count(ScanSym))
481 return true;
482
483 AlreadyProcessed.insert(ScanSym);
484
485 HandleNotableSymbol(N, S, ScanSym, BR, PD);
486 return true;
487 }
488};
489} // end anonymous namespace
490
491//===----------------------------------------------------------------------===//
492// "Minimal" path diagnostic generation algorithm.
493//===----------------------------------------------------------------------===//
494
Ted Kremenek14856d72009-04-06 23:06:54 +0000495static void CompactPathDiagnostic(PathDiagnostic &PD, const SourceManager& SM);
496
Ted Kremenek31061982009-03-31 23:00:32 +0000497static void GenerateMinimalPathDiagnostic(PathDiagnostic& PD,
498 PathDiagnosticBuilder &PDB,
499 const ExplodedNode<GRState> *N) {
Ted Kremenek8966bc12009-05-06 21:39:49 +0000500
Ted Kremenek31061982009-03-31 23:00:32 +0000501 SourceManager& SMgr = PDB.getSourceManager();
502 const ExplodedNode<GRState>* NextNode = N->pred_empty()
503 ? NULL : *(N->pred_begin());
504 while (NextNode) {
505 N = NextNode;
506 NextNode = GetPredecessorNode(N);
507
508 ProgramPoint P = N->getLocation();
509
510 if (const BlockEdge* BE = dyn_cast<BlockEdge>(&P)) {
511 CFGBlock* Src = BE->getSrc();
512 CFGBlock* Dst = BE->getDst();
513 Stmt* T = Src->getTerminator();
514
515 if (!T)
516 continue;
517
518 FullSourceLoc Start(T->getLocStart(), SMgr);
519
520 switch (T->getStmtClass()) {
521 default:
522 break;
523
524 case Stmt::GotoStmtClass:
525 case Stmt::IndirectGotoStmtClass: {
526 Stmt* S = GetNextStmt(N);
527
528 if (!S)
529 continue;
530
531 std::string sbuf;
532 llvm::raw_string_ostream os(sbuf);
533 const PathDiagnosticLocation &End = PDB.getEnclosingStmtLocation(S);
534
535 os << "Control jumps to line "
536 << End.asLocation().getInstantiationLineNumber();
537 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
538 os.str()));
539 break;
540 }
541
542 case Stmt::SwitchStmtClass: {
543 // Figure out what case arm we took.
544 std::string sbuf;
545 llvm::raw_string_ostream os(sbuf);
546
547 if (Stmt* S = Dst->getLabel()) {
548 PathDiagnosticLocation End(S, SMgr);
549
550 switch (S->getStmtClass()) {
551 default:
552 os << "No cases match in the switch statement. "
553 "Control jumps to line "
554 << End.asLocation().getInstantiationLineNumber();
555 break;
556 case Stmt::DefaultStmtClass:
557 os << "Control jumps to the 'default' case at line "
558 << End.asLocation().getInstantiationLineNumber();
559 break;
560
561 case Stmt::CaseStmtClass: {
562 os << "Control jumps to 'case ";
563 CaseStmt* Case = cast<CaseStmt>(S);
564 Expr* LHS = Case->getLHS()->IgnoreParenCasts();
565
566 // Determine if it is an enum.
567 bool GetRawInt = true;
568
569 if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(LHS)) {
570 // FIXME: Maybe this should be an assertion. Are there cases
571 // were it is not an EnumConstantDecl?
572 EnumConstantDecl* D =
573 dyn_cast<EnumConstantDecl>(DR->getDecl());
574
575 if (D) {
576 GetRawInt = false;
577 os << D->getNameAsString();
578 }
579 }
Eli Friedman9ec64d62009-04-26 19:04:51 +0000580
581 if (GetRawInt)
Ted Kremenek8966bc12009-05-06 21:39:49 +0000582 os << LHS->EvaluateAsInt(PDB.getASTContext());
Eli Friedman9ec64d62009-04-26 19:04:51 +0000583
Ted Kremenek31061982009-03-31 23:00:32 +0000584 os << ":' at line "
585 << End.asLocation().getInstantiationLineNumber();
586 break;
587 }
588 }
589 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
590 os.str()));
591 }
592 else {
593 os << "'Default' branch taken. ";
594 const PathDiagnosticLocation &End = PDB.ExecutionContinues(os, N);
595 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
596 os.str()));
597 }
598
599 break;
600 }
601
602 case Stmt::BreakStmtClass:
603 case Stmt::ContinueStmtClass: {
604 std::string sbuf;
605 llvm::raw_string_ostream os(sbuf);
606 PathDiagnosticLocation End = PDB.ExecutionContinues(os, N);
607 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
608 os.str()));
609 break;
610 }
611
612 // Determine control-flow for ternary '?'.
613 case Stmt::ConditionalOperatorClass: {
614 std::string sbuf;
615 llvm::raw_string_ostream os(sbuf);
616 os << "'?' condition is ";
617
618 if (*(Src->succ_begin()+1) == Dst)
619 os << "false";
620 else
621 os << "true";
622
623 PathDiagnosticLocation End = PDB.ExecutionContinues(N);
624
625 if (const Stmt *S = End.asStmt())
626 End = PDB.getEnclosingStmtLocation(S);
627
628 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
629 os.str()));
630 break;
631 }
632
633 // Determine control-flow for short-circuited '&&' and '||'.
634 case Stmt::BinaryOperatorClass: {
635 if (!PDB.supportsLogicalOpControlFlow())
636 break;
637
638 BinaryOperator *B = cast<BinaryOperator>(T);
639 std::string sbuf;
640 llvm::raw_string_ostream os(sbuf);
641 os << "Left side of '";
642
643 if (B->getOpcode() == BinaryOperator::LAnd) {
644 os << "&&" << "' is ";
645
646 if (*(Src->succ_begin()+1) == Dst) {
647 os << "false";
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 else {
654 os << "true";
655 PathDiagnosticLocation Start(B->getLHS(), SMgr);
656 PathDiagnosticLocation End = PDB.ExecutionContinues(N);
657 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
658 os.str()));
659 }
660 }
661 else {
662 assert(B->getOpcode() == BinaryOperator::LOr);
663 os << "||" << "' is ";
664
665 if (*(Src->succ_begin()+1) == Dst) {
666 os << "false";
667 PathDiagnosticLocation Start(B->getLHS(), SMgr);
668 PathDiagnosticLocation End = PDB.ExecutionContinues(N);
669 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
670 os.str()));
671 }
672 else {
673 os << "true";
674 PathDiagnosticLocation End(B->getLHS(), SMgr);
675 PathDiagnosticLocation Start(B->getOperatorLoc(), SMgr);
676 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
677 os.str()));
678 }
679 }
680
681 break;
682 }
683
684 case Stmt::DoStmtClass: {
685 if (*(Src->succ_begin()) == Dst) {
686 std::string sbuf;
687 llvm::raw_string_ostream os(sbuf);
688
689 os << "Loop condition is true. ";
690 PathDiagnosticLocation End = PDB.ExecutionContinues(os, N);
691
692 if (const Stmt *S = End.asStmt())
693 End = PDB.getEnclosingStmtLocation(S);
694
695 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
696 os.str()));
697 }
698 else {
699 PathDiagnosticLocation End = PDB.ExecutionContinues(N);
700
701 if (const Stmt *S = End.asStmt())
702 End = PDB.getEnclosingStmtLocation(S);
703
704 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
705 "Loop condition is false. Exiting loop"));
706 }
707
708 break;
709 }
710
711 case Stmt::WhileStmtClass:
712 case Stmt::ForStmtClass: {
713 if (*(Src->succ_begin()+1) == Dst) {
714 std::string sbuf;
715 llvm::raw_string_ostream os(sbuf);
716
717 os << "Loop condition is false. ";
718 PathDiagnosticLocation End = PDB.ExecutionContinues(os, N);
719 if (const Stmt *S = End.asStmt())
720 End = PDB.getEnclosingStmtLocation(S);
721
722 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
723 os.str()));
724 }
725 else {
726 PathDiagnosticLocation End = PDB.ExecutionContinues(N);
727 if (const Stmt *S = End.asStmt())
728 End = PDB.getEnclosingStmtLocation(S);
729
730 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000731 "Loop condition is true. Entering loop body"));
Ted Kremenek31061982009-03-31 23:00:32 +0000732 }
733
734 break;
735 }
736
737 case Stmt::IfStmtClass: {
738 PathDiagnosticLocation End = PDB.ExecutionContinues(N);
739
740 if (const Stmt *S = End.asStmt())
741 End = PDB.getEnclosingStmtLocation(S);
742
743 if (*(Src->succ_begin()+1) == Dst)
744 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000745 "Taking false branch"));
Ted Kremenek31061982009-03-31 23:00:32 +0000746 else
747 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000748 "Taking true branch"));
Ted Kremenek31061982009-03-31 23:00:32 +0000749
750 break;
751 }
752 }
753 }
754
Ted Kremenekdd986cc2009-05-07 00:45:33 +0000755 if (NextNode) {
756 for (BugReporterContext::visitor_iterator I = PDB.visitor_begin(),
757 E = PDB.visitor_end(); I!=E; ++I) {
758 if (PathDiagnosticPiece* p = (*I)->VisitNode(N, NextNode, PDB))
759 PD.push_front(p);
760 }
Ted Kremenek8966bc12009-05-06 21:39:49 +0000761 }
Ted Kremenek31061982009-03-31 23:00:32 +0000762
763 if (const PostStmt* PS = dyn_cast<PostStmt>(&P)) {
764 // Scan the region bindings, and see if a "notable" symbol has a new
765 // lval binding.
766 ScanNotableSymbols SNS(N, PS->getStmt(), PDB.getBugReporter(), PD);
767 PDB.getStateManager().iterBindings(N->getState(), SNS);
768 }
769 }
Ted Kremenek14856d72009-04-06 23:06:54 +0000770
771 // After constructing the full PathDiagnostic, do a pass over it to compact
772 // PathDiagnosticPieces that occur within a macro.
773 CompactPathDiagnostic(PD, PDB.getSourceManager());
Ted Kremenek31061982009-03-31 23:00:32 +0000774}
775
776//===----------------------------------------------------------------------===//
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000777// "Extensive" PathDiagnostic generation.
778//===----------------------------------------------------------------------===//
779
780static bool IsControlFlowExpr(const Stmt *S) {
781 const Expr *E = dyn_cast<Expr>(S);
Ted Kremenek14856d72009-04-06 23:06:54 +0000782
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000783 if (!E)
784 return false;
785
786 E = E->IgnoreParenCasts();
787
788 if (isa<ConditionalOperator>(E))
789 return true;
790
791 if (const BinaryOperator *B = dyn_cast<BinaryOperator>(E))
792 if (B->isLogicalOp())
793 return true;
794
795 return false;
796}
797
Ted Kremenek14856d72009-04-06 23:06:54 +0000798namespace {
Ted Kremenek8f9b1b32009-05-01 16:08:09 +0000799class VISIBILITY_HIDDEN ContextLocation : public PathDiagnosticLocation {
800 bool IsDead;
801public:
802 ContextLocation(const PathDiagnosticLocation &L, bool isdead = false)
803 : PathDiagnosticLocation(L), IsDead(isdead) {}
804
805 void markDead() { IsDead = true; }
806 bool isDead() const { return IsDead; }
807};
808
Ted Kremenek14856d72009-04-06 23:06:54 +0000809class VISIBILITY_HIDDEN EdgeBuilder {
Ted Kremenek8f9b1b32009-05-01 16:08:09 +0000810 std::vector<ContextLocation> CLocs;
811 typedef std::vector<ContextLocation>::iterator iterator;
Ted Kremenek14856d72009-04-06 23:06:54 +0000812 PathDiagnostic &PD;
813 PathDiagnosticBuilder &PDB;
814 PathDiagnosticLocation PrevLoc;
Ted Kremenek8f9b1b32009-05-01 16:08:09 +0000815
816 bool IsConsumedExpr(const PathDiagnosticLocation &L);
817
Ted Kremenek14856d72009-04-06 23:06:54 +0000818 bool containsLocation(const PathDiagnosticLocation &Container,
819 const PathDiagnosticLocation &Containee);
820
821 PathDiagnosticLocation getContextLocation(const PathDiagnosticLocation &L);
Ted Kremenek14856d72009-04-06 23:06:54 +0000822
Ted Kremenek9650cf32009-05-11 21:42:34 +0000823 PathDiagnosticLocation cleanUpLocation(PathDiagnosticLocation L,
824 bool firstCharOnly = false) {
Ted Kremenek8c8b0ad2009-05-11 19:50:47 +0000825 if (const Stmt *S = L.asStmt()) {
Ted Kremenek9650cf32009-05-11 21:42:34 +0000826 const Stmt *Original = S;
Ted Kremenek8c8b0ad2009-05-11 19:50:47 +0000827 while (1) {
828 // Adjust the location for some expressions that are best referenced
829 // by one of their subexpressions.
Ted Kremenek9650cf32009-05-11 21:42:34 +0000830 switch (S->getStmtClass()) {
831 default:
832 break;
833 case Stmt::ParenExprClass:
834 S = cast<ParenExpr>(S)->IgnoreParens();
835 firstCharOnly = true;
836 continue;
837 case Stmt::ConditionalOperatorClass:
838 S = cast<ConditionalOperator>(S)->getCond();
839 firstCharOnly = true;
840 continue;
841 case Stmt::ChooseExprClass:
842 S = cast<ChooseExpr>(S)->getCond();
843 firstCharOnly = true;
844 continue;
845 case Stmt::BinaryOperatorClass:
846 S = cast<BinaryOperator>(S)->getLHS();
847 firstCharOnly = true;
848 continue;
849 }
850
851 break;
Ted Kremenek8c8b0ad2009-05-11 19:50:47 +0000852 }
853
Ted Kremenek9650cf32009-05-11 21:42:34 +0000854 if (S != Original)
855 L = PathDiagnosticLocation(S, L.getManager());
Ted Kremenek8c8b0ad2009-05-11 19:50:47 +0000856 }
857
Ted Kremenek9650cf32009-05-11 21:42:34 +0000858 if (firstCharOnly)
859 L = PathDiagnosticLocation(L.asLocation());
860
Ted Kremenek8c8b0ad2009-05-11 19:50:47 +0000861 return L;
862 }
863
Ted Kremenek14856d72009-04-06 23:06:54 +0000864 void popLocation() {
Ted Kremenek8f9b1b32009-05-01 16:08:09 +0000865 if (!CLocs.back().isDead() && CLocs.back().asLocation().isFileID()) {
Ted Kremenek5c7168c2009-04-22 20:36:26 +0000866 // For contexts, we only one the first character as the range.
Ted Kremenek07c015c2009-05-15 02:46:13 +0000867 rawAddEdge(cleanUpLocation(CLocs.back(), true));
Ted Kremenek5c7168c2009-04-22 20:36:26 +0000868 }
Ted Kremenek14856d72009-04-06 23:06:54 +0000869 CLocs.pop_back();
870 }
871
872 PathDiagnosticLocation IgnoreParens(const PathDiagnosticLocation &L);
873
874public:
875 EdgeBuilder(PathDiagnostic &pd, PathDiagnosticBuilder &pdb)
876 : PD(pd), PDB(pdb) {
Ted Kremeneka301a672009-04-22 18:16:20 +0000877
878 // If the PathDiagnostic already has pieces, add the enclosing statement
879 // of the first piece as a context as well.
Ted Kremenek14856d72009-04-06 23:06:54 +0000880 if (!PD.empty()) {
881 PrevLoc = PD.begin()->getLocation();
882
883 if (const Stmt *S = PrevLoc.asStmt())
Ted Kremeneke1baed32009-05-05 23:13:38 +0000884 addExtendedContext(PDB.getEnclosingStmtLocation(S).asStmt());
Ted Kremenek14856d72009-04-06 23:06:54 +0000885 }
886 }
887
888 ~EdgeBuilder() {
889 while (!CLocs.empty()) popLocation();
Ted Kremeneka301a672009-04-22 18:16:20 +0000890
891 // Finally, add an initial edge from the start location of the first
892 // statement (if it doesn't already exist).
Sebastian Redld3a413d2009-04-26 20:35:05 +0000893 // FIXME: Should handle CXXTryStmt if analyser starts supporting C++.
894 if (const CompoundStmt *CS =
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +0000895 PDB.getCodeDecl().getCompoundBody())
Ted Kremeneka301a672009-04-22 18:16:20 +0000896 if (!CS->body_empty()) {
897 SourceLocation Loc = (*CS->body_begin())->getLocStart();
898 rawAddEdge(PathDiagnosticLocation(Loc, PDB.getSourceManager()));
899 }
900
Ted Kremenek14856d72009-04-06 23:06:54 +0000901 }
902
903 void addEdge(PathDiagnosticLocation NewLoc, bool alwaysAdd = false);
904
905 void addEdge(const Stmt *S, bool alwaysAdd = false) {
906 addEdge(PathDiagnosticLocation(S, PDB.getSourceManager()), alwaysAdd);
907 }
908
Ted Kremenek8bd4d032009-04-28 04:23:15 +0000909 void rawAddEdge(PathDiagnosticLocation NewLoc);
910
Ted Kremenek14856d72009-04-06 23:06:54 +0000911 void addContext(const Stmt *S);
Ted Kremeneke1baed32009-05-05 23:13:38 +0000912 void addExtendedContext(const Stmt *S);
Ted Kremenek14856d72009-04-06 23:06:54 +0000913};
914} // end anonymous namespace
915
916
917PathDiagnosticLocation
918EdgeBuilder::getContextLocation(const PathDiagnosticLocation &L) {
919 if (const Stmt *S = L.asStmt()) {
920 if (IsControlFlowExpr(S))
921 return L;
922
923 return PDB.getEnclosingStmtLocation(S);
924 }
925
926 return L;
927}
928
929bool EdgeBuilder::containsLocation(const PathDiagnosticLocation &Container,
930 const PathDiagnosticLocation &Containee) {
931
932 if (Container == Containee)
933 return true;
934
935 if (Container.asDecl())
936 return true;
937
938 if (const Stmt *S = Containee.asStmt())
939 if (const Stmt *ContainerS = Container.asStmt()) {
940 while (S) {
941 if (S == ContainerS)
942 return true;
943 S = PDB.getParent(S);
944 }
945 return false;
946 }
947
948 // Less accurate: compare using source ranges.
949 SourceRange ContainerR = Container.asRange();
950 SourceRange ContaineeR = Containee.asRange();
951
952 SourceManager &SM = PDB.getSourceManager();
953 SourceLocation ContainerRBeg = SM.getInstantiationLoc(ContainerR.getBegin());
954 SourceLocation ContainerREnd = SM.getInstantiationLoc(ContainerR.getEnd());
955 SourceLocation ContaineeRBeg = SM.getInstantiationLoc(ContaineeR.getBegin());
956 SourceLocation ContaineeREnd = SM.getInstantiationLoc(ContaineeR.getEnd());
957
958 unsigned ContainerBegLine = SM.getInstantiationLineNumber(ContainerRBeg);
959 unsigned ContainerEndLine = SM.getInstantiationLineNumber(ContainerREnd);
960 unsigned ContaineeBegLine = SM.getInstantiationLineNumber(ContaineeRBeg);
961 unsigned ContaineeEndLine = SM.getInstantiationLineNumber(ContaineeREnd);
962
963 assert(ContainerBegLine <= ContainerEndLine);
964 assert(ContaineeBegLine <= ContaineeEndLine);
965
966 return (ContainerBegLine <= ContaineeBegLine &&
967 ContainerEndLine >= ContaineeEndLine &&
968 (ContainerBegLine != ContaineeBegLine ||
969 SM.getInstantiationColumnNumber(ContainerRBeg) <=
970 SM.getInstantiationColumnNumber(ContaineeRBeg)) &&
971 (ContainerEndLine != ContaineeEndLine ||
972 SM.getInstantiationColumnNumber(ContainerREnd) >=
973 SM.getInstantiationColumnNumber(ContainerREnd)));
974}
975
976PathDiagnosticLocation
977EdgeBuilder::IgnoreParens(const PathDiagnosticLocation &L) {
978 if (const Expr* E = dyn_cast_or_null<Expr>(L.asStmt()))
979 return PathDiagnosticLocation(E->IgnoreParenCasts(),
980 PDB.getSourceManager());
981 return L;
982}
983
984void EdgeBuilder::rawAddEdge(PathDiagnosticLocation NewLoc) {
985 if (!PrevLoc.isValid()) {
986 PrevLoc = NewLoc;
987 return;
988 }
989
Ted Kremenek8c8b0ad2009-05-11 19:50:47 +0000990 const PathDiagnosticLocation &NewLocClean = cleanUpLocation(NewLoc);
991 const PathDiagnosticLocation &PrevLocClean = cleanUpLocation(PrevLoc);
992
993 if (NewLocClean.asLocation() == PrevLocClean.asLocation())
Ted Kremenek14856d72009-04-06 23:06:54 +0000994 return;
995
996 // FIXME: Ignore intra-macro edges for now.
Ted Kremenek8c8b0ad2009-05-11 19:50:47 +0000997 if (NewLocClean.asLocation().getInstantiationLoc() ==
998 PrevLocClean.asLocation().getInstantiationLoc())
Ted Kremenek14856d72009-04-06 23:06:54 +0000999 return;
1000
Ted Kremenek8c8b0ad2009-05-11 19:50:47 +00001001 PD.push_front(new PathDiagnosticControlFlowPiece(NewLocClean, PrevLocClean));
1002 PrevLoc = NewLoc;
Ted Kremenek14856d72009-04-06 23:06:54 +00001003}
1004
1005void EdgeBuilder::addEdge(PathDiagnosticLocation NewLoc, bool alwaysAdd) {
Ted Kremeneka301a672009-04-22 18:16:20 +00001006
1007 if (!alwaysAdd && NewLoc.asLocation().isMacroID())
1008 return;
1009
Ted Kremenek14856d72009-04-06 23:06:54 +00001010 const PathDiagnosticLocation &CLoc = getContextLocation(NewLoc);
1011
1012 while (!CLocs.empty()) {
Ted Kremenek8f9b1b32009-05-01 16:08:09 +00001013 ContextLocation &TopContextLoc = CLocs.back();
Ted Kremenek14856d72009-04-06 23:06:54 +00001014
1015 // Is the top location context the same as the one for the new location?
1016 if (TopContextLoc == CLoc) {
Ted Kremenek8f9b1b32009-05-01 16:08:09 +00001017 if (alwaysAdd) {
Ted Kremenek4c6f8d32009-05-04 18:15:17 +00001018 if (IsConsumedExpr(TopContextLoc) &&
1019 !IsControlFlowExpr(TopContextLoc.asStmt()))
Ted Kremenek8f9b1b32009-05-01 16:08:09 +00001020 TopContextLoc.markDead();
1021
Ted Kremenek14856d72009-04-06 23:06:54 +00001022 rawAddEdge(NewLoc);
Ted Kremenek8f9b1b32009-05-01 16:08:09 +00001023 }
Ted Kremenek14856d72009-04-06 23:06:54 +00001024
1025 return;
1026 }
1027
1028 if (containsLocation(TopContextLoc, CLoc)) {
Ted Kremenek8f9b1b32009-05-01 16:08:09 +00001029 if (alwaysAdd) {
Ted Kremenek14856d72009-04-06 23:06:54 +00001030 rawAddEdge(NewLoc);
Ted Kremenek8f9b1b32009-05-01 16:08:09 +00001031
Ted Kremenek4c6f8d32009-05-04 18:15:17 +00001032 if (IsConsumedExpr(CLoc) && !IsControlFlowExpr(CLoc.asStmt())) {
Ted Kremenek8f9b1b32009-05-01 16:08:09 +00001033 CLocs.push_back(ContextLocation(CLoc, true));
1034 return;
1035 }
1036 }
1037
Ted Kremenek14856d72009-04-06 23:06:54 +00001038 CLocs.push_back(CLoc);
1039 return;
1040 }
1041
1042 // Context does not contain the location. Flush it.
1043 popLocation();
1044 }
Ted Kremenek5c7168c2009-04-22 20:36:26 +00001045
1046 // If we reach here, there is no enclosing context. Just add the edge.
1047 rawAddEdge(NewLoc);
Ted Kremenek14856d72009-04-06 23:06:54 +00001048}
1049
Ted Kremenek8f9b1b32009-05-01 16:08:09 +00001050bool EdgeBuilder::IsConsumedExpr(const PathDiagnosticLocation &L) {
1051 if (const Expr *X = dyn_cast_or_null<Expr>(L.asStmt()))
1052 return PDB.getParentMap().isConsumedExpr(X) && !IsControlFlowExpr(X);
1053
1054 return false;
1055}
1056
Ted Kremeneke1baed32009-05-05 23:13:38 +00001057void EdgeBuilder::addExtendedContext(const Stmt *S) {
1058 if (!S)
1059 return;
1060
1061 const Stmt *Parent = PDB.getParent(S);
1062 while (Parent) {
1063 if (isa<CompoundStmt>(Parent))
1064 Parent = PDB.getParent(Parent);
1065 else
1066 break;
1067 }
1068
1069 if (Parent) {
1070 switch (Parent->getStmtClass()) {
1071 case Stmt::DoStmtClass:
1072 case Stmt::ObjCAtSynchronizedStmtClass:
1073 addContext(Parent);
1074 default:
1075 break;
1076 }
1077 }
1078
1079 addContext(S);
1080}
1081
Ted Kremenek14856d72009-04-06 23:06:54 +00001082void EdgeBuilder::addContext(const Stmt *S) {
1083 if (!S)
1084 return;
1085
1086 PathDiagnosticLocation L(S, PDB.getSourceManager());
1087
1088 while (!CLocs.empty()) {
1089 const PathDiagnosticLocation &TopContextLoc = CLocs.back();
1090
1091 // Is the top location context the same as the one for the new location?
1092 if (TopContextLoc == L)
1093 return;
1094
1095 if (containsLocation(TopContextLoc, L)) {
Ted Kremenek14856d72009-04-06 23:06:54 +00001096 CLocs.push_back(L);
1097 return;
1098 }
1099
1100 // Context does not contain the location. Flush it.
1101 popLocation();
1102 }
1103
1104 CLocs.push_back(L);
1105}
1106
1107static void GenerateExtensivePathDiagnostic(PathDiagnostic& PD,
1108 PathDiagnosticBuilder &PDB,
1109 const ExplodedNode<GRState> *N) {
1110
1111
1112 EdgeBuilder EB(PD, PDB);
1113
1114 const ExplodedNode<GRState>* NextNode = N->pred_empty()
1115 ? NULL : *(N->pred_begin());
Ted Kremenek14856d72009-04-06 23:06:54 +00001116 while (NextNode) {
1117 N = NextNode;
1118 NextNode = GetPredecessorNode(N);
1119 ProgramPoint P = N->getLocation();
1120
Ted Kremenekdd986cc2009-05-07 00:45:33 +00001121 do {
1122 // Block edges.
1123 if (const BlockEdge *BE = dyn_cast<BlockEdge>(&P)) {
1124 const CFGBlock &Blk = *BE->getSrc();
1125 const Stmt *Term = Blk.getTerminator();
1126
Ted Kremenekdd986cc2009-05-07 00:45:33 +00001127 // Are we jumping to the head of a loop? Add a special diagnostic.
Ted Kremenekddb7bab2009-05-15 01:50:15 +00001128 if (const Stmt *Loop = BE->getDst()->getLoopTarget()) {
Ted Kremenekdd986cc2009-05-07 00:45:33 +00001129 PathDiagnosticLocation L(Loop, PDB.getSourceManager());
Ted Kremenekddb7bab2009-05-15 01:50:15 +00001130 const CompoundStmt *CS = NULL;
1131
1132 if (!Term) {
1133 if (const ForStmt *FS = dyn_cast<ForStmt>(Loop))
1134 CS = dyn_cast<CompoundStmt>(FS->getBody());
1135 else if (const WhileStmt *WS = dyn_cast<WhileStmt>(Loop))
1136 CS = dyn_cast<CompoundStmt>(WS->getBody());
1137 }
1138
Ted Kremenekdd986cc2009-05-07 00:45:33 +00001139 PathDiagnosticEventPiece *p =
1140 new PathDiagnosticEventPiece(L,
Ted Kremenek07c015c2009-05-15 02:46:13 +00001141 "Looping back to the head of the loop");
Ted Kremenekdd986cc2009-05-07 00:45:33 +00001142
1143 EB.addEdge(p->getLocation(), true);
1144 PD.push_front(p);
1145
Ted Kremenekddb7bab2009-05-15 01:50:15 +00001146 if (CS) {
Ted Kremenek07c015c2009-05-15 02:46:13 +00001147 PathDiagnosticLocation BL(CS->getRBracLoc(),
1148 PDB.getSourceManager());
1149 BL = PathDiagnosticLocation(BL.asLocation());
1150 EB.addEdge(BL);
Ted Kremenekdd986cc2009-05-07 00:45:33 +00001151 }
Ted Kremenek8bd4d032009-04-28 04:23:15 +00001152 }
Ted Kremenekddb7bab2009-05-15 01:50:15 +00001153
1154 if (Term)
1155 EB.addContext(Term);
Ted Kremenekdd986cc2009-05-07 00:45:33 +00001156
1157 break;
Ted Kremenek14856d72009-04-06 23:06:54 +00001158 }
1159
Ted Kremenekdd986cc2009-05-07 00:45:33 +00001160 if (const BlockEntrance *BE = dyn_cast<BlockEntrance>(&P)) {
1161 if (const Stmt* S = BE->getFirstStmt()) {
1162 if (IsControlFlowExpr(S)) {
1163 // Add the proper context for '&&', '||', and '?'.
1164 EB.addContext(S);
1165 }
1166 else
1167 EB.addExtendedContext(PDB.getEnclosingStmtLocation(S).asStmt());
1168 }
1169
1170 break;
1171 }
1172 } while (0);
1173
1174 if (!NextNode)
Ted Kremenek14856d72009-04-06 23:06:54 +00001175 continue;
Ted Kremenek14856d72009-04-06 23:06:54 +00001176
Ted Kremenek8966bc12009-05-06 21:39:49 +00001177 for (BugReporterContext::visitor_iterator I = PDB.visitor_begin(),
1178 E = PDB.visitor_end(); I!=E; ++I) {
1179 if (PathDiagnosticPiece* p = (*I)->VisitNode(N, NextNode, PDB)) {
1180 const PathDiagnosticLocation &Loc = p->getLocation();
1181 EB.addEdge(Loc, true);
1182 PD.push_front(p);
1183 if (const Stmt *S = Loc.asStmt())
1184 EB.addExtendedContext(PDB.getEnclosingStmtLocation(S).asStmt());
1185 }
1186 }
Ted Kremenek14856d72009-04-06 23:06:54 +00001187 }
1188}
1189
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +00001190//===----------------------------------------------------------------------===//
Ted Kremenekcf118d42009-02-04 23:49:09 +00001191// Methods for BugType and subclasses.
1192//===----------------------------------------------------------------------===//
1193BugType::~BugType() {}
1194void BugType::FlushReports(BugReporter &BR) {}
Ted Kremenekbb77e9b2008-05-01 22:50:36 +00001195
Ted Kremenekcf118d42009-02-04 23:49:09 +00001196//===----------------------------------------------------------------------===//
1197// Methods for BugReport and subclasses.
1198//===----------------------------------------------------------------------===//
1199BugReport::~BugReport() {}
1200RangedBugReport::~RangedBugReport() {}
1201
1202Stmt* BugReport::getStmt(BugReporter& BR) const {
Ted Kremenek200ed922008-05-02 23:21:21 +00001203 ProgramPoint ProgP = EndNode->getLocation();
Ted Kremenekbd7efa82008-04-17 23:44:37 +00001204 Stmt *S = NULL;
1205
Ted Kremenekcf118d42009-02-04 23:49:09 +00001206 if (BlockEntrance* BE = dyn_cast<BlockEntrance>(&ProgP)) {
Ted Kremenekb697b102009-02-23 22:44:26 +00001207 if (BE->getBlock() == &BR.getCFG()->getExit()) S = GetPreviousStmt(EndNode);
Ted Kremenekcf118d42009-02-04 23:49:09 +00001208 }
1209 if (!S) S = GetStmt(ProgP);
1210
Ted Kremenekbb77e9b2008-05-01 22:50:36 +00001211 return S;
1212}
1213
1214PathDiagnosticPiece*
Ted Kremenek8966bc12009-05-06 21:39:49 +00001215BugReport::getEndPath(BugReporterContext& BRC,
Ted Kremenek3148eb42009-01-24 00:55:43 +00001216 const ExplodedNode<GRState>* EndPathNode) {
Ted Kremenekbb77e9b2008-05-01 22:50:36 +00001217
Ted Kremenek8966bc12009-05-06 21:39:49 +00001218 Stmt* S = getStmt(BRC.getBugReporter());
Ted Kremenek61f3e052008-04-03 04:42:52 +00001219
1220 if (!S)
1221 return NULL;
Ted Kremenek3ef538d2009-05-11 23:50:59 +00001222
Ted Kremenekde7161f2008-04-03 18:00:37 +00001223 const SourceRange *Beg, *End;
Ted Kremenek3ef538d2009-05-11 23:50:59 +00001224 getRanges(BRC.getBugReporter(), Beg, End);
1225 PathDiagnosticLocation L(S, BRC.getSourceManager());
Ted Kremenekcf118d42009-02-04 23:49:09 +00001226
Ted Kremenek3ef538d2009-05-11 23:50:59 +00001227 // Only add the statement itself as a range if we didn't specify any
1228 // special ranges for this report.
1229 PathDiagnosticPiece* P = new PathDiagnosticEventPiece(L, getDescription(),
1230 Beg == End);
1231
Ted Kremenekbb77e9b2008-05-01 22:50:36 +00001232 for (; Beg != End; ++Beg)
1233 P->addRange(*Beg);
Ted Kremenek61f3e052008-04-03 04:42:52 +00001234
1235 return P;
1236}
1237
Ted Kremenekbb77e9b2008-05-01 22:50:36 +00001238void BugReport::getRanges(BugReporter& BR, const SourceRange*& beg,
1239 const SourceRange*& end) {
1240
1241 if (Expr* E = dyn_cast_or_null<Expr>(getStmt(BR))) {
1242 R = E->getSourceRange();
Ted Kremenek9b5e5052009-02-27 20:05:10 +00001243 assert(R.isValid());
Ted Kremenekbb77e9b2008-05-01 22:50:36 +00001244 beg = &R;
1245 end = beg+1;
1246 }
1247 else
1248 beg = end = 0;
Ted Kremenekf1ae7052008-04-03 17:57:38 +00001249}
1250
Ted Kremenekcf118d42009-02-04 23:49:09 +00001251SourceLocation BugReport::getLocation() const {
1252 if (EndNode)
Ted Kremenek9b5e5052009-02-27 20:05:10 +00001253 if (Stmt* S = GetCurrentOrPreviousStmt(EndNode)) {
1254 // For member expressions, return the location of the '.' or '->'.
1255 if (MemberExpr* ME = dyn_cast<MemberExpr>(S))
1256 return ME->getMemberLoc();
1257
Ted Kremenekcf118d42009-02-04 23:49:09 +00001258 return S->getLocStart();
Ted Kremenek9b5e5052009-02-27 20:05:10 +00001259 }
Ted Kremenekcf118d42009-02-04 23:49:09 +00001260
1261 return FullSourceLoc();
Ted Kremenekd2f642b2008-04-14 17:39:48 +00001262}
1263
Ted Kremenek3148eb42009-01-24 00:55:43 +00001264PathDiagnosticPiece* BugReport::VisitNode(const ExplodedNode<GRState>* N,
1265 const ExplodedNode<GRState>* PrevN,
Ted Kremenek8966bc12009-05-06 21:39:49 +00001266 BugReporterContext &BRC) {
Ted Kremenek50a6d0c2008-04-09 21:41:14 +00001267 return NULL;
1268}
1269
Ted Kremenekcf118d42009-02-04 23:49:09 +00001270//===----------------------------------------------------------------------===//
1271// Methods for BugReporter and subclasses.
1272//===----------------------------------------------------------------------===//
1273
1274BugReportEquivClass::~BugReportEquivClass() {
Ted Kremenek8966bc12009-05-06 21:39:49 +00001275 for (iterator I=begin(), E=end(); I!=E; ++I) delete *I;
Ted Kremenekcf118d42009-02-04 23:49:09 +00001276}
1277
1278GRBugReporter::~GRBugReporter() { FlushReports(); }
1279BugReporterData::~BugReporterData() {}
1280
1281ExplodedGraph<GRState>&
1282GRBugReporter::getGraph() { return Eng.getGraph(); }
1283
1284GRStateManager&
1285GRBugReporter::getStateManager() { return Eng.getStateManager(); }
1286
1287BugReporter::~BugReporter() { FlushReports(); }
1288
1289void BugReporter::FlushReports() {
1290 if (BugTypes.isEmpty())
1291 return;
1292
1293 // First flush the warnings for each BugType. This may end up creating new
1294 // warnings and new BugTypes. Because ImmutableSet is a functional data
1295 // structure, we do not need to worry about the iterators being invalidated.
1296 for (BugTypesTy::iterator I=BugTypes.begin(), E=BugTypes.end(); I!=E; ++I)
1297 const_cast<BugType*>(*I)->FlushReports(*this);
1298
1299 // Iterate through BugTypes a second time. BugTypes may have been updated
1300 // with new BugType objects and new warnings.
1301 for (BugTypesTy::iterator I=BugTypes.begin(), E=BugTypes.end(); I!=E; ++I) {
1302 BugType *BT = const_cast<BugType*>(*I);
1303
1304 typedef llvm::FoldingSet<BugReportEquivClass> SetTy;
1305 SetTy& EQClasses = BT->EQClasses;
1306
1307 for (SetTy::iterator EI=EQClasses.begin(), EE=EQClasses.end(); EI!=EE;++EI){
1308 BugReportEquivClass& EQ = *EI;
1309 FlushReport(EQ);
1310 }
Ted Kremeneka43a1eb2008-04-23 23:02:12 +00001311
Ted Kremenekcf118d42009-02-04 23:49:09 +00001312 // Delete the BugType object. This will also delete the equivalence
1313 // classes.
1314 delete BT;
Ted Kremenek94826a72008-04-03 04:59:14 +00001315 }
Ted Kremenekcf118d42009-02-04 23:49:09 +00001316
1317 // Remove all references to the BugType objects.
1318 BugTypes = F.GetEmptySet();
1319}
1320
1321//===----------------------------------------------------------------------===//
1322// PathDiagnostics generation.
1323//===----------------------------------------------------------------------===//
1324
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001325static std::pair<std::pair<ExplodedGraph<GRState>*, NodeBackMap*>,
Ted Kremenekcf118d42009-02-04 23:49:09 +00001326 std::pair<ExplodedNode<GRState>*, unsigned> >
1327MakeReportGraph(const ExplodedGraph<GRState>* G,
1328 const ExplodedNode<GRState>** NStart,
1329 const ExplodedNode<GRState>** NEnd) {
Ted Kremenek94826a72008-04-03 04:59:14 +00001330
Ted Kremenekcf118d42009-02-04 23:49:09 +00001331 // Create the trimmed graph. It will contain the shortest paths from the
1332 // error nodes to the root. In the new graph we should only have one
1333 // error node unless there are two or more error nodes with the same minimum
1334 // path length.
1335 ExplodedGraph<GRState>* GTrim;
1336 InterExplodedGraphMap<GRState>* NMap;
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001337
1338 llvm::DenseMap<const void*, const void*> InverseMap;
1339 llvm::tie(GTrim, NMap) = G->Trim(NStart, NEnd, &InverseMap);
Ted Kremenekcf118d42009-02-04 23:49:09 +00001340
1341 // Create owning pointers for GTrim and NMap just to ensure that they are
1342 // released when this function exists.
1343 llvm::OwningPtr<ExplodedGraph<GRState> > AutoReleaseGTrim(GTrim);
1344 llvm::OwningPtr<InterExplodedGraphMap<GRState> > AutoReleaseNMap(NMap);
1345
1346 // Find the (first) error node in the trimmed graph. We just need to consult
1347 // the node map (NMap) which maps from nodes in the original graph to nodes
1348 // in the new graph.
Ted Kremenek938332c2009-05-16 01:11:58 +00001349
1350 std::queue<const ExplodedNode<GRState>*> WS;
1351 typedef llvm::DenseMap<const ExplodedNode<GRState>*,unsigned> IndexMapTy;
1352 IndexMapTy IndexMap;
Ted Kremenekcf118d42009-02-04 23:49:09 +00001353
1354 for (const ExplodedNode<GRState>** I = NStart; I != NEnd; ++I)
Ted Kremenek938332c2009-05-16 01:11:58 +00001355 if (const ExplodedNode<GRState> *N = NMap->getMappedNode(*I)) {
1356 unsigned NodeIndex = (I - NStart) / sizeof(*I);
1357 WS.push(N);
1358 IndexMap[*I] = NodeIndex;
Ted Kremenekcf118d42009-02-04 23:49:09 +00001359 }
1360
Ted Kremenek938332c2009-05-16 01:11:58 +00001361 assert(!WS.empty() && "No error node found in the trimmed graph.");
Ted Kremenekcf118d42009-02-04 23:49:09 +00001362
1363 // Create a new (third!) graph with a single path. This is the graph
1364 // that will be returned to the caller.
Ted Kremenek3148eb42009-01-24 00:55:43 +00001365 ExplodedGraph<GRState> *GNew =
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001366 new ExplodedGraph<GRState>(GTrim->getCFG(), GTrim->getCodeDecl(),
1367 GTrim->getContext());
Ted Kremenekcf118d42009-02-04 23:49:09 +00001368
Ted Kremenek10aa5542009-03-12 23:41:59 +00001369 // Sometimes the trimmed graph can contain a cycle. Perform a reverse BFS
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001370 // to the root node, and then construct a new graph that contains only
1371 // a single path.
Ted Kremenek3148eb42009-01-24 00:55:43 +00001372 llvm::DenseMap<const void*,unsigned> Visited;
Ted Kremenek10aa5542009-03-12 23:41:59 +00001373
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001374 unsigned cnt = 0;
Ted Kremenek3148eb42009-01-24 00:55:43 +00001375 const ExplodedNode<GRState>* Root = 0;
Ted Kremenekc1da4412008-06-17 19:14:06 +00001376
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001377 while (!WS.empty()) {
Ted Kremenek10aa5542009-03-12 23:41:59 +00001378 const ExplodedNode<GRState>* Node = WS.front();
1379 WS.pop();
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001380
1381 if (Visited.find(Node) != Visited.end())
1382 continue;
1383
1384 Visited[Node] = cnt++;
1385
1386 if (Node->pred_empty()) {
1387 Root = Node;
1388 break;
1389 }
1390
Ted Kremenek3148eb42009-01-24 00:55:43 +00001391 for (ExplodedNode<GRState>::const_pred_iterator I=Node->pred_begin(),
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001392 E=Node->pred_end(); I!=E; ++I)
Ted Kremenek10aa5542009-03-12 23:41:59 +00001393 WS.push(*I);
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001394 }
Ted Kremenekcf118d42009-02-04 23:49:09 +00001395
Ted Kremenek938332c2009-05-16 01:11:58 +00001396 assert(Root);
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001397
Ted Kremenek10aa5542009-03-12 23:41:59 +00001398 // Now walk from the root down the BFS path, always taking the successor
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001399 // with the lowest number.
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001400 ExplodedNode<GRState> *Last = 0, *First = 0;
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001401 NodeBackMap *BM = new NodeBackMap();
Ted Kremenek938332c2009-05-16 01:11:58 +00001402 unsigned NodeIndex = 0;
Ted Kremenekcf118d42009-02-04 23:49:09 +00001403
Ted Kremenek938332c2009-05-16 01:11:58 +00001404 for ( const ExplodedNode<GRState> *N = Root ;;) {
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001405 // Lookup the number associated with the current node.
Ted Kremenek3148eb42009-01-24 00:55:43 +00001406 llvm::DenseMap<const void*,unsigned>::iterator I = Visited.find(N);
Ted Kremenek938332c2009-05-16 01:11:58 +00001407 assert(I != Visited.end());
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001408
1409 // Create the equivalent node in the new graph with the same state
1410 // and location.
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001411 ExplodedNode<GRState>* NewN =
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001412 GNew->getNode(N->getLocation(), N->getState());
1413
1414 // Store the mapping to the original node.
1415 llvm::DenseMap<const void*, const void*>::iterator IMitr=InverseMap.find(N);
1416 assert(IMitr != InverseMap.end() && "No mapping to original node.");
1417 (*BM)[NewN] = (const ExplodedNode<GRState>*) IMitr->second;
Ted Kremenekcf118d42009-02-04 23:49:09 +00001418
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001419 // Link up the new node with the previous node.
1420 if (Last)
1421 NewN->addPredecessor(Last);
Ted Kremeneka43a1eb2008-04-23 23:02:12 +00001422
1423 Last = NewN;
Ted Kremenekcf118d42009-02-04 23:49:09 +00001424
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001425 // Are we at the final node?
Ted Kremenek938332c2009-05-16 01:11:58 +00001426 IndexMapTy::iterator IMI =
1427 IndexMap.find((const ExplodedNode<GRState>*)(IMitr->second));
1428 if (IMI != IndexMap.end()) {
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001429 First = NewN;
Ted Kremenek938332c2009-05-16 01:11:58 +00001430 NodeIndex = IMI->second;
Ted Kremenekc1da4412008-06-17 19:14:06 +00001431 break;
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001432 }
Ted Kremenekcf118d42009-02-04 23:49:09 +00001433
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001434 // Find the next successor node. We choose the node that is marked
1435 // with the lowest DFS number.
Ted Kremenek3148eb42009-01-24 00:55:43 +00001436 ExplodedNode<GRState>::const_succ_iterator SI = N->succ_begin();
1437 ExplodedNode<GRState>::const_succ_iterator SE = N->succ_end();
Ted Kremenekc1da4412008-06-17 19:14:06 +00001438 N = 0;
1439
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001440 for (unsigned MinVal = 0; SI != SE; ++SI) {
Ted Kremenekcf118d42009-02-04 23:49:09 +00001441
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001442 I = Visited.find(*SI);
1443
1444 if (I == Visited.end())
1445 continue;
1446
1447 if (!N || I->second < MinVal) {
1448 N = *SI;
1449 MinVal = I->second;
Ted Kremenekc1da4412008-06-17 19:14:06 +00001450 }
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001451 }
Ted Kremenekcf118d42009-02-04 23:49:09 +00001452
Ted Kremenek938332c2009-05-16 01:11:58 +00001453 assert(N);
Ted Kremeneka43a1eb2008-04-23 23:02:12 +00001454 }
Ted Kremenekcf118d42009-02-04 23:49:09 +00001455
Ted Kremenek938332c2009-05-16 01:11:58 +00001456 assert(First);
1457
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001458 return std::make_pair(std::make_pair(GNew, BM),
1459 std::make_pair(First, NodeIndex));
Ted Kremeneka43a1eb2008-04-23 23:02:12 +00001460}
1461
Ted Kremenek0e5c8d42009-03-10 05:16:17 +00001462/// CompactPathDiagnostic - This function postprocesses a PathDiagnostic object
1463/// and collapses PathDiagosticPieces that are expanded by macros.
1464static void CompactPathDiagnostic(PathDiagnostic &PD, const SourceManager& SM) {
1465 typedef std::vector<std::pair<PathDiagnosticMacroPiece*, SourceLocation> >
1466 MacroStackTy;
1467
1468 typedef std::vector<PathDiagnosticPiece*>
1469 PiecesTy;
1470
1471 MacroStackTy MacroStack;
1472 PiecesTy Pieces;
1473
1474 for (PathDiagnostic::iterator I = PD.begin(), E = PD.end(); I!=E; ++I) {
1475 // Get the location of the PathDiagnosticPiece.
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +00001476 const FullSourceLoc Loc = I->getLocation().asLocation();
Ted Kremenek0e5c8d42009-03-10 05:16:17 +00001477
1478 // Determine the instantiation location, which is the location we group
1479 // related PathDiagnosticPieces.
1480 SourceLocation InstantiationLoc = Loc.isMacroID() ?
1481 SM.getInstantiationLoc(Loc) :
1482 SourceLocation();
1483
1484 if (Loc.isFileID()) {
1485 MacroStack.clear();
1486 Pieces.push_back(&*I);
1487 continue;
1488 }
1489
1490 assert(Loc.isMacroID());
1491
1492 // Is the PathDiagnosticPiece within the same macro group?
1493 if (!MacroStack.empty() && InstantiationLoc == MacroStack.back().second) {
1494 MacroStack.back().first->push_back(&*I);
1495 continue;
1496 }
1497
1498 // We aren't in the same group. Are we descending into a new macro
1499 // or are part of an old one?
1500 PathDiagnosticMacroPiece *MacroGroup = 0;
1501
1502 SourceLocation ParentInstantiationLoc = InstantiationLoc.isMacroID() ?
1503 SM.getInstantiationLoc(Loc) :
1504 SourceLocation();
1505
1506 // Walk the entire macro stack.
1507 while (!MacroStack.empty()) {
1508 if (InstantiationLoc == MacroStack.back().second) {
1509 MacroGroup = MacroStack.back().first;
1510 break;
1511 }
1512
1513 if (ParentInstantiationLoc == MacroStack.back().second) {
1514 MacroGroup = MacroStack.back().first;
1515 break;
1516 }
1517
1518 MacroStack.pop_back();
1519 }
1520
1521 if (!MacroGroup || ParentInstantiationLoc == MacroStack.back().second) {
1522 // Create a new macro group and add it to the stack.
1523 PathDiagnosticMacroPiece *NewGroup = new PathDiagnosticMacroPiece(Loc);
1524
1525 if (MacroGroup)
1526 MacroGroup->push_back(NewGroup);
1527 else {
1528 assert(InstantiationLoc.isFileID());
1529 Pieces.push_back(NewGroup);
1530 }
1531
1532 MacroGroup = NewGroup;
1533 MacroStack.push_back(std::make_pair(MacroGroup, InstantiationLoc));
1534 }
1535
1536 // Finally, add the PathDiagnosticPiece to the group.
1537 MacroGroup->push_back(&*I);
1538 }
1539
1540 // Now take the pieces and construct a new PathDiagnostic.
1541 PD.resetPath(false);
1542
1543 for (PiecesTy::iterator I=Pieces.begin(), E=Pieces.end(); I!=E; ++I) {
1544 if (PathDiagnosticMacroPiece *MP=dyn_cast<PathDiagnosticMacroPiece>(*I))
1545 if (!MP->containsEvent()) {
1546 delete MP;
1547 continue;
1548 }
1549
1550 PD.push_back(*I);
1551 }
1552}
1553
Ted Kremenek7dc86642009-03-31 20:22:36 +00001554void GRBugReporter::GeneratePathDiagnostic(PathDiagnostic& PD,
Ted Kremenek8966bc12009-05-06 21:39:49 +00001555 BugReportEquivClass& EQ) {
Ted Kremenek7dc86642009-03-31 20:22:36 +00001556
1557 std::vector<const ExplodedNode<GRState>*> Nodes;
1558
Ted Kremenekcf118d42009-02-04 23:49:09 +00001559 for (BugReportEquivClass::iterator I=EQ.begin(), E=EQ.end(); I!=E; ++I) {
1560 const ExplodedNode<GRState>* N = I->getEndNode();
1561 if (N) Nodes.push_back(N);
1562 }
1563
1564 if (Nodes.empty())
1565 return;
Ted Kremeneka43a1eb2008-04-23 23:02:12 +00001566
1567 // Construct a new graph that contains only a single path from the error
Ted Kremenekcf118d42009-02-04 23:49:09 +00001568 // node to a root.
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001569 const std::pair<std::pair<ExplodedGraph<GRState>*, NodeBackMap*>,
Ted Kremenek7dc86642009-03-31 20:22:36 +00001570 std::pair<ExplodedNode<GRState>*, unsigned> >&
1571 GPair = MakeReportGraph(&getGraph(), &Nodes[0], &Nodes[0] + Nodes.size());
Ted Kremeneka43a1eb2008-04-23 23:02:12 +00001572
Ted Kremenekcf118d42009-02-04 23:49:09 +00001573 // Find the BugReport with the original location.
1574 BugReport *R = 0;
1575 unsigned i = 0;
1576 for (BugReportEquivClass::iterator I=EQ.begin(), E=EQ.end(); I!=E; ++I, ++i)
1577 if (i == GPair.second.second) { R = *I; break; }
1578
1579 assert(R && "No original report found for sliced graph.");
Ted Kremeneka43a1eb2008-04-23 23:02:12 +00001580
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001581 llvm::OwningPtr<ExplodedGraph<GRState> > ReportGraph(GPair.first.first);
1582 llvm::OwningPtr<NodeBackMap> BackMap(GPair.first.second);
Ted Kremenekcf118d42009-02-04 23:49:09 +00001583 const ExplodedNode<GRState> *N = GPair.second.first;
Ted Kremenek7dc86642009-03-31 20:22:36 +00001584
Ted Kremenek8966bc12009-05-06 21:39:49 +00001585 // Start building the path diagnostic...
1586 PathDiagnosticBuilder PDB(*this, R, BackMap.get(), getPathDiagnosticClient());
1587
1588 if (PathDiagnosticPiece* Piece = R->getEndPath(PDB, N))
Ted Kremenekbd7efa82008-04-17 23:44:37 +00001589 PD.push_back(Piece);
1590 else
1591 return;
Ted Kremenekdd986cc2009-05-07 00:45:33 +00001592
1593 R->registerInitialVisitors(PDB, N);
Ted Kremenekbd7efa82008-04-17 23:44:37 +00001594
Ted Kremenek7dc86642009-03-31 20:22:36 +00001595 switch (PDB.getGenerationScheme()) {
1596 case PathDiagnosticClient::Extensive:
Ted Kremenek8966bc12009-05-06 21:39:49 +00001597 GenerateExtensivePathDiagnostic(PD, PDB, N);
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +00001598 break;
Ted Kremenek7dc86642009-03-31 20:22:36 +00001599 case PathDiagnosticClient::Minimal:
1600 GenerateMinimalPathDiagnostic(PD, PDB, N);
1601 break;
1602 }
Ted Kremenek7dc86642009-03-31 20:22:36 +00001603}
1604
Ted Kremenekcf118d42009-02-04 23:49:09 +00001605void BugReporter::Register(BugType *BT) {
1606 BugTypes = F.Add(BugTypes, BT);
Ted Kremenek76d90c82008-05-16 18:33:14 +00001607}
1608
Ted Kremenekcf118d42009-02-04 23:49:09 +00001609void BugReporter::EmitReport(BugReport* R) {
1610 // Compute the bug report's hash to determine its equivalence class.
1611 llvm::FoldingSetNodeID ID;
1612 R->Profile(ID);
Ted Kremenek61f3e052008-04-03 04:42:52 +00001613
Ted Kremenekcf118d42009-02-04 23:49:09 +00001614 // Lookup the equivance class. If there isn't one, create it.
1615 BugType& BT = R->getBugType();
1616 Register(&BT);
1617 void *InsertPos;
1618 BugReportEquivClass* EQ = BT.EQClasses.FindNodeOrInsertPos(ID, InsertPos);
1619
1620 if (!EQ) {
1621 EQ = new BugReportEquivClass(R);
1622 BT.EQClasses.InsertNode(EQ, InsertPos);
1623 }
1624 else
1625 EQ->AddReport(R);
Ted Kremenek61f3e052008-04-03 04:42:52 +00001626}
1627
Ted Kremenekcf118d42009-02-04 23:49:09 +00001628void BugReporter::FlushReport(BugReportEquivClass& EQ) {
1629 assert(!EQ.Reports.empty());
1630 BugReport &R = **EQ.begin();
Ted Kremenekd49967f2009-04-29 21:58:13 +00001631 PathDiagnosticClient* PD = getPathDiagnosticClient();
Ted Kremenekcf118d42009-02-04 23:49:09 +00001632
1633 // FIXME: Make sure we use the 'R' for the path that was actually used.
1634 // Probably doesn't make a difference in practice.
1635 BugType& BT = R.getBugType();
1636
Ted Kremenekd49967f2009-04-29 21:58:13 +00001637 llvm::OwningPtr<PathDiagnostic>
1638 D(new PathDiagnostic(R.getBugType().getName(),
Ted Kremenekda0e8422009-04-29 22:05:03 +00001639 !PD || PD->useVerboseDescription()
Ted Kremenekd49967f2009-04-29 21:58:13 +00001640 ? R.getDescription() : R.getShortDescription(),
1641 BT.getCategory()));
1642
Ted Kremenekcf118d42009-02-04 23:49:09 +00001643 GeneratePathDiagnostic(*D.get(), EQ);
Ted Kremenek072192b2008-04-30 23:47:44 +00001644
1645 // Get the meta data.
Ted Kremenek072192b2008-04-30 23:47:44 +00001646 std::pair<const char**, const char**> Meta = R.getExtraDescriptiveText();
Ted Kremenek3148eb42009-01-24 00:55:43 +00001647 for (const char** s = Meta.first; s != Meta.second; ++s) D->addMeta(*s);
Ted Kremenek75840e12008-04-18 01:56:37 +00001648
Ted Kremenek3148eb42009-01-24 00:55:43 +00001649 // Emit a summary diagnostic to the regular Diagnostics engine.
Ted Kremenek3148eb42009-01-24 00:55:43 +00001650 const SourceRange *Beg = 0, *End = 0;
1651 R.getRanges(*this, Beg, End);
1652 Diagnostic& Diag = getDiagnostic();
Ted Kremenekcf118d42009-02-04 23:49:09 +00001653 FullSourceLoc L(R.getLocation(), getSourceManager());
Ted Kremenekd90e7082009-02-07 22:36:41 +00001654 unsigned ErrorDiag = Diag.getCustomDiagID(Diagnostic::Warning,
Ted Kremenekeaedfea2009-05-10 05:11:21 +00001655 R.getShortDescription().c_str());
Ted Kremenek57202072008-07-14 17:40:50 +00001656
Ted Kremenek3148eb42009-01-24 00:55:43 +00001657 switch (End-Beg) {
Chris Lattner0a14eee2008-11-18 07:04:44 +00001658 default: assert(0 && "Don't handle this many ranges yet!");
1659 case 0: Diag.Report(L, ErrorDiag); break;
1660 case 1: Diag.Report(L, ErrorDiag) << Beg[0]; break;
1661 case 2: Diag.Report(L, ErrorDiag) << Beg[0] << Beg[1]; break;
1662 case 3: Diag.Report(L, ErrorDiag) << Beg[0] << Beg[1] << Beg[2]; break;
Ted Kremenek2f0e89e2008-04-18 22:56:53 +00001663 }
Ted Kremenek3148eb42009-01-24 00:55:43 +00001664
1665 // Emit a full diagnostic for the path if we have a PathDiagnosticClient.
1666 if (!PD)
1667 return;
1668
1669 if (D->empty()) {
Ted Kremenek1fbfd5b2009-03-06 23:58:11 +00001670 PathDiagnosticPiece* piece =
1671 new PathDiagnosticEventPiece(L, R.getDescription());
1672
Ted Kremenek3148eb42009-01-24 00:55:43 +00001673 for ( ; Beg != End; ++Beg) piece->addRange(*Beg);
1674 D->push_back(piece);
1675 }
1676
1677 PD->HandlePathDiagnostic(D.take());
Ted Kremenek61f3e052008-04-03 04:42:52 +00001678}
Ted Kremenek57202072008-07-14 17:40:50 +00001679
Ted Kremenek8c036c72008-09-20 04:23:38 +00001680void BugReporter::EmitBasicReport(const char* name, const char* str,
1681 SourceLocation Loc,
1682 SourceRange* RBeg, unsigned NumRanges) {
1683 EmitBasicReport(name, "", str, Loc, RBeg, NumRanges);
1684}
Ted Kremenekcf118d42009-02-04 23:49:09 +00001685
Ted Kremenek8c036c72008-09-20 04:23:38 +00001686void BugReporter::EmitBasicReport(const char* name, const char* category,
1687 const char* str, SourceLocation Loc,
1688 SourceRange* RBeg, unsigned NumRanges) {
1689
Ted Kremenekcf118d42009-02-04 23:49:09 +00001690 // 'BT' will be owned by BugReporter as soon as we call 'EmitReport'.
1691 BugType *BT = new BugType(name, category);
Chris Lattner0a14eee2008-11-18 07:04:44 +00001692 FullSourceLoc L = getContext().getFullLoc(Loc);
Ted Kremenekcf118d42009-02-04 23:49:09 +00001693 RangedBugReport *R = new DiagBugReport(*BT, str, L);
1694 for ( ; NumRanges > 0 ; --NumRanges, ++RBeg) R->addRange(*RBeg);
1695 EmitReport(R);
Ted Kremenek57202072008-07-14 17:40:50 +00001696}