blob: c8f54c0410a74037b7f9e348273e07ed078b855c [file] [log] [blame]
Ted Kremenek61f3e052008-04-03 04:42:52 +00001// BugReporter.cpp - Generate PathDiagnostics for Bugs ------------*- C++ -*--//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines BugReporter, a utility class for generating
11// PathDiagnostics for analyses based on GRSimpleVals.
12//
13//===----------------------------------------------------------------------===//
14
15#include "clang/Analysis/PathSensitive/BugReporter.h"
Ted Kremenek50a6d0c2008-04-09 21:41:14 +000016#include "clang/Analysis/PathSensitive/GRExprEngine.h"
Ted Kremenek61f3e052008-04-03 04:42:52 +000017#include "clang/Basic/SourceManager.h"
18#include "clang/Basic/SourceLocation.h"
19#include "clang/AST/ASTContext.h"
20#include "clang/AST/CFG.h"
21#include "clang/AST/Expr.h"
Ted Kremenek00605e02009-03-27 20:55:39 +000022#include "clang/AST/ParentMap.h"
Ted Kremenek61f3e052008-04-03 04:42:52 +000023#include "clang/Analysis/ProgramPoint.h"
24#include "clang/Analysis/PathDiagnostic.h"
Chris Lattner405674c2008-08-23 22:23:37 +000025#include "llvm/Support/raw_ostream.h"
Ted Kremenek331b0ac2008-06-18 05:34:07 +000026#include "llvm/ADT/DenseMap.h"
Ted Kremenekcf118d42009-02-04 23:49:09 +000027#include "llvm/ADT/STLExtras.h"
Ted Kremenek00605e02009-03-27 20:55:39 +000028#include "llvm/ADT/OwningPtr.h"
Ted Kremenek10aa5542009-03-12 23:41:59 +000029#include <queue>
Ted Kremenek61f3e052008-04-03 04:42:52 +000030
31using namespace clang;
32
Ted Kremenekcf118d42009-02-04 23:49:09 +000033//===----------------------------------------------------------------------===//
Ted Kremenek31061982009-03-31 23:00:32 +000034// Helper routines for walking the ExplodedGraph and fetching statements.
Ted Kremenekcf118d42009-02-04 23:49:09 +000035//===----------------------------------------------------------------------===//
Ted Kremenek61f3e052008-04-03 04:42:52 +000036
Ted Kremenekb697b102009-02-23 22:44:26 +000037static inline Stmt* GetStmt(ProgramPoint P) {
38 if (const PostStmt* PS = dyn_cast<PostStmt>(&P))
Ted Kremenek61f3e052008-04-03 04:42:52 +000039 return PS->getStmt();
Ted Kremenekb697b102009-02-23 22:44:26 +000040 else if (const BlockEdge* BE = dyn_cast<BlockEdge>(&P))
Ted Kremenek61f3e052008-04-03 04:42:52 +000041 return BE->getSrc()->getTerminator();
Ted Kremenek61f3e052008-04-03 04:42:52 +000042
Ted Kremenekb697b102009-02-23 22:44:26 +000043 return 0;
Ted Kremenek706e3cf2008-04-07 23:35:17 +000044}
45
Ted Kremenek3148eb42009-01-24 00:55:43 +000046static inline const ExplodedNode<GRState>*
Ted Kremenekb697b102009-02-23 22:44:26 +000047GetPredecessorNode(const ExplodedNode<GRState>* N) {
Ted Kremenekbd7efa82008-04-17 23:44:37 +000048 return N->pred_empty() ? NULL : *(N->pred_begin());
49}
Ted Kremenek2673c9f2008-04-25 19:01:27 +000050
Ted Kremenekb697b102009-02-23 22:44:26 +000051static inline const ExplodedNode<GRState>*
52GetSuccessorNode(const ExplodedNode<GRState>* N) {
53 return N->succ_empty() ? NULL : *(N->succ_begin());
Ted Kremenekbd7efa82008-04-17 23:44:37 +000054}
55
Ted Kremenekb697b102009-02-23 22:44:26 +000056static Stmt* GetPreviousStmt(const ExplodedNode<GRState>* N) {
57 for (N = GetPredecessorNode(N); N; N = GetPredecessorNode(N))
58 if (Stmt *S = GetStmt(N->getLocation()))
59 return S;
60
61 return 0;
Ted Kremenek3148eb42009-01-24 00:55:43 +000062}
63
Ted Kremenekb697b102009-02-23 22:44:26 +000064static Stmt* GetNextStmt(const ExplodedNode<GRState>* N) {
65 for (N = GetSuccessorNode(N); N; N = GetSuccessorNode(N))
Ted Kremenekf5ab8e62009-03-28 17:33:57 +000066 if (Stmt *S = GetStmt(N->getLocation())) {
67 // Check if the statement is '?' or '&&'/'||'. These are "merges",
68 // not actual statement points.
69 switch (S->getStmtClass()) {
70 case Stmt::ChooseExprClass:
71 case Stmt::ConditionalOperatorClass: continue;
72 case Stmt::BinaryOperatorClass: {
73 BinaryOperator::Opcode Op = cast<BinaryOperator>(S)->getOpcode();
74 if (Op == BinaryOperator::LAnd || Op == BinaryOperator::LOr)
75 continue;
76 break;
77 }
78 default:
79 break;
80 }
Ted Kremenekb697b102009-02-23 22:44:26 +000081 return S;
Ted Kremenekf5ab8e62009-03-28 17:33:57 +000082 }
Ted Kremenekb697b102009-02-23 22:44:26 +000083
84 return 0;
85}
86
87static inline Stmt* GetCurrentOrPreviousStmt(const ExplodedNode<GRState>* N) {
88 if (Stmt *S = GetStmt(N->getLocation()))
89 return S;
90
91 return GetPreviousStmt(N);
92}
93
94static inline Stmt* GetCurrentOrNextStmt(const ExplodedNode<GRState>* N) {
95 if (Stmt *S = GetStmt(N->getLocation()))
96 return S;
97
98 return GetNextStmt(N);
99}
100
101//===----------------------------------------------------------------------===//
Ted Kremenek31061982009-03-31 23:00:32 +0000102// PathDiagnosticBuilder and its associated routines and helper objects.
Ted Kremenekb697b102009-02-23 22:44:26 +0000103//===----------------------------------------------------------------------===//
Ted Kremenekb479dad2009-02-23 23:13:51 +0000104
Ted Kremenek7dc86642009-03-31 20:22:36 +0000105typedef llvm::DenseMap<const ExplodedNode<GRState>*,
106const ExplodedNode<GRState>*> NodeBackMap;
107
Ted Kremenekbabdd7b2009-03-27 05:06:10 +0000108namespace {
Ted Kremenek7dc86642009-03-31 20:22:36 +0000109class VISIBILITY_HIDDEN NodeMapClosure : public BugReport::NodeResolver {
110 NodeBackMap& M;
111public:
112 NodeMapClosure(NodeBackMap *m) : M(*m) {}
113 ~NodeMapClosure() {}
114
115 const ExplodedNode<GRState>* getOriginalNode(const ExplodedNode<GRState>* N) {
116 NodeBackMap::iterator I = M.find(N);
117 return I == M.end() ? 0 : I->second;
118 }
119};
120
Ted Kremenekbabdd7b2009-03-27 05:06:10 +0000121class VISIBILITY_HIDDEN PathDiagnosticBuilder {
Ted Kremenek7dc86642009-03-31 20:22:36 +0000122 GRBugReporter &BR;
Ted Kremenekbabdd7b2009-03-27 05:06:10 +0000123 SourceManager &SMgr;
Ted Kremenek7dc86642009-03-31 20:22:36 +0000124 ExplodedGraph<GRState> *ReportGraph;
125 BugReport *R;
Ted Kremenekbabdd7b2009-03-27 05:06:10 +0000126 const Decl& CodeDecl;
127 PathDiagnosticClient *PDC;
Ted Kremenek00605e02009-03-27 20:55:39 +0000128 llvm::OwningPtr<ParentMap> PM;
Ted Kremenek7dc86642009-03-31 20:22:36 +0000129 NodeMapClosure NMC;
Ted Kremenekbabdd7b2009-03-27 05:06:10 +0000130public:
Ted Kremenek7dc86642009-03-31 20:22:36 +0000131 PathDiagnosticBuilder(GRBugReporter &br, ExplodedGraph<GRState> *reportGraph,
132 BugReport *r, NodeBackMap *Backmap,
133 const Decl& codedecl, PathDiagnosticClient *pdc)
134 : BR(br), SMgr(BR.getSourceManager()), ReportGraph(reportGraph), R(r),
135 CodeDecl(codedecl), PDC(pdc), NMC(Backmap) {}
Ted Kremenekbabdd7b2009-03-27 05:06:10 +0000136
Ted Kremenek00605e02009-03-27 20:55:39 +0000137 PathDiagnosticLocation ExecutionContinues(const ExplodedNode<GRState>* N);
Ted Kremenekbabdd7b2009-03-27 05:06:10 +0000138
Ted Kremenek00605e02009-03-27 20:55:39 +0000139 PathDiagnosticLocation ExecutionContinues(llvm::raw_string_ostream& os,
140 const ExplodedNode<GRState>* N);
141
142 ParentMap& getParentMap() {
143 if (PM.get() == 0) PM.reset(new ParentMap(CodeDecl.getBody()));
144 return *PM.get();
145 }
Ted Kremenekbabdd7b2009-03-27 05:06:10 +0000146
Ted Kremenekc3f83ad2009-04-01 17:18:21 +0000147 const Stmt *getParent(const Stmt *S) {
148 return getParentMap().getParent(S);
149 }
150
Ted Kremenek7dc86642009-03-31 20:22:36 +0000151 ExplodedGraph<GRState>& getGraph() { return *ReportGraph; }
152 NodeMapClosure& getNodeMapClosure() { return NMC; }
153 ASTContext& getContext() { return BR.getContext(); }
154 SourceManager& getSourceManager() { return SMgr; }
155 BugReport& getReport() { return *R; }
156 GRBugReporter& getBugReporter() { return BR; }
157 GRStateManager& getStateManager() { return BR.getStateManager(); }
158
Ted Kremenekd8c938b2009-03-27 21:16:25 +0000159 PathDiagnosticLocation getEnclosingStmtLocation(const Stmt *S);
160
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000161 PathDiagnosticLocation
162 getEnclosingStmtLocation(const PathDiagnosticLocation &L) {
163 if (const Stmt *S = L.asStmt())
164 return getEnclosingStmtLocation(S);
165
166 return L;
167 }
168
Ted Kremenek7dc86642009-03-31 20:22:36 +0000169 PathDiagnosticClient::PathGenerationScheme getGenerationScheme() const {
170 return PDC ? PDC->getGenerationScheme() : PathDiagnosticClient::Extensive;
171 }
172
Ted Kremenekbabdd7b2009-03-27 05:06:10 +0000173 bool supportsLogicalOpControlFlow() const {
174 return PDC ? PDC->supportsLogicalOpControlFlow() : true;
175 }
176};
177} // end anonymous namespace
178
Ted Kremenek00605e02009-03-27 20:55:39 +0000179PathDiagnosticLocation
180PathDiagnosticBuilder::ExecutionContinues(const ExplodedNode<GRState>* N) {
181 if (Stmt *S = GetNextStmt(N))
182 return PathDiagnosticLocation(S, SMgr);
183
184 return FullSourceLoc(CodeDecl.getBody()->getRBracLoc(), SMgr);
Ted Kremenek082cb8d2009-03-12 18:41:53 +0000185}
186
Ted Kremenek00605e02009-03-27 20:55:39 +0000187PathDiagnosticLocation
Ted Kremenekbabdd7b2009-03-27 05:06:10 +0000188PathDiagnosticBuilder::ExecutionContinues(llvm::raw_string_ostream& os,
189 const ExplodedNode<GRState>* N) {
190
Ted Kremenek143ca222008-05-06 18:11:09 +0000191 // Slow, but probably doesn't matter.
Ted Kremenekb697b102009-02-23 22:44:26 +0000192 if (os.str().empty())
193 os << ' ';
Ted Kremenek143ca222008-05-06 18:11:09 +0000194
Ted Kremenek00605e02009-03-27 20:55:39 +0000195 const PathDiagnosticLocation &Loc = ExecutionContinues(N);
Ted Kremenek082cb8d2009-03-12 18:41:53 +0000196
Ted Kremenek00605e02009-03-27 20:55:39 +0000197 if (Loc.asStmt())
Ted Kremenekb697b102009-02-23 22:44:26 +0000198 os << "Execution continues on line "
Ted Kremenek00605e02009-03-27 20:55:39 +0000199 << SMgr.getInstantiationLineNumber(Loc.asLocation()) << '.';
Ted Kremenekb697b102009-02-23 22:44:26 +0000200 else
Ted Kremenekb479dad2009-02-23 23:13:51 +0000201 os << "Execution jumps to the end of the "
Ted Kremenekbabdd7b2009-03-27 05:06:10 +0000202 << (isa<ObjCMethodDecl>(CodeDecl) ? "method" : "function") << '.';
Ted Kremenek082cb8d2009-03-12 18:41:53 +0000203
204 return Loc;
Ted Kremenek143ca222008-05-06 18:11:09 +0000205}
206
Ted Kremenekd8c938b2009-03-27 21:16:25 +0000207PathDiagnosticLocation
208PathDiagnosticBuilder::getEnclosingStmtLocation(const Stmt *S) {
209 assert(S && "Null Stmt* passed to getEnclosingStmtLocation");
210 ParentMap &P = getParentMap();
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000211
212 while (isa<DeclStmt>(S) || isa<Expr>(S)) {
Ted Kremenekd8c938b2009-03-27 21:16:25 +0000213 const Stmt *Parent = P.getParent(S);
214
Ted Kremenekaf3e3d52009-03-28 03:37:59 +0000215 if (!Parent)
216 break;
Ted Kremenekd8c938b2009-03-27 21:16:25 +0000217
Ted Kremenekaf3e3d52009-03-28 03:37:59 +0000218 switch (Parent->getStmtClass()) {
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000219 case Stmt::BinaryOperatorClass: {
220 const BinaryOperator *B = cast<BinaryOperator>(Parent);
221 if (B->isLogicalOp())
222 return PathDiagnosticLocation(S, SMgr);
223 break;
224 }
225
Ted Kremenekaf3e3d52009-03-28 03:37:59 +0000226 case Stmt::CompoundStmtClass:
227 case Stmt::StmtExprClass:
Ted Kremenek1d9a23a2009-03-28 04:08:14 +0000228 return PathDiagnosticLocation(S, SMgr);
229 case Stmt::ChooseExprClass:
230 // Similar to '?' if we are referring to condition, just have the edge
231 // point to the entire choose expression.
232 if (cast<ChooseExpr>(Parent)->getCond() == S)
233 return PathDiagnosticLocation(Parent, SMgr);
234 else
235 return PathDiagnosticLocation(S, SMgr);
236 case Stmt::ConditionalOperatorClass:
237 // For '?', if we are referring to condition, just have the edge point
238 // to the entire '?' expression.
239 if (cast<ConditionalOperator>(Parent)->getCond() == S)
240 return PathDiagnosticLocation(Parent, SMgr);
241 else
242 return PathDiagnosticLocation(S, SMgr);
Ted Kremenekaf3e3d52009-03-28 03:37:59 +0000243 case Stmt::DoStmtClass:
244 if (cast<DoStmt>(Parent)->getCond() != S)
245 return PathDiagnosticLocation(S, SMgr);
246 break;
247 case Stmt::ForStmtClass:
248 if (cast<ForStmt>(Parent)->getBody() == S)
249 return PathDiagnosticLocation(S, SMgr);
250 break;
251 case Stmt::IfStmtClass:
252 if (cast<IfStmt>(Parent)->getCond() != S)
253 return PathDiagnosticLocation(S, SMgr);
254 break;
255 case Stmt::ObjCForCollectionStmtClass:
256 if (cast<ObjCForCollectionStmt>(Parent)->getBody() == S)
257 return PathDiagnosticLocation(S, SMgr);
258 break;
259 case Stmt::WhileStmtClass:
260 if (cast<WhileStmt>(Parent)->getCond() != S)
261 return PathDiagnosticLocation(S, SMgr);
262 break;
263 default:
264 break;
265 }
266
Ted Kremenekd8c938b2009-03-27 21:16:25 +0000267 S = Parent;
268 }
269
270 assert(S && "Cannot have null Stmt for PathDiagnosticLocation");
271 return PathDiagnosticLocation(S, SMgr);
272}
273
Ted Kremenekcf118d42009-02-04 23:49:09 +0000274//===----------------------------------------------------------------------===//
Ted Kremenek31061982009-03-31 23:00:32 +0000275// ScanNotableSymbols: closure-like callback for scanning Store bindings.
276//===----------------------------------------------------------------------===//
277
278static const VarDecl*
279GetMostRecentVarDeclBinding(const ExplodedNode<GRState>* N,
280 GRStateManager& VMgr, SVal X) {
281
282 for ( ; N ; N = N->pred_empty() ? 0 : *N->pred_begin()) {
283
284 ProgramPoint P = N->getLocation();
285
286 if (!isa<PostStmt>(P))
287 continue;
288
289 DeclRefExpr* DR = dyn_cast<DeclRefExpr>(cast<PostStmt>(P).getStmt());
290
291 if (!DR)
292 continue;
293
294 SVal Y = VMgr.GetSVal(N->getState(), DR);
295
296 if (X != Y)
297 continue;
298
299 VarDecl* VD = dyn_cast<VarDecl>(DR->getDecl());
300
301 if (!VD)
302 continue;
303
304 return VD;
305 }
306
307 return 0;
308}
309
310namespace {
311class VISIBILITY_HIDDEN NotableSymbolHandler
312: public StoreManager::BindingsHandler {
313
314 SymbolRef Sym;
315 const GRState* PrevSt;
316 const Stmt* S;
317 GRStateManager& VMgr;
318 const ExplodedNode<GRState>* Pred;
319 PathDiagnostic& PD;
320 BugReporter& BR;
321
322public:
323
324 NotableSymbolHandler(SymbolRef sym, const GRState* prevst, const Stmt* s,
325 GRStateManager& vmgr, const ExplodedNode<GRState>* pred,
326 PathDiagnostic& pd, BugReporter& br)
327 : Sym(sym), PrevSt(prevst), S(s), VMgr(vmgr), Pred(pred), PD(pd), BR(br) {}
328
329 bool HandleBinding(StoreManager& SMgr, Store store, const MemRegion* R,
330 SVal V) {
331
332 SymbolRef ScanSym = V.getAsSymbol();
333
334 if (ScanSym != Sym)
335 return true;
336
337 // Check if the previous state has this binding.
338 SVal X = VMgr.GetSVal(PrevSt, loc::MemRegionVal(R));
339
340 if (X == V) // Same binding?
341 return true;
342
343 // Different binding. Only handle assignments for now. We don't pull
344 // this check out of the loop because we will eventually handle other
345 // cases.
346
347 VarDecl *VD = 0;
348
349 if (const BinaryOperator* B = dyn_cast<BinaryOperator>(S)) {
350 if (!B->isAssignmentOp())
351 return true;
352
353 // What variable did we assign to?
354 DeclRefExpr* DR = dyn_cast<DeclRefExpr>(B->getLHS()->IgnoreParenCasts());
355
356 if (!DR)
357 return true;
358
359 VD = dyn_cast<VarDecl>(DR->getDecl());
360 }
361 else if (const DeclStmt* DS = dyn_cast<DeclStmt>(S)) {
362 // FIXME: Eventually CFGs won't have DeclStmts. Right now we
363 // assume that each DeclStmt has a single Decl. This invariant
364 // holds by contruction in the CFG.
365 VD = dyn_cast<VarDecl>(*DS->decl_begin());
366 }
367
368 if (!VD)
369 return true;
370
371 // What is the most recently referenced variable with this binding?
372 const VarDecl* MostRecent = GetMostRecentVarDeclBinding(Pred, VMgr, V);
373
374 if (!MostRecent)
375 return true;
376
377 // Create the diagnostic.
378 FullSourceLoc L(S->getLocStart(), BR.getSourceManager());
379
380 if (Loc::IsLocType(VD->getType())) {
381 std::string msg = "'" + std::string(VD->getNameAsString()) +
382 "' now aliases '" + MostRecent->getNameAsString() + "'";
383
384 PD.push_front(new PathDiagnosticEventPiece(L, msg));
385 }
386
387 return true;
388 }
389};
390}
391
392static void HandleNotableSymbol(const ExplodedNode<GRState>* N,
393 const Stmt* S,
394 SymbolRef Sym, BugReporter& BR,
395 PathDiagnostic& PD) {
396
397 const ExplodedNode<GRState>* Pred = N->pred_empty() ? 0 : *N->pred_begin();
398 const GRState* PrevSt = Pred ? Pred->getState() : 0;
399
400 if (!PrevSt)
401 return;
402
403 // Look at the region bindings of the current state that map to the
404 // specified symbol. Are any of them not in the previous state?
405 GRStateManager& VMgr = cast<GRBugReporter>(BR).getStateManager();
406 NotableSymbolHandler H(Sym, PrevSt, S, VMgr, Pred, PD, BR);
407 cast<GRBugReporter>(BR).getStateManager().iterBindings(N->getState(), H);
408}
409
410namespace {
411class VISIBILITY_HIDDEN ScanNotableSymbols
412: public StoreManager::BindingsHandler {
413
414 llvm::SmallSet<SymbolRef, 10> AlreadyProcessed;
415 const ExplodedNode<GRState>* N;
416 Stmt* S;
417 GRBugReporter& BR;
418 PathDiagnostic& PD;
419
420public:
421 ScanNotableSymbols(const ExplodedNode<GRState>* n, Stmt* s, GRBugReporter& br,
422 PathDiagnostic& pd)
423 : N(n), S(s), BR(br), PD(pd) {}
424
425 bool HandleBinding(StoreManager& SMgr, Store store,
426 const MemRegion* R, SVal V) {
427
428 SymbolRef ScanSym = V.getAsSymbol();
429
430 if (!ScanSym)
431 return true;
432
433 if (!BR.isNotable(ScanSym))
434 return true;
435
436 if (AlreadyProcessed.count(ScanSym))
437 return true;
438
439 AlreadyProcessed.insert(ScanSym);
440
441 HandleNotableSymbol(N, S, ScanSym, BR, PD);
442 return true;
443 }
444};
445} // end anonymous namespace
446
447//===----------------------------------------------------------------------===//
448// "Minimal" path diagnostic generation algorithm.
449//===----------------------------------------------------------------------===//
450
451static void GenerateMinimalPathDiagnostic(PathDiagnostic& PD,
452 PathDiagnosticBuilder &PDB,
453 const ExplodedNode<GRState> *N) {
454 ASTContext& Ctx = PDB.getContext();
455 SourceManager& SMgr = PDB.getSourceManager();
456 const ExplodedNode<GRState>* NextNode = N->pred_empty()
457 ? NULL : *(N->pred_begin());
458 while (NextNode) {
459 N = NextNode;
460 NextNode = GetPredecessorNode(N);
461
462 ProgramPoint P = N->getLocation();
463
464 if (const BlockEdge* BE = dyn_cast<BlockEdge>(&P)) {
465 CFGBlock* Src = BE->getSrc();
466 CFGBlock* Dst = BE->getDst();
467 Stmt* T = Src->getTerminator();
468
469 if (!T)
470 continue;
471
472 FullSourceLoc Start(T->getLocStart(), SMgr);
473
474 switch (T->getStmtClass()) {
475 default:
476 break;
477
478 case Stmt::GotoStmtClass:
479 case Stmt::IndirectGotoStmtClass: {
480 Stmt* S = GetNextStmt(N);
481
482 if (!S)
483 continue;
484
485 std::string sbuf;
486 llvm::raw_string_ostream os(sbuf);
487 const PathDiagnosticLocation &End = PDB.getEnclosingStmtLocation(S);
488
489 os << "Control jumps to line "
490 << End.asLocation().getInstantiationLineNumber();
491 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
492 os.str()));
493 break;
494 }
495
496 case Stmt::SwitchStmtClass: {
497 // Figure out what case arm we took.
498 std::string sbuf;
499 llvm::raw_string_ostream os(sbuf);
500
501 if (Stmt* S = Dst->getLabel()) {
502 PathDiagnosticLocation End(S, SMgr);
503
504 switch (S->getStmtClass()) {
505 default:
506 os << "No cases match in the switch statement. "
507 "Control jumps to line "
508 << End.asLocation().getInstantiationLineNumber();
509 break;
510 case Stmt::DefaultStmtClass:
511 os << "Control jumps to the 'default' case at line "
512 << End.asLocation().getInstantiationLineNumber();
513 break;
514
515 case Stmt::CaseStmtClass: {
516 os << "Control jumps to 'case ";
517 CaseStmt* Case = cast<CaseStmt>(S);
518 Expr* LHS = Case->getLHS()->IgnoreParenCasts();
519
520 // Determine if it is an enum.
521 bool GetRawInt = true;
522
523 if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(LHS)) {
524 // FIXME: Maybe this should be an assertion. Are there cases
525 // were it is not an EnumConstantDecl?
526 EnumConstantDecl* D =
527 dyn_cast<EnumConstantDecl>(DR->getDecl());
528
529 if (D) {
530 GetRawInt = false;
531 os << D->getNameAsString();
532 }
533 }
534
535 if (GetRawInt) {
536
537 // Not an enum.
538 Expr* CondE = cast<SwitchStmt>(T)->getCond();
539 unsigned bits = Ctx.getTypeSize(CondE->getType());
540 llvm::APSInt V(bits, false);
541
542 if (!LHS->isIntegerConstantExpr(V, Ctx, 0, true)) {
543 assert (false && "Case condition must be constant.");
544 continue;
545 }
546
547 os << V;
548 }
549
550 os << ":' at line "
551 << End.asLocation().getInstantiationLineNumber();
552 break;
553 }
554 }
555 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
556 os.str()));
557 }
558 else {
559 os << "'Default' branch taken. ";
560 const PathDiagnosticLocation &End = PDB.ExecutionContinues(os, N);
561 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
562 os.str()));
563 }
564
565 break;
566 }
567
568 case Stmt::BreakStmtClass:
569 case Stmt::ContinueStmtClass: {
570 std::string sbuf;
571 llvm::raw_string_ostream os(sbuf);
572 PathDiagnosticLocation End = PDB.ExecutionContinues(os, N);
573 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
574 os.str()));
575 break;
576 }
577
578 // Determine control-flow for ternary '?'.
579 case Stmt::ConditionalOperatorClass: {
580 std::string sbuf;
581 llvm::raw_string_ostream os(sbuf);
582 os << "'?' condition is ";
583
584 if (*(Src->succ_begin()+1) == Dst)
585 os << "false";
586 else
587 os << "true";
588
589 PathDiagnosticLocation End = PDB.ExecutionContinues(N);
590
591 if (const Stmt *S = End.asStmt())
592 End = PDB.getEnclosingStmtLocation(S);
593
594 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
595 os.str()));
596 break;
597 }
598
599 // Determine control-flow for short-circuited '&&' and '||'.
600 case Stmt::BinaryOperatorClass: {
601 if (!PDB.supportsLogicalOpControlFlow())
602 break;
603
604 BinaryOperator *B = cast<BinaryOperator>(T);
605 std::string sbuf;
606 llvm::raw_string_ostream os(sbuf);
607 os << "Left side of '";
608
609 if (B->getOpcode() == BinaryOperator::LAnd) {
610 os << "&&" << "' is ";
611
612 if (*(Src->succ_begin()+1) == Dst) {
613 os << "false";
614 PathDiagnosticLocation End(B->getLHS(), SMgr);
615 PathDiagnosticLocation Start(B->getOperatorLoc(), SMgr);
616 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
617 os.str()));
618 }
619 else {
620 os << "true";
621 PathDiagnosticLocation Start(B->getLHS(), SMgr);
622 PathDiagnosticLocation End = PDB.ExecutionContinues(N);
623 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
624 os.str()));
625 }
626 }
627 else {
628 assert(B->getOpcode() == BinaryOperator::LOr);
629 os << "||" << "' is ";
630
631 if (*(Src->succ_begin()+1) == Dst) {
632 os << "false";
633 PathDiagnosticLocation Start(B->getLHS(), SMgr);
634 PathDiagnosticLocation End = PDB.ExecutionContinues(N);
635 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
636 os.str()));
637 }
638 else {
639 os << "true";
640 PathDiagnosticLocation End(B->getLHS(), SMgr);
641 PathDiagnosticLocation Start(B->getOperatorLoc(), SMgr);
642 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
643 os.str()));
644 }
645 }
646
647 break;
648 }
649
650 case Stmt::DoStmtClass: {
651 if (*(Src->succ_begin()) == Dst) {
652 std::string sbuf;
653 llvm::raw_string_ostream os(sbuf);
654
655 os << "Loop condition is true. ";
656 PathDiagnosticLocation End = PDB.ExecutionContinues(os, N);
657
658 if (const Stmt *S = End.asStmt())
659 End = PDB.getEnclosingStmtLocation(S);
660
661 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
662 os.str()));
663 }
664 else {
665 PathDiagnosticLocation End = PDB.ExecutionContinues(N);
666
667 if (const Stmt *S = End.asStmt())
668 End = PDB.getEnclosingStmtLocation(S);
669
670 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
671 "Loop condition is false. Exiting loop"));
672 }
673
674 break;
675 }
676
677 case Stmt::WhileStmtClass:
678 case Stmt::ForStmtClass: {
679 if (*(Src->succ_begin()+1) == Dst) {
680 std::string sbuf;
681 llvm::raw_string_ostream os(sbuf);
682
683 os << "Loop condition is false. ";
684 PathDiagnosticLocation End = PDB.ExecutionContinues(os, N);
685 if (const Stmt *S = End.asStmt())
686 End = PDB.getEnclosingStmtLocation(S);
687
688 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
689 os.str()));
690 }
691 else {
692 PathDiagnosticLocation End = PDB.ExecutionContinues(N);
693 if (const Stmt *S = End.asStmt())
694 End = PDB.getEnclosingStmtLocation(S);
695
696 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000697 "Loop condition is true. Entering loop body"));
Ted Kremenek31061982009-03-31 23:00:32 +0000698 }
699
700 break;
701 }
702
703 case Stmt::IfStmtClass: {
704 PathDiagnosticLocation End = PDB.ExecutionContinues(N);
705
706 if (const Stmt *S = End.asStmt())
707 End = PDB.getEnclosingStmtLocation(S);
708
709 if (*(Src->succ_begin()+1) == Dst)
710 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000711 "Taking false branch"));
Ted Kremenek31061982009-03-31 23:00:32 +0000712 else
713 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000714 "Taking true branch"));
Ted Kremenek31061982009-03-31 23:00:32 +0000715
716 break;
717 }
718 }
719 }
720
721 if (PathDiagnosticPiece* p =
722 PDB.getReport().VisitNode(N, NextNode, PDB.getGraph(),
723 PDB.getBugReporter(),
724 PDB.getNodeMapClosure())) {
725 PD.push_front(p);
726 }
727
728 if (const PostStmt* PS = dyn_cast<PostStmt>(&P)) {
729 // Scan the region bindings, and see if a "notable" symbol has a new
730 // lval binding.
731 ScanNotableSymbols SNS(N, PS->getStmt(), PDB.getBugReporter(), PD);
732 PDB.getStateManager().iterBindings(N->getState(), SNS);
733 }
734 }
735}
736
737//===----------------------------------------------------------------------===//
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000738// "Extensive" PathDiagnostic generation.
739//===----------------------------------------------------------------------===//
740
741static bool IsControlFlowExpr(const Stmt *S) {
742 const Expr *E = dyn_cast<Expr>(S);
743
744 if (!E)
745 return false;
746
747 E = E->IgnoreParenCasts();
748
749 if (isa<ConditionalOperator>(E))
750 return true;
751
752 if (const BinaryOperator *B = dyn_cast<BinaryOperator>(E))
753 if (B->isLogicalOp())
754 return true;
755
756 return false;
757}
758
759static void GenExtAddEdge(PathDiagnostic& PD,
760 PathDiagnosticBuilder &PDB,
761 PathDiagnosticLocation NewLoc,
762 PathDiagnosticLocation &PrevLoc,
Ted Kremenekc3f83ad2009-04-01 17:18:21 +0000763 bool allowBlockJump = false) {
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000764
765 if (const Stmt *S = NewLoc.asStmt()) {
766 if (IsControlFlowExpr(S))
767 return;
768 }
769
770
771 if (!PrevLoc.isValid()) {
772 PrevLoc = NewLoc;
773 return;
774 }
775
776 if (NewLoc == PrevLoc)
777 return;
Ted Kremenekc3f83ad2009-04-01 17:18:21 +0000778
779 // Are we jumping between statements with the same compound statement?
780 if (!allowBlockJump)
781 if (const Stmt *PS = PrevLoc.asStmt())
782 if (const Stmt *NS = NewLoc.asStmt()) {
783 const Stmt *parentPS = PDB.getParent(PS);
784 if (isa<CompoundStmt>(parentPS) && parentPS == PDB.getParent(NS))
785 return;
786 }
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000787
788 PD.push_front(new PathDiagnosticControlFlowPiece(NewLoc, PrevLoc));
Ted Kremenekc3f83ad2009-04-01 17:18:21 +0000789 PrevLoc = NewLoc;
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000790}
791
792static bool IsNestedDeclStmt(const Stmt *S, ParentMap &PM) {
793 const DeclStmt *DS = dyn_cast<DeclStmt>(S);
794
795 if (!DS)
796 return false;
797
798 const Stmt *Parent = PM.getParent(DS);
799 if (!Parent)
800 return false;
801
802 if (const ForStmt *FS = dyn_cast<ForStmt>(Parent))
803 return FS->getInit() == DS;
804
805 // FIXME: In the future IfStmt/WhileStmt may contain DeclStmts in their condition.
806// if (const IfStmt *IF = dyn_cast<IfStmt>(Parent))
807// return IF->getCond() == DS;
808//
809// if (const WhileStmt *WS = dyn_cast<WhileStmt>(Parent))
810// return WS->getCond() == DS;
811
812 return false;
813}
814
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000815static void GenerateExtensivePathDiagnostic(PathDiagnostic& PD,
816 PathDiagnosticBuilder &PDB,
817 const ExplodedNode<GRState> *N) {
818
819 SourceManager& SMgr = PDB.getSourceManager();
820 const ExplodedNode<GRState>* NextNode = N->pred_empty()
821 ? NULL : *(N->pred_begin());
822
823 PathDiagnosticLocation PrevLoc;
824
825 while (NextNode) {
826 N = NextNode;
827 NextNode = GetPredecessorNode(N);
828 ProgramPoint P = N->getLocation();
829
830 // Block edges.
831 if (const BlockEdge *BE = dyn_cast<BlockEdge>(&P)) {
832 const CFGBlock &Blk = *BE->getSrc();
833 if (const Stmt *Term = Blk.getTerminator()) {
834 const Stmt *Cond = Blk.getTerminatorCondition();
835
836 if (!Cond || !IsControlFlowExpr(Cond)) {
Ted Kremenekc3f83ad2009-04-01 17:18:21 +0000837 GenExtAddEdge(PD, PDB, PathDiagnosticLocation(Term, SMgr), PrevLoc,
838 true);
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000839 continue;
840 }
841 }
842
843 // Only handle blocks with more than 1 statement here, as the blocks
844 // with one statement are handled at BlockEntrances.
845 if (Blk.size() > 1) {
846 const Stmt *S = *Blk.rbegin();
847
848 // We don't add control-flow edges for DeclStmt's that appear in
849 // the condition of if/while/for or are control-flow merge expressions.
850 if (!IsControlFlowExpr(S) && !IsNestedDeclStmt(S, PDB.getParentMap())) {
851 GenExtAddEdge(PD, PDB, PathDiagnosticLocation(S, SMgr), PrevLoc);
852 }
853 }
854
855 continue;
856 }
857
858 if (const BlockEntrance *BE = dyn_cast<BlockEntrance>(&P)) {
859 if (const Stmt* S = BE->getFirstStmt()) {
860 if (!IsControlFlowExpr(S) && !IsNestedDeclStmt(S, PDB.getParentMap())) {
Ted Kremenekc3f83ad2009-04-01 17:18:21 +0000861 if (PrevLoc.isValid()) {
862 // Are we jumping with the same enclosing statement?
863 if (PDB.getEnclosingStmtLocation(S) ==
864 PDB.getEnclosingStmtLocation(PrevLoc))
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000865 continue;
866 }
867
868 GenExtAddEdge(PD, PDB, PDB.getEnclosingStmtLocation(S), PrevLoc);
869 }
870 }
871
872 continue;
873 }
874
875 PathDiagnosticPiece* p =
876 PDB.getReport().VisitNode(N, NextNode, PDB.getGraph(),
877 PDB.getBugReporter(), PDB.getNodeMapClosure());
878
879 if (p) {
880 GenExtAddEdge(PD, PDB, p->getLocation(), PrevLoc);
881 PD.push_front(p);
882 }
883 }
884}
885
886//===----------------------------------------------------------------------===//
Ted Kremenekcf118d42009-02-04 23:49:09 +0000887// Methods for BugType and subclasses.
888//===----------------------------------------------------------------------===//
889BugType::~BugType() {}
890void BugType::FlushReports(BugReporter &BR) {}
Ted Kremenekbb77e9b2008-05-01 22:50:36 +0000891
Ted Kremenekcf118d42009-02-04 23:49:09 +0000892//===----------------------------------------------------------------------===//
893// Methods for BugReport and subclasses.
894//===----------------------------------------------------------------------===//
895BugReport::~BugReport() {}
896RangedBugReport::~RangedBugReport() {}
897
898Stmt* BugReport::getStmt(BugReporter& BR) const {
Ted Kremenek200ed922008-05-02 23:21:21 +0000899 ProgramPoint ProgP = EndNode->getLocation();
Ted Kremenekbd7efa82008-04-17 23:44:37 +0000900 Stmt *S = NULL;
901
Ted Kremenekcf118d42009-02-04 23:49:09 +0000902 if (BlockEntrance* BE = dyn_cast<BlockEntrance>(&ProgP)) {
Ted Kremenekb697b102009-02-23 22:44:26 +0000903 if (BE->getBlock() == &BR.getCFG()->getExit()) S = GetPreviousStmt(EndNode);
Ted Kremenekcf118d42009-02-04 23:49:09 +0000904 }
905 if (!S) S = GetStmt(ProgP);
906
Ted Kremenekbb77e9b2008-05-01 22:50:36 +0000907 return S;
908}
909
910PathDiagnosticPiece*
911BugReport::getEndPath(BugReporter& BR,
Ted Kremenek3148eb42009-01-24 00:55:43 +0000912 const ExplodedNode<GRState>* EndPathNode) {
Ted Kremenekbb77e9b2008-05-01 22:50:36 +0000913
914 Stmt* S = getStmt(BR);
Ted Kremenek61f3e052008-04-03 04:42:52 +0000915
916 if (!S)
917 return NULL;
918
Ted Kremenekc9fa2f72008-05-01 23:13:35 +0000919 FullSourceLoc L(S->getLocStart(), BR.getContext().getSourceManager());
Ted Kremenek1fbfd5b2009-03-06 23:58:11 +0000920 PathDiagnosticPiece* P = new PathDiagnosticEventPiece(L, getDescription());
Ted Kremenek61f3e052008-04-03 04:42:52 +0000921
Ted Kremenekde7161f2008-04-03 18:00:37 +0000922 const SourceRange *Beg, *End;
Ted Kremenekbb77e9b2008-05-01 22:50:36 +0000923 getRanges(BR, Beg, End);
Ted Kremenekcf118d42009-02-04 23:49:09 +0000924
Ted Kremenekbb77e9b2008-05-01 22:50:36 +0000925 for (; Beg != End; ++Beg)
926 P->addRange(*Beg);
Ted Kremenek61f3e052008-04-03 04:42:52 +0000927
928 return P;
929}
930
Ted Kremenekbb77e9b2008-05-01 22:50:36 +0000931void BugReport::getRanges(BugReporter& BR, const SourceRange*& beg,
932 const SourceRange*& end) {
933
934 if (Expr* E = dyn_cast_or_null<Expr>(getStmt(BR))) {
935 R = E->getSourceRange();
Ted Kremenek9b5e5052009-02-27 20:05:10 +0000936 assert(R.isValid());
Ted Kremenekbb77e9b2008-05-01 22:50:36 +0000937 beg = &R;
938 end = beg+1;
939 }
940 else
941 beg = end = 0;
Ted Kremenekf1ae7052008-04-03 17:57:38 +0000942}
943
Ted Kremenekcf118d42009-02-04 23:49:09 +0000944SourceLocation BugReport::getLocation() const {
945 if (EndNode)
Ted Kremenek9b5e5052009-02-27 20:05:10 +0000946 if (Stmt* S = GetCurrentOrPreviousStmt(EndNode)) {
947 // For member expressions, return the location of the '.' or '->'.
948 if (MemberExpr* ME = dyn_cast<MemberExpr>(S))
949 return ME->getMemberLoc();
950
Ted Kremenekcf118d42009-02-04 23:49:09 +0000951 return S->getLocStart();
Ted Kremenek9b5e5052009-02-27 20:05:10 +0000952 }
Ted Kremenekcf118d42009-02-04 23:49:09 +0000953
954 return FullSourceLoc();
Ted Kremenekd2f642b2008-04-14 17:39:48 +0000955}
956
Ted Kremenek3148eb42009-01-24 00:55:43 +0000957PathDiagnosticPiece* BugReport::VisitNode(const ExplodedNode<GRState>* N,
958 const ExplodedNode<GRState>* PrevN,
959 const ExplodedGraph<GRState>& G,
Ted Kremenekfe9e5432009-02-18 03:48:14 +0000960 BugReporter& BR,
961 NodeResolver &NR) {
Ted Kremenek50a6d0c2008-04-09 21:41:14 +0000962 return NULL;
963}
964
Ted Kremenekcf118d42009-02-04 23:49:09 +0000965//===----------------------------------------------------------------------===//
966// Methods for BugReporter and subclasses.
967//===----------------------------------------------------------------------===//
968
969BugReportEquivClass::~BugReportEquivClass() {
970 for (iterator I=begin(), E=end(); I!=E; ++I) delete *I;
971}
972
973GRBugReporter::~GRBugReporter() { FlushReports(); }
974BugReporterData::~BugReporterData() {}
975
976ExplodedGraph<GRState>&
977GRBugReporter::getGraph() { return Eng.getGraph(); }
978
979GRStateManager&
980GRBugReporter::getStateManager() { return Eng.getStateManager(); }
981
982BugReporter::~BugReporter() { FlushReports(); }
983
984void BugReporter::FlushReports() {
985 if (BugTypes.isEmpty())
986 return;
987
988 // First flush the warnings for each BugType. This may end up creating new
989 // warnings and new BugTypes. Because ImmutableSet is a functional data
990 // structure, we do not need to worry about the iterators being invalidated.
991 for (BugTypesTy::iterator I=BugTypes.begin(), E=BugTypes.end(); I!=E; ++I)
992 const_cast<BugType*>(*I)->FlushReports(*this);
993
994 // Iterate through BugTypes a second time. BugTypes may have been updated
995 // with new BugType objects and new warnings.
996 for (BugTypesTy::iterator I=BugTypes.begin(), E=BugTypes.end(); I!=E; ++I) {
997 BugType *BT = const_cast<BugType*>(*I);
998
999 typedef llvm::FoldingSet<BugReportEquivClass> SetTy;
1000 SetTy& EQClasses = BT->EQClasses;
1001
1002 for (SetTy::iterator EI=EQClasses.begin(), EE=EQClasses.end(); EI!=EE;++EI){
1003 BugReportEquivClass& EQ = *EI;
1004 FlushReport(EQ);
1005 }
Ted Kremeneka43a1eb2008-04-23 23:02:12 +00001006
Ted Kremenekcf118d42009-02-04 23:49:09 +00001007 // Delete the BugType object. This will also delete the equivalence
1008 // classes.
1009 delete BT;
Ted Kremenek94826a72008-04-03 04:59:14 +00001010 }
Ted Kremenekcf118d42009-02-04 23:49:09 +00001011
1012 // Remove all references to the BugType objects.
1013 BugTypes = F.GetEmptySet();
1014}
1015
1016//===----------------------------------------------------------------------===//
1017// PathDiagnostics generation.
1018//===----------------------------------------------------------------------===//
1019
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001020static std::pair<std::pair<ExplodedGraph<GRState>*, NodeBackMap*>,
Ted Kremenekcf118d42009-02-04 23:49:09 +00001021 std::pair<ExplodedNode<GRState>*, unsigned> >
1022MakeReportGraph(const ExplodedGraph<GRState>* G,
1023 const ExplodedNode<GRState>** NStart,
1024 const ExplodedNode<GRState>** NEnd) {
Ted Kremenek94826a72008-04-03 04:59:14 +00001025
Ted Kremenekcf118d42009-02-04 23:49:09 +00001026 // Create the trimmed graph. It will contain the shortest paths from the
1027 // error nodes to the root. In the new graph we should only have one
1028 // error node unless there are two or more error nodes with the same minimum
1029 // path length.
1030 ExplodedGraph<GRState>* GTrim;
1031 InterExplodedGraphMap<GRState>* NMap;
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001032
1033 llvm::DenseMap<const void*, const void*> InverseMap;
1034 llvm::tie(GTrim, NMap) = G->Trim(NStart, NEnd, &InverseMap);
Ted Kremenekcf118d42009-02-04 23:49:09 +00001035
1036 // Create owning pointers for GTrim and NMap just to ensure that they are
1037 // released when this function exists.
1038 llvm::OwningPtr<ExplodedGraph<GRState> > AutoReleaseGTrim(GTrim);
1039 llvm::OwningPtr<InterExplodedGraphMap<GRState> > AutoReleaseNMap(NMap);
1040
1041 // Find the (first) error node in the trimmed graph. We just need to consult
1042 // the node map (NMap) which maps from nodes in the original graph to nodes
1043 // in the new graph.
1044 const ExplodedNode<GRState>* N = 0;
1045 unsigned NodeIndex = 0;
1046
1047 for (const ExplodedNode<GRState>** I = NStart; I != NEnd; ++I)
1048 if ((N = NMap->getMappedNode(*I))) {
1049 NodeIndex = (I - NStart) / sizeof(*I);
1050 break;
1051 }
1052
1053 assert(N && "No error node found in the trimmed graph.");
1054
1055 // Create a new (third!) graph with a single path. This is the graph
1056 // that will be returned to the caller.
Ted Kremenek3148eb42009-01-24 00:55:43 +00001057 ExplodedGraph<GRState> *GNew =
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001058 new ExplodedGraph<GRState>(GTrim->getCFG(), GTrim->getCodeDecl(),
1059 GTrim->getContext());
Ted Kremenekcf118d42009-02-04 23:49:09 +00001060
Ted Kremenek10aa5542009-03-12 23:41:59 +00001061 // Sometimes the trimmed graph can contain a cycle. Perform a reverse BFS
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001062 // to the root node, and then construct a new graph that contains only
1063 // a single path.
Ted Kremenek3148eb42009-01-24 00:55:43 +00001064 llvm::DenseMap<const void*,unsigned> Visited;
Ted Kremenek10aa5542009-03-12 23:41:59 +00001065 std::queue<const ExplodedNode<GRState>*> WS;
1066 WS.push(N);
1067
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001068 unsigned cnt = 0;
Ted Kremenek3148eb42009-01-24 00:55:43 +00001069 const ExplodedNode<GRState>* Root = 0;
Ted Kremenekc1da4412008-06-17 19:14:06 +00001070
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001071 while (!WS.empty()) {
Ted Kremenek10aa5542009-03-12 23:41:59 +00001072 const ExplodedNode<GRState>* Node = WS.front();
1073 WS.pop();
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001074
1075 if (Visited.find(Node) != Visited.end())
1076 continue;
1077
1078 Visited[Node] = cnt++;
1079
1080 if (Node->pred_empty()) {
1081 Root = Node;
1082 break;
1083 }
1084
Ted Kremenek3148eb42009-01-24 00:55:43 +00001085 for (ExplodedNode<GRState>::const_pred_iterator I=Node->pred_begin(),
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001086 E=Node->pred_end(); I!=E; ++I)
Ted Kremenek10aa5542009-03-12 23:41:59 +00001087 WS.push(*I);
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001088 }
Ted Kremenekcf118d42009-02-04 23:49:09 +00001089
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001090 assert (Root);
1091
Ted Kremenek10aa5542009-03-12 23:41:59 +00001092 // Now walk from the root down the BFS path, always taking the successor
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001093 // with the lowest number.
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001094 ExplodedNode<GRState> *Last = 0, *First = 0;
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001095 NodeBackMap *BM = new NodeBackMap();
Ted Kremenekcf118d42009-02-04 23:49:09 +00001096
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001097 for ( N = Root ;;) {
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001098 // Lookup the number associated with the current node.
Ted Kremenek3148eb42009-01-24 00:55:43 +00001099 llvm::DenseMap<const void*,unsigned>::iterator I = Visited.find(N);
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001100 assert (I != Visited.end());
1101
1102 // Create the equivalent node in the new graph with the same state
1103 // and location.
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001104 ExplodedNode<GRState>* NewN =
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001105 GNew->getNode(N->getLocation(), N->getState());
1106
1107 // Store the mapping to the original node.
1108 llvm::DenseMap<const void*, const void*>::iterator IMitr=InverseMap.find(N);
1109 assert(IMitr != InverseMap.end() && "No mapping to original node.");
1110 (*BM)[NewN] = (const ExplodedNode<GRState>*) IMitr->second;
Ted Kremenekcf118d42009-02-04 23:49:09 +00001111
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001112 // Link up the new node with the previous node.
1113 if (Last)
1114 NewN->addPredecessor(Last);
Ted Kremeneka43a1eb2008-04-23 23:02:12 +00001115
1116 Last = NewN;
Ted Kremenekcf118d42009-02-04 23:49:09 +00001117
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001118 // Are we at the final node?
1119 if (I->second == 0) {
1120 First = NewN;
Ted Kremenekc1da4412008-06-17 19:14:06 +00001121 break;
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001122 }
Ted Kremenekcf118d42009-02-04 23:49:09 +00001123
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001124 // Find the next successor node. We choose the node that is marked
1125 // with the lowest DFS number.
Ted Kremenek3148eb42009-01-24 00:55:43 +00001126 ExplodedNode<GRState>::const_succ_iterator SI = N->succ_begin();
1127 ExplodedNode<GRState>::const_succ_iterator SE = N->succ_end();
Ted Kremenekc1da4412008-06-17 19:14:06 +00001128 N = 0;
1129
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001130 for (unsigned MinVal = 0; SI != SE; ++SI) {
Ted Kremenekcf118d42009-02-04 23:49:09 +00001131
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001132 I = Visited.find(*SI);
1133
1134 if (I == Visited.end())
1135 continue;
1136
1137 if (!N || I->second < MinVal) {
1138 N = *SI;
1139 MinVal = I->second;
Ted Kremenekc1da4412008-06-17 19:14:06 +00001140 }
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001141 }
Ted Kremenekcf118d42009-02-04 23:49:09 +00001142
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001143 assert (N);
Ted Kremeneka43a1eb2008-04-23 23:02:12 +00001144 }
Ted Kremenekcf118d42009-02-04 23:49:09 +00001145
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001146 assert (First);
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001147 return std::make_pair(std::make_pair(GNew, BM),
1148 std::make_pair(First, NodeIndex));
Ted Kremeneka43a1eb2008-04-23 23:02:12 +00001149}
1150
Ted Kremenek0e5c8d42009-03-10 05:16:17 +00001151/// CompactPathDiagnostic - This function postprocesses a PathDiagnostic object
1152/// and collapses PathDiagosticPieces that are expanded by macros.
1153static void CompactPathDiagnostic(PathDiagnostic &PD, const SourceManager& SM) {
1154 typedef std::vector<std::pair<PathDiagnosticMacroPiece*, SourceLocation> >
1155 MacroStackTy;
1156
1157 typedef std::vector<PathDiagnosticPiece*>
1158 PiecesTy;
1159
1160 MacroStackTy MacroStack;
1161 PiecesTy Pieces;
1162
1163 for (PathDiagnostic::iterator I = PD.begin(), E = PD.end(); I!=E; ++I) {
1164 // Get the location of the PathDiagnosticPiece.
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +00001165 const FullSourceLoc Loc = I->getLocation().asLocation();
Ted Kremenek0e5c8d42009-03-10 05:16:17 +00001166
1167 // Determine the instantiation location, which is the location we group
1168 // related PathDiagnosticPieces.
1169 SourceLocation InstantiationLoc = Loc.isMacroID() ?
1170 SM.getInstantiationLoc(Loc) :
1171 SourceLocation();
1172
1173 if (Loc.isFileID()) {
1174 MacroStack.clear();
1175 Pieces.push_back(&*I);
1176 continue;
1177 }
1178
1179 assert(Loc.isMacroID());
1180
1181 // Is the PathDiagnosticPiece within the same macro group?
1182 if (!MacroStack.empty() && InstantiationLoc == MacroStack.back().second) {
1183 MacroStack.back().first->push_back(&*I);
1184 continue;
1185 }
1186
1187 // We aren't in the same group. Are we descending into a new macro
1188 // or are part of an old one?
1189 PathDiagnosticMacroPiece *MacroGroup = 0;
1190
1191 SourceLocation ParentInstantiationLoc = InstantiationLoc.isMacroID() ?
1192 SM.getInstantiationLoc(Loc) :
1193 SourceLocation();
1194
1195 // Walk the entire macro stack.
1196 while (!MacroStack.empty()) {
1197 if (InstantiationLoc == MacroStack.back().second) {
1198 MacroGroup = MacroStack.back().first;
1199 break;
1200 }
1201
1202 if (ParentInstantiationLoc == MacroStack.back().second) {
1203 MacroGroup = MacroStack.back().first;
1204 break;
1205 }
1206
1207 MacroStack.pop_back();
1208 }
1209
1210 if (!MacroGroup || ParentInstantiationLoc == MacroStack.back().second) {
1211 // Create a new macro group and add it to the stack.
1212 PathDiagnosticMacroPiece *NewGroup = new PathDiagnosticMacroPiece(Loc);
1213
1214 if (MacroGroup)
1215 MacroGroup->push_back(NewGroup);
1216 else {
1217 assert(InstantiationLoc.isFileID());
1218 Pieces.push_back(NewGroup);
1219 }
1220
1221 MacroGroup = NewGroup;
1222 MacroStack.push_back(std::make_pair(MacroGroup, InstantiationLoc));
1223 }
1224
1225 // Finally, add the PathDiagnosticPiece to the group.
1226 MacroGroup->push_back(&*I);
1227 }
1228
1229 // Now take the pieces and construct a new PathDiagnostic.
1230 PD.resetPath(false);
1231
1232 for (PiecesTy::iterator I=Pieces.begin(), E=Pieces.end(); I!=E; ++I) {
1233 if (PathDiagnosticMacroPiece *MP=dyn_cast<PathDiagnosticMacroPiece>(*I))
1234 if (!MP->containsEvent()) {
1235 delete MP;
1236 continue;
1237 }
1238
1239 PD.push_back(*I);
1240 }
1241}
1242
Ted Kremenek7dc86642009-03-31 20:22:36 +00001243void GRBugReporter::GeneratePathDiagnostic(PathDiagnostic& PD,
1244 BugReportEquivClass& EQ) {
1245
1246 std::vector<const ExplodedNode<GRState>*> Nodes;
1247
Ted Kremenekcf118d42009-02-04 23:49:09 +00001248 for (BugReportEquivClass::iterator I=EQ.begin(), E=EQ.end(); I!=E; ++I) {
1249 const ExplodedNode<GRState>* N = I->getEndNode();
1250 if (N) Nodes.push_back(N);
1251 }
1252
1253 if (Nodes.empty())
1254 return;
Ted Kremeneka43a1eb2008-04-23 23:02:12 +00001255
1256 // Construct a new graph that contains only a single path from the error
Ted Kremenekcf118d42009-02-04 23:49:09 +00001257 // node to a root.
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001258 const std::pair<std::pair<ExplodedGraph<GRState>*, NodeBackMap*>,
Ted Kremenek7dc86642009-03-31 20:22:36 +00001259 std::pair<ExplodedNode<GRState>*, unsigned> >&
1260 GPair = MakeReportGraph(&getGraph(), &Nodes[0], &Nodes[0] + Nodes.size());
Ted Kremeneka43a1eb2008-04-23 23:02:12 +00001261
Ted Kremenekcf118d42009-02-04 23:49:09 +00001262 // Find the BugReport with the original location.
1263 BugReport *R = 0;
1264 unsigned i = 0;
1265 for (BugReportEquivClass::iterator I=EQ.begin(), E=EQ.end(); I!=E; ++I, ++i)
1266 if (i == GPair.second.second) { R = *I; break; }
1267
1268 assert(R && "No original report found for sliced graph.");
Ted Kremeneka43a1eb2008-04-23 23:02:12 +00001269
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001270 llvm::OwningPtr<ExplodedGraph<GRState> > ReportGraph(GPair.first.first);
1271 llvm::OwningPtr<NodeBackMap> BackMap(GPair.first.second);
Ted Kremenekcf118d42009-02-04 23:49:09 +00001272 const ExplodedNode<GRState> *N = GPair.second.first;
Ted Kremenek7dc86642009-03-31 20:22:36 +00001273
Ted Kremenekcf118d42009-02-04 23:49:09 +00001274 // Start building the path diagnostic...
1275 if (PathDiagnosticPiece* Piece = R->getEndPath(*this, N))
Ted Kremenekbd7efa82008-04-17 23:44:37 +00001276 PD.push_back(Piece);
1277 else
1278 return;
Ted Kremenek7dc86642009-03-31 20:22:36 +00001279
1280 PathDiagnosticBuilder PDB(*this, ReportGraph.get(), R, BackMap.get(),
1281 getStateManager().getCodeDecl(),
Ted Kremenekbabdd7b2009-03-27 05:06:10 +00001282 getPathDiagnosticClient());
Ted Kremenekbd7efa82008-04-17 23:44:37 +00001283
Ted Kremenek7dc86642009-03-31 20:22:36 +00001284 switch (PDB.getGenerationScheme()) {
1285 case PathDiagnosticClient::Extensive:
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +00001286 GenerateExtensivePathDiagnostic(PD,PDB, N);
1287 break;
Ted Kremenek7dc86642009-03-31 20:22:36 +00001288 case PathDiagnosticClient::Minimal:
1289 GenerateMinimalPathDiagnostic(PD, PDB, N);
1290 break;
1291 }
1292
1293 // After constructing the full PathDiagnostic, do a pass over it to compact
1294 // PathDiagnosticPieces that occur within a macro.
1295 CompactPathDiagnostic(PD, PDB.getSourceManager());
1296}
1297
Ted Kremenekcf118d42009-02-04 23:49:09 +00001298void BugReporter::Register(BugType *BT) {
1299 BugTypes = F.Add(BugTypes, BT);
Ted Kremenek76d90c82008-05-16 18:33:14 +00001300}
1301
Ted Kremenekcf118d42009-02-04 23:49:09 +00001302void BugReporter::EmitReport(BugReport* R) {
1303 // Compute the bug report's hash to determine its equivalence class.
1304 llvm::FoldingSetNodeID ID;
1305 R->Profile(ID);
Ted Kremenek61f3e052008-04-03 04:42:52 +00001306
Ted Kremenekcf118d42009-02-04 23:49:09 +00001307 // Lookup the equivance class. If there isn't one, create it.
1308 BugType& BT = R->getBugType();
1309 Register(&BT);
1310 void *InsertPos;
1311 BugReportEquivClass* EQ = BT.EQClasses.FindNodeOrInsertPos(ID, InsertPos);
1312
1313 if (!EQ) {
1314 EQ = new BugReportEquivClass(R);
1315 BT.EQClasses.InsertNode(EQ, InsertPos);
1316 }
1317 else
1318 EQ->AddReport(R);
Ted Kremenek61f3e052008-04-03 04:42:52 +00001319}
1320
Ted Kremenekcf118d42009-02-04 23:49:09 +00001321void BugReporter::FlushReport(BugReportEquivClass& EQ) {
1322 assert(!EQ.Reports.empty());
1323 BugReport &R = **EQ.begin();
1324
1325 // FIXME: Make sure we use the 'R' for the path that was actually used.
1326 // Probably doesn't make a difference in practice.
1327 BugType& BT = R.getBugType();
1328
1329 llvm::OwningPtr<PathDiagnostic> D(new PathDiagnostic(R.getBugType().getName(),
1330 R.getDescription(),
1331 BT.getCategory()));
1332 GeneratePathDiagnostic(*D.get(), EQ);
Ted Kremenek072192b2008-04-30 23:47:44 +00001333
1334 // Get the meta data.
Ted Kremenek072192b2008-04-30 23:47:44 +00001335 std::pair<const char**, const char**> Meta = R.getExtraDescriptiveText();
Ted Kremenek3148eb42009-01-24 00:55:43 +00001336 for (const char** s = Meta.first; s != Meta.second; ++s) D->addMeta(*s);
Ted Kremenek75840e12008-04-18 01:56:37 +00001337
Ted Kremenek3148eb42009-01-24 00:55:43 +00001338 // Emit a summary diagnostic to the regular Diagnostics engine.
Ted Kremenekc0959972008-07-02 21:24:01 +00001339 PathDiagnosticClient* PD = getPathDiagnosticClient();
Ted Kremenek3148eb42009-01-24 00:55:43 +00001340 const SourceRange *Beg = 0, *End = 0;
1341 R.getRanges(*this, Beg, End);
1342 Diagnostic& Diag = getDiagnostic();
Ted Kremenekcf118d42009-02-04 23:49:09 +00001343 FullSourceLoc L(R.getLocation(), getSourceManager());
Ted Kremenekd90e7082009-02-07 22:36:41 +00001344 unsigned ErrorDiag = Diag.getCustomDiagID(Diagnostic::Warning,
1345 R.getDescription().c_str());
Ted Kremenek57202072008-07-14 17:40:50 +00001346
Ted Kremenek3148eb42009-01-24 00:55:43 +00001347 switch (End-Beg) {
Chris Lattner0a14eee2008-11-18 07:04:44 +00001348 default: assert(0 && "Don't handle this many ranges yet!");
1349 case 0: Diag.Report(L, ErrorDiag); break;
1350 case 1: Diag.Report(L, ErrorDiag) << Beg[0]; break;
1351 case 2: Diag.Report(L, ErrorDiag) << Beg[0] << Beg[1]; break;
1352 case 3: Diag.Report(L, ErrorDiag) << Beg[0] << Beg[1] << Beg[2]; break;
Ted Kremenek2f0e89e2008-04-18 22:56:53 +00001353 }
Ted Kremenek3148eb42009-01-24 00:55:43 +00001354
1355 // Emit a full diagnostic for the path if we have a PathDiagnosticClient.
1356 if (!PD)
1357 return;
1358
1359 if (D->empty()) {
Ted Kremenek1fbfd5b2009-03-06 23:58:11 +00001360 PathDiagnosticPiece* piece =
1361 new PathDiagnosticEventPiece(L, R.getDescription());
1362
Ted Kremenek3148eb42009-01-24 00:55:43 +00001363 for ( ; Beg != End; ++Beg) piece->addRange(*Beg);
1364 D->push_back(piece);
1365 }
1366
1367 PD->HandlePathDiagnostic(D.take());
Ted Kremenek61f3e052008-04-03 04:42:52 +00001368}
Ted Kremenek57202072008-07-14 17:40:50 +00001369
Ted Kremenek8c036c72008-09-20 04:23:38 +00001370void BugReporter::EmitBasicReport(const char* name, const char* str,
1371 SourceLocation Loc,
1372 SourceRange* RBeg, unsigned NumRanges) {
1373 EmitBasicReport(name, "", str, Loc, RBeg, NumRanges);
1374}
Ted Kremenekcf118d42009-02-04 23:49:09 +00001375
Ted Kremenek8c036c72008-09-20 04:23:38 +00001376void BugReporter::EmitBasicReport(const char* name, const char* category,
1377 const char* str, SourceLocation Loc,
1378 SourceRange* RBeg, unsigned NumRanges) {
1379
Ted Kremenekcf118d42009-02-04 23:49:09 +00001380 // 'BT' will be owned by BugReporter as soon as we call 'EmitReport'.
1381 BugType *BT = new BugType(name, category);
Chris Lattner0a14eee2008-11-18 07:04:44 +00001382 FullSourceLoc L = getContext().getFullLoc(Loc);
Ted Kremenekcf118d42009-02-04 23:49:09 +00001383 RangedBugReport *R = new DiagBugReport(*BT, str, L);
1384 for ( ; NumRanges > 0 ; --NumRanges, ++RBeg) R->addRange(*RBeg);
1385 EmitReport(R);
Ted Kremenek57202072008-07-14 17:40:50 +00001386}