blob: 397d28b6e2e068a08ae984b1543350d194b9d78f [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/AST/ASTContext.h"
18#include "clang/AST/CFG.h"
19#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 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() {
Douglas Gregor72971342009-04-18 00:02:19 +0000143 if (PM.get() == 0) PM.reset(new ParentMap(CodeDecl.getBody(getContext())));
Ted Kremenek00605e02009-03-27 20:55:39 +0000144 return *PM.get();
145 }
Ted Kremenekbabdd7b2009-03-27 05:06:10 +0000146
Ted Kremenekc3f83ad2009-04-01 17:18:21 +0000147 const Stmt *getParent(const Stmt *S) {
148 return getParentMap().getParent(S);
149 }
150
Ted Kremenek51a735c2009-04-01 17:52:26 +0000151 const CFG& getCFG() {
152 return *BR.getCFG();
153 }
154
155 const Decl& getCodeDecl() {
156 return BR.getStateManager().getCodeDecl();
157 }
158
Ted Kremenek7dc86642009-03-31 20:22:36 +0000159 ExplodedGraph<GRState>& getGraph() { return *ReportGraph; }
160 NodeMapClosure& getNodeMapClosure() { return NMC; }
161 ASTContext& getContext() { return BR.getContext(); }
162 SourceManager& getSourceManager() { return SMgr; }
163 BugReport& getReport() { return *R; }
164 GRBugReporter& getBugReporter() { return BR; }
165 GRStateManager& getStateManager() { return BR.getStateManager(); }
Douglas Gregor72971342009-04-18 00:02:19 +0000166
Ted Kremenekd8c938b2009-03-27 21:16:25 +0000167 PathDiagnosticLocation getEnclosingStmtLocation(const Stmt *S);
168
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000169 PathDiagnosticLocation
170 getEnclosingStmtLocation(const PathDiagnosticLocation &L) {
171 if (const Stmt *S = L.asStmt())
172 return getEnclosingStmtLocation(S);
173
174 return L;
175 }
176
Ted Kremenek7dc86642009-03-31 20:22:36 +0000177 PathDiagnosticClient::PathGenerationScheme getGenerationScheme() const {
178 return PDC ? PDC->getGenerationScheme() : PathDiagnosticClient::Extensive;
179 }
180
Ted Kremenekbabdd7b2009-03-27 05:06:10 +0000181 bool supportsLogicalOpControlFlow() const {
182 return PDC ? PDC->supportsLogicalOpControlFlow() : true;
183 }
184};
185} // end anonymous namespace
186
Ted Kremenek00605e02009-03-27 20:55:39 +0000187PathDiagnosticLocation
188PathDiagnosticBuilder::ExecutionContinues(const ExplodedNode<GRState>* N) {
189 if (Stmt *S = GetNextStmt(N))
190 return PathDiagnosticLocation(S, SMgr);
191
Sebastian Redld3a413d2009-04-26 20:35:05 +0000192 return FullSourceLoc(CodeDecl.getBodyRBrace(getContext()), SMgr);
Ted Kremenek082cb8d2009-03-12 18:41:53 +0000193}
194
Ted Kremenek00605e02009-03-27 20:55:39 +0000195PathDiagnosticLocation
Ted Kremenekbabdd7b2009-03-27 05:06:10 +0000196PathDiagnosticBuilder::ExecutionContinues(llvm::raw_string_ostream& os,
197 const ExplodedNode<GRState>* N) {
198
Ted Kremenek143ca222008-05-06 18:11:09 +0000199 // Slow, but probably doesn't matter.
Ted Kremenekb697b102009-02-23 22:44:26 +0000200 if (os.str().empty())
201 os << ' ';
Ted Kremenek143ca222008-05-06 18:11:09 +0000202
Ted Kremenek00605e02009-03-27 20:55:39 +0000203 const PathDiagnosticLocation &Loc = ExecutionContinues(N);
Ted Kremenek082cb8d2009-03-12 18:41:53 +0000204
Ted Kremenek00605e02009-03-27 20:55:39 +0000205 if (Loc.asStmt())
Ted Kremenekb697b102009-02-23 22:44:26 +0000206 os << "Execution continues on line "
Ted Kremenek00605e02009-03-27 20:55:39 +0000207 << SMgr.getInstantiationLineNumber(Loc.asLocation()) << '.';
Ted Kremenekb697b102009-02-23 22:44:26 +0000208 else
Ted Kremenekb479dad2009-02-23 23:13:51 +0000209 os << "Execution jumps to the end of the "
Ted Kremenekbabdd7b2009-03-27 05:06:10 +0000210 << (isa<ObjCMethodDecl>(CodeDecl) ? "method" : "function") << '.';
Ted Kremenek082cb8d2009-03-12 18:41:53 +0000211
212 return Loc;
Ted Kremenek143ca222008-05-06 18:11:09 +0000213}
214
Ted Kremenekd8c938b2009-03-27 21:16:25 +0000215PathDiagnosticLocation
216PathDiagnosticBuilder::getEnclosingStmtLocation(const Stmt *S) {
217 assert(S && "Null Stmt* passed to getEnclosingStmtLocation");
218 ParentMap &P = getParentMap();
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000219
220 while (isa<DeclStmt>(S) || isa<Expr>(S)) {
Ted Kremenekd8c938b2009-03-27 21:16:25 +0000221 const Stmt *Parent = P.getParent(S);
222
Ted Kremenekaf3e3d52009-03-28 03:37:59 +0000223 if (!Parent)
224 break;
Ted Kremenekd8c938b2009-03-27 21:16:25 +0000225
Ted Kremenekaf3e3d52009-03-28 03:37:59 +0000226 switch (Parent->getStmtClass()) {
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000227 case Stmt::BinaryOperatorClass: {
228 const BinaryOperator *B = cast<BinaryOperator>(Parent);
229 if (B->isLogicalOp())
230 return PathDiagnosticLocation(S, SMgr);
231 break;
232 }
233
Ted Kremenekaf3e3d52009-03-28 03:37:59 +0000234 case Stmt::CompoundStmtClass:
235 case Stmt::StmtExprClass:
Ted Kremenek1d9a23a2009-03-28 04:08:14 +0000236 return PathDiagnosticLocation(S, SMgr);
237 case Stmt::ChooseExprClass:
238 // Similar to '?' if we are referring to condition, just have the edge
239 // point to the entire choose expression.
240 if (cast<ChooseExpr>(Parent)->getCond() == S)
241 return PathDiagnosticLocation(Parent, SMgr);
242 else
243 return PathDiagnosticLocation(S, SMgr);
244 case Stmt::ConditionalOperatorClass:
245 // For '?', if we are referring to condition, just have the edge point
246 // to the entire '?' expression.
247 if (cast<ConditionalOperator>(Parent)->getCond() == S)
248 return PathDiagnosticLocation(Parent, SMgr);
249 else
250 return PathDiagnosticLocation(S, SMgr);
Ted Kremenekaf3e3d52009-03-28 03:37:59 +0000251 case Stmt::DoStmtClass:
252 if (cast<DoStmt>(Parent)->getCond() != S)
253 return PathDiagnosticLocation(S, SMgr);
254 break;
255 case Stmt::ForStmtClass:
256 if (cast<ForStmt>(Parent)->getBody() == S)
257 return PathDiagnosticLocation(S, SMgr);
258 break;
259 case Stmt::IfStmtClass:
260 if (cast<IfStmt>(Parent)->getCond() != S)
261 return PathDiagnosticLocation(S, SMgr);
262 break;
263 case Stmt::ObjCForCollectionStmtClass:
264 if (cast<ObjCForCollectionStmt>(Parent)->getBody() == S)
265 return PathDiagnosticLocation(S, SMgr);
266 break;
267 case Stmt::WhileStmtClass:
268 if (cast<WhileStmt>(Parent)->getCond() != S)
269 return PathDiagnosticLocation(S, SMgr);
270 break;
271 default:
272 break;
273 }
274
Ted Kremenekd8c938b2009-03-27 21:16:25 +0000275 S = Parent;
276 }
277
278 assert(S && "Cannot have null Stmt for PathDiagnosticLocation");
279 return PathDiagnosticLocation(S, SMgr);
280}
281
Ted Kremenekcf118d42009-02-04 23:49:09 +0000282//===----------------------------------------------------------------------===//
Ted Kremenek31061982009-03-31 23:00:32 +0000283// ScanNotableSymbols: closure-like callback for scanning Store bindings.
284//===----------------------------------------------------------------------===//
285
286static const VarDecl*
287GetMostRecentVarDeclBinding(const ExplodedNode<GRState>* N,
288 GRStateManager& VMgr, SVal X) {
289
290 for ( ; N ; N = N->pred_empty() ? 0 : *N->pred_begin()) {
291
292 ProgramPoint P = N->getLocation();
293
294 if (!isa<PostStmt>(P))
295 continue;
296
297 DeclRefExpr* DR = dyn_cast<DeclRefExpr>(cast<PostStmt>(P).getStmt());
298
299 if (!DR)
300 continue;
301
302 SVal Y = VMgr.GetSVal(N->getState(), DR);
303
304 if (X != Y)
305 continue;
306
307 VarDecl* VD = dyn_cast<VarDecl>(DR->getDecl());
308
309 if (!VD)
310 continue;
311
312 return VD;
313 }
314
315 return 0;
316}
317
318namespace {
319class VISIBILITY_HIDDEN NotableSymbolHandler
320: public StoreManager::BindingsHandler {
321
322 SymbolRef Sym;
323 const GRState* PrevSt;
324 const Stmt* S;
325 GRStateManager& VMgr;
326 const ExplodedNode<GRState>* Pred;
327 PathDiagnostic& PD;
328 BugReporter& BR;
329
330public:
331
332 NotableSymbolHandler(SymbolRef sym, const GRState* prevst, const Stmt* s,
333 GRStateManager& vmgr, const ExplodedNode<GRState>* pred,
334 PathDiagnostic& pd, BugReporter& br)
335 : Sym(sym), PrevSt(prevst), S(s), VMgr(vmgr), Pred(pred), PD(pd), BR(br) {}
336
337 bool HandleBinding(StoreManager& SMgr, Store store, const MemRegion* R,
338 SVal V) {
339
340 SymbolRef ScanSym = V.getAsSymbol();
341
342 if (ScanSym != Sym)
343 return true;
344
345 // Check if the previous state has this binding.
346 SVal X = VMgr.GetSVal(PrevSt, loc::MemRegionVal(R));
347
348 if (X == V) // Same binding?
349 return true;
350
351 // Different binding. Only handle assignments for now. We don't pull
352 // this check out of the loop because we will eventually handle other
353 // cases.
354
355 VarDecl *VD = 0;
356
357 if (const BinaryOperator* B = dyn_cast<BinaryOperator>(S)) {
358 if (!B->isAssignmentOp())
359 return true;
360
361 // What variable did we assign to?
362 DeclRefExpr* DR = dyn_cast<DeclRefExpr>(B->getLHS()->IgnoreParenCasts());
363
364 if (!DR)
365 return true;
366
367 VD = dyn_cast<VarDecl>(DR->getDecl());
368 }
369 else if (const DeclStmt* DS = dyn_cast<DeclStmt>(S)) {
370 // FIXME: Eventually CFGs won't have DeclStmts. Right now we
371 // assume that each DeclStmt has a single Decl. This invariant
372 // holds by contruction in the CFG.
373 VD = dyn_cast<VarDecl>(*DS->decl_begin());
374 }
375
376 if (!VD)
377 return true;
378
379 // What is the most recently referenced variable with this binding?
380 const VarDecl* MostRecent = GetMostRecentVarDeclBinding(Pred, VMgr, V);
381
382 if (!MostRecent)
383 return true;
384
385 // Create the diagnostic.
386 FullSourceLoc L(S->getLocStart(), BR.getSourceManager());
387
388 if (Loc::IsLocType(VD->getType())) {
389 std::string msg = "'" + std::string(VD->getNameAsString()) +
390 "' now aliases '" + MostRecent->getNameAsString() + "'";
391
392 PD.push_front(new PathDiagnosticEventPiece(L, msg));
393 }
394
395 return true;
396 }
397};
398}
399
400static void HandleNotableSymbol(const ExplodedNode<GRState>* N,
401 const Stmt* S,
402 SymbolRef Sym, BugReporter& BR,
403 PathDiagnostic& PD) {
404
405 const ExplodedNode<GRState>* Pred = N->pred_empty() ? 0 : *N->pred_begin();
406 const GRState* PrevSt = Pred ? Pred->getState() : 0;
407
408 if (!PrevSt)
409 return;
410
411 // Look at the region bindings of the current state that map to the
412 // specified symbol. Are any of them not in the previous state?
413 GRStateManager& VMgr = cast<GRBugReporter>(BR).getStateManager();
414 NotableSymbolHandler H(Sym, PrevSt, S, VMgr, Pred, PD, BR);
415 cast<GRBugReporter>(BR).getStateManager().iterBindings(N->getState(), H);
416}
417
418namespace {
419class VISIBILITY_HIDDEN ScanNotableSymbols
420: public StoreManager::BindingsHandler {
421
422 llvm::SmallSet<SymbolRef, 10> AlreadyProcessed;
423 const ExplodedNode<GRState>* N;
424 Stmt* S;
425 GRBugReporter& BR;
426 PathDiagnostic& PD;
427
428public:
429 ScanNotableSymbols(const ExplodedNode<GRState>* n, Stmt* s, GRBugReporter& br,
430 PathDiagnostic& pd)
431 : N(n), S(s), BR(br), PD(pd) {}
432
433 bool HandleBinding(StoreManager& SMgr, Store store,
434 const MemRegion* R, SVal V) {
435
436 SymbolRef ScanSym = V.getAsSymbol();
437
438 if (!ScanSym)
439 return true;
440
441 if (!BR.isNotable(ScanSym))
442 return true;
443
444 if (AlreadyProcessed.count(ScanSym))
445 return true;
446
447 AlreadyProcessed.insert(ScanSym);
448
449 HandleNotableSymbol(N, S, ScanSym, BR, PD);
450 return true;
451 }
452};
453} // end anonymous namespace
454
455//===----------------------------------------------------------------------===//
456// "Minimal" path diagnostic generation algorithm.
457//===----------------------------------------------------------------------===//
458
Ted Kremenek14856d72009-04-06 23:06:54 +0000459static void CompactPathDiagnostic(PathDiagnostic &PD, const SourceManager& SM);
460
Ted Kremenek31061982009-03-31 23:00:32 +0000461static void GenerateMinimalPathDiagnostic(PathDiagnostic& PD,
462 PathDiagnosticBuilder &PDB,
463 const ExplodedNode<GRState> *N) {
464 ASTContext& Ctx = PDB.getContext();
465 SourceManager& SMgr = PDB.getSourceManager();
466 const ExplodedNode<GRState>* NextNode = N->pred_empty()
467 ? NULL : *(N->pred_begin());
468 while (NextNode) {
469 N = NextNode;
470 NextNode = GetPredecessorNode(N);
471
472 ProgramPoint P = N->getLocation();
473
474 if (const BlockEdge* BE = dyn_cast<BlockEdge>(&P)) {
475 CFGBlock* Src = BE->getSrc();
476 CFGBlock* Dst = BE->getDst();
477 Stmt* T = Src->getTerminator();
478
479 if (!T)
480 continue;
481
482 FullSourceLoc Start(T->getLocStart(), SMgr);
483
484 switch (T->getStmtClass()) {
485 default:
486 break;
487
488 case Stmt::GotoStmtClass:
489 case Stmt::IndirectGotoStmtClass: {
490 Stmt* S = GetNextStmt(N);
491
492 if (!S)
493 continue;
494
495 std::string sbuf;
496 llvm::raw_string_ostream os(sbuf);
497 const PathDiagnosticLocation &End = PDB.getEnclosingStmtLocation(S);
498
499 os << "Control jumps to line "
500 << End.asLocation().getInstantiationLineNumber();
501 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
502 os.str()));
503 break;
504 }
505
506 case Stmt::SwitchStmtClass: {
507 // Figure out what case arm we took.
508 std::string sbuf;
509 llvm::raw_string_ostream os(sbuf);
510
511 if (Stmt* S = Dst->getLabel()) {
512 PathDiagnosticLocation End(S, SMgr);
513
514 switch (S->getStmtClass()) {
515 default:
516 os << "No cases match in the switch statement. "
517 "Control jumps to line "
518 << End.asLocation().getInstantiationLineNumber();
519 break;
520 case Stmt::DefaultStmtClass:
521 os << "Control jumps to the 'default' case at line "
522 << End.asLocation().getInstantiationLineNumber();
523 break;
524
525 case Stmt::CaseStmtClass: {
526 os << "Control jumps to 'case ";
527 CaseStmt* Case = cast<CaseStmt>(S);
528 Expr* LHS = Case->getLHS()->IgnoreParenCasts();
529
530 // Determine if it is an enum.
531 bool GetRawInt = true;
532
533 if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(LHS)) {
534 // FIXME: Maybe this should be an assertion. Are there cases
535 // were it is not an EnumConstantDecl?
536 EnumConstantDecl* D =
537 dyn_cast<EnumConstantDecl>(DR->getDecl());
538
539 if (D) {
540 GetRawInt = false;
541 os << D->getNameAsString();
542 }
543 }
Eli Friedman9ec64d62009-04-26 19:04:51 +0000544
545 if (GetRawInt)
546 os << LHS->EvaluateAsInt(Ctx);
547
Ted Kremenek31061982009-03-31 23:00:32 +0000548 os << ":' at line "
549 << End.asLocation().getInstantiationLineNumber();
550 break;
551 }
552 }
553 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
554 os.str()));
555 }
556 else {
557 os << "'Default' branch taken. ";
558 const PathDiagnosticLocation &End = PDB.ExecutionContinues(os, N);
559 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
560 os.str()));
561 }
562
563 break;
564 }
565
566 case Stmt::BreakStmtClass:
567 case Stmt::ContinueStmtClass: {
568 std::string sbuf;
569 llvm::raw_string_ostream os(sbuf);
570 PathDiagnosticLocation End = PDB.ExecutionContinues(os, N);
571 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
572 os.str()));
573 break;
574 }
575
576 // Determine control-flow for ternary '?'.
577 case Stmt::ConditionalOperatorClass: {
578 std::string sbuf;
579 llvm::raw_string_ostream os(sbuf);
580 os << "'?' condition is ";
581
582 if (*(Src->succ_begin()+1) == Dst)
583 os << "false";
584 else
585 os << "true";
586
587 PathDiagnosticLocation End = PDB.ExecutionContinues(N);
588
589 if (const Stmt *S = End.asStmt())
590 End = PDB.getEnclosingStmtLocation(S);
591
592 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
593 os.str()));
594 break;
595 }
596
597 // Determine control-flow for short-circuited '&&' and '||'.
598 case Stmt::BinaryOperatorClass: {
599 if (!PDB.supportsLogicalOpControlFlow())
600 break;
601
602 BinaryOperator *B = cast<BinaryOperator>(T);
603 std::string sbuf;
604 llvm::raw_string_ostream os(sbuf);
605 os << "Left side of '";
606
607 if (B->getOpcode() == BinaryOperator::LAnd) {
608 os << "&&" << "' is ";
609
610 if (*(Src->succ_begin()+1) == Dst) {
611 os << "false";
612 PathDiagnosticLocation End(B->getLHS(), SMgr);
613 PathDiagnosticLocation Start(B->getOperatorLoc(), SMgr);
614 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
615 os.str()));
616 }
617 else {
618 os << "true";
619 PathDiagnosticLocation Start(B->getLHS(), SMgr);
620 PathDiagnosticLocation End = PDB.ExecutionContinues(N);
621 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
622 os.str()));
623 }
624 }
625 else {
626 assert(B->getOpcode() == BinaryOperator::LOr);
627 os << "||" << "' is ";
628
629 if (*(Src->succ_begin()+1) == Dst) {
630 os << "false";
631 PathDiagnosticLocation Start(B->getLHS(), SMgr);
632 PathDiagnosticLocation End = PDB.ExecutionContinues(N);
633 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
634 os.str()));
635 }
636 else {
637 os << "true";
638 PathDiagnosticLocation End(B->getLHS(), SMgr);
639 PathDiagnosticLocation Start(B->getOperatorLoc(), SMgr);
640 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
641 os.str()));
642 }
643 }
644
645 break;
646 }
647
648 case Stmt::DoStmtClass: {
649 if (*(Src->succ_begin()) == Dst) {
650 std::string sbuf;
651 llvm::raw_string_ostream os(sbuf);
652
653 os << "Loop condition is true. ";
654 PathDiagnosticLocation End = PDB.ExecutionContinues(os, N);
655
656 if (const Stmt *S = End.asStmt())
657 End = PDB.getEnclosingStmtLocation(S);
658
659 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
660 os.str()));
661 }
662 else {
663 PathDiagnosticLocation End = PDB.ExecutionContinues(N);
664
665 if (const Stmt *S = End.asStmt())
666 End = PDB.getEnclosingStmtLocation(S);
667
668 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
669 "Loop condition is false. Exiting loop"));
670 }
671
672 break;
673 }
674
675 case Stmt::WhileStmtClass:
676 case Stmt::ForStmtClass: {
677 if (*(Src->succ_begin()+1) == Dst) {
678 std::string sbuf;
679 llvm::raw_string_ostream os(sbuf);
680
681 os << "Loop condition is false. ";
682 PathDiagnosticLocation End = PDB.ExecutionContinues(os, N);
683 if (const Stmt *S = End.asStmt())
684 End = PDB.getEnclosingStmtLocation(S);
685
686 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
687 os.str()));
688 }
689 else {
690 PathDiagnosticLocation End = PDB.ExecutionContinues(N);
691 if (const Stmt *S = End.asStmt())
692 End = PDB.getEnclosingStmtLocation(S);
693
694 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000695 "Loop condition is true. Entering loop body"));
Ted Kremenek31061982009-03-31 23:00:32 +0000696 }
697
698 break;
699 }
700
701 case Stmt::IfStmtClass: {
702 PathDiagnosticLocation End = PDB.ExecutionContinues(N);
703
704 if (const Stmt *S = End.asStmt())
705 End = PDB.getEnclosingStmtLocation(S);
706
707 if (*(Src->succ_begin()+1) == Dst)
708 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000709 "Taking false branch"));
Ted Kremenek31061982009-03-31 23:00:32 +0000710 else
711 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000712 "Taking true branch"));
Ted Kremenek31061982009-03-31 23:00:32 +0000713
714 break;
715 }
716 }
717 }
718
719 if (PathDiagnosticPiece* p =
720 PDB.getReport().VisitNode(N, NextNode, PDB.getGraph(),
721 PDB.getBugReporter(),
722 PDB.getNodeMapClosure())) {
723 PD.push_front(p);
724 }
725
726 if (const PostStmt* PS = dyn_cast<PostStmt>(&P)) {
727 // Scan the region bindings, and see if a "notable" symbol has a new
728 // lval binding.
729 ScanNotableSymbols SNS(N, PS->getStmt(), PDB.getBugReporter(), PD);
730 PDB.getStateManager().iterBindings(N->getState(), SNS);
731 }
732 }
Ted Kremenek14856d72009-04-06 23:06:54 +0000733
734 // After constructing the full PathDiagnostic, do a pass over it to compact
735 // PathDiagnosticPieces that occur within a macro.
736 CompactPathDiagnostic(PD, PDB.getSourceManager());
Ted Kremenek31061982009-03-31 23:00:32 +0000737}
738
739//===----------------------------------------------------------------------===//
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000740// "Extensive" PathDiagnostic generation.
741//===----------------------------------------------------------------------===//
742
743static bool IsControlFlowExpr(const Stmt *S) {
744 const Expr *E = dyn_cast<Expr>(S);
Ted Kremenek14856d72009-04-06 23:06:54 +0000745
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000746 if (!E)
747 return false;
748
749 E = E->IgnoreParenCasts();
750
751 if (isa<ConditionalOperator>(E))
752 return true;
753
754 if (const BinaryOperator *B = dyn_cast<BinaryOperator>(E))
755 if (B->isLogicalOp())
756 return true;
757
758 return false;
759}
760
Ted Kremenek14856d72009-04-06 23:06:54 +0000761#if 1
762
763namespace {
764class VISIBILITY_HIDDEN EdgeBuilder {
765 std::vector<PathDiagnosticLocation> CLocs;
766 typedef std::vector<PathDiagnosticLocation>::iterator iterator;
767 PathDiagnostic &PD;
768 PathDiagnosticBuilder &PDB;
769 PathDiagnosticLocation PrevLoc;
770
771 bool containsLocation(const PathDiagnosticLocation &Container,
772 const PathDiagnosticLocation &Containee);
773
774 PathDiagnosticLocation getContextLocation(const PathDiagnosticLocation &L);
775 void rawAddEdge(PathDiagnosticLocation NewLoc);
776
777 void popLocation() {
Ted Kremenek404dd7a2009-04-22 18:37:42 +0000778 PathDiagnosticLocation L = CLocs.back();
Ted Kremenek5c7168c2009-04-22 20:36:26 +0000779 if (L.asLocation().isFileID()) {
Ted Kremenekc2924d02009-04-23 16:19:29 +0000780
Ted Kremenek6f132352009-04-23 16:44:22 +0000781 if (const Stmt *S = L.asStmt()) {
782 while (1) {
783 // Adjust the location for some expressions that are best referenced
784 // by one of their subexpressions.
785 if (const ParenExpr *PE = dyn_cast<ParenExpr>(S))
786 S = PE->IgnoreParens();
787 else if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(S))
788 S = CO->getCond();
789 else if (const ChooseExpr *CE = dyn_cast<ChooseExpr>(S))
790 S = CE->getCond();
791 else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(S))
792 S = BE->getLHS();
793 else
794 break;
795 }
796
Ted Kremenekc2924d02009-04-23 16:19:29 +0000797 L = PathDiagnosticLocation(S, L.getManager());
798 }
799
Ted Kremenek5c7168c2009-04-22 20:36:26 +0000800 // For contexts, we only one the first character as the range.
801 L = PathDiagnosticLocation(L.asLocation(), L.getManager());
Ted Kremenek4f5be3b2009-04-22 20:51:59 +0000802 rawAddEdge(L);
Ted Kremenek5c7168c2009-04-22 20:36:26 +0000803 }
Ted Kremenek14856d72009-04-06 23:06:54 +0000804 CLocs.pop_back();
805 }
806
807 PathDiagnosticLocation IgnoreParens(const PathDiagnosticLocation &L);
808
809public:
810 EdgeBuilder(PathDiagnostic &pd, PathDiagnosticBuilder &pdb)
811 : PD(pd), PDB(pdb) {
Ted Kremeneka301a672009-04-22 18:16:20 +0000812
813 // If the PathDiagnostic already has pieces, add the enclosing statement
814 // of the first piece as a context as well.
Ted Kremenek14856d72009-04-06 23:06:54 +0000815 if (!PD.empty()) {
816 PrevLoc = PD.begin()->getLocation();
817
818 if (const Stmt *S = PrevLoc.asStmt())
819 addContext(PDB.getEnclosingStmtLocation(S).asStmt());
820 }
821 }
822
823 ~EdgeBuilder() {
824 while (!CLocs.empty()) popLocation();
Ted Kremeneka301a672009-04-22 18:16:20 +0000825
826 // Finally, add an initial edge from the start location of the first
827 // statement (if it doesn't already exist).
Sebastian Redld3a413d2009-04-26 20:35:05 +0000828 // FIXME: Should handle CXXTryStmt if analyser starts supporting C++.
829 if (const CompoundStmt *CS =
830 PDB.getCodeDecl().getCompoundBody(PDB.getContext()))
Ted Kremeneka301a672009-04-22 18:16:20 +0000831 if (!CS->body_empty()) {
832 SourceLocation Loc = (*CS->body_begin())->getLocStart();
833 rawAddEdge(PathDiagnosticLocation(Loc, PDB.getSourceManager()));
834 }
835
Ted Kremenek14856d72009-04-06 23:06:54 +0000836 }
837
838 void addEdge(PathDiagnosticLocation NewLoc, bool alwaysAdd = false);
839
840 void addEdge(const Stmt *S, bool alwaysAdd = false) {
841 addEdge(PathDiagnosticLocation(S, PDB.getSourceManager()), alwaysAdd);
842 }
843
844 void addContext(const Stmt *S);
845};
846} // end anonymous namespace
847
848
849PathDiagnosticLocation
850EdgeBuilder::getContextLocation(const PathDiagnosticLocation &L) {
851 if (const Stmt *S = L.asStmt()) {
852 if (IsControlFlowExpr(S))
853 return L;
854
855 return PDB.getEnclosingStmtLocation(S);
856 }
857
858 return L;
859}
860
861bool EdgeBuilder::containsLocation(const PathDiagnosticLocation &Container,
862 const PathDiagnosticLocation &Containee) {
863
864 if (Container == Containee)
865 return true;
866
867 if (Container.asDecl())
868 return true;
869
870 if (const Stmt *S = Containee.asStmt())
871 if (const Stmt *ContainerS = Container.asStmt()) {
872 while (S) {
873 if (S == ContainerS)
874 return true;
875 S = PDB.getParent(S);
876 }
877 return false;
878 }
879
880 // Less accurate: compare using source ranges.
881 SourceRange ContainerR = Container.asRange();
882 SourceRange ContaineeR = Containee.asRange();
883
884 SourceManager &SM = PDB.getSourceManager();
885 SourceLocation ContainerRBeg = SM.getInstantiationLoc(ContainerR.getBegin());
886 SourceLocation ContainerREnd = SM.getInstantiationLoc(ContainerR.getEnd());
887 SourceLocation ContaineeRBeg = SM.getInstantiationLoc(ContaineeR.getBegin());
888 SourceLocation ContaineeREnd = SM.getInstantiationLoc(ContaineeR.getEnd());
889
890 unsigned ContainerBegLine = SM.getInstantiationLineNumber(ContainerRBeg);
891 unsigned ContainerEndLine = SM.getInstantiationLineNumber(ContainerREnd);
892 unsigned ContaineeBegLine = SM.getInstantiationLineNumber(ContaineeRBeg);
893 unsigned ContaineeEndLine = SM.getInstantiationLineNumber(ContaineeREnd);
894
895 assert(ContainerBegLine <= ContainerEndLine);
896 assert(ContaineeBegLine <= ContaineeEndLine);
897
898 return (ContainerBegLine <= ContaineeBegLine &&
899 ContainerEndLine >= ContaineeEndLine &&
900 (ContainerBegLine != ContaineeBegLine ||
901 SM.getInstantiationColumnNumber(ContainerRBeg) <=
902 SM.getInstantiationColumnNumber(ContaineeRBeg)) &&
903 (ContainerEndLine != ContaineeEndLine ||
904 SM.getInstantiationColumnNumber(ContainerREnd) >=
905 SM.getInstantiationColumnNumber(ContainerREnd)));
906}
907
908PathDiagnosticLocation
909EdgeBuilder::IgnoreParens(const PathDiagnosticLocation &L) {
910 if (const Expr* E = dyn_cast_or_null<Expr>(L.asStmt()))
911 return PathDiagnosticLocation(E->IgnoreParenCasts(),
912 PDB.getSourceManager());
913 return L;
914}
915
916void EdgeBuilder::rawAddEdge(PathDiagnosticLocation NewLoc) {
917 if (!PrevLoc.isValid()) {
918 PrevLoc = NewLoc;
919 return;
920 }
921
922 if (NewLoc.asLocation() == PrevLoc.asLocation())
923 return;
924
925 // FIXME: Ignore intra-macro edges for now.
926 if (NewLoc.asLocation().getInstantiationLoc() ==
927 PrevLoc.asLocation().getInstantiationLoc())
928 return;
929
930 PD.push_front(new PathDiagnosticControlFlowPiece(NewLoc, PrevLoc));
931 PrevLoc = NewLoc;
932}
933
934void EdgeBuilder::addEdge(PathDiagnosticLocation NewLoc, bool alwaysAdd) {
Ted Kremeneka301a672009-04-22 18:16:20 +0000935
936 if (!alwaysAdd && NewLoc.asLocation().isMacroID())
937 return;
938
Ted Kremenek14856d72009-04-06 23:06:54 +0000939 const PathDiagnosticLocation &CLoc = getContextLocation(NewLoc);
940
941 while (!CLocs.empty()) {
942 const PathDiagnosticLocation &TopContextLoc = CLocs.back();
943
944 // Is the top location context the same as the one for the new location?
945 if (TopContextLoc == CLoc) {
Ted Kremeneke97386f2009-04-07 00:11:40 +0000946 if (alwaysAdd)
Ted Kremenek14856d72009-04-06 23:06:54 +0000947 rawAddEdge(NewLoc);
948
949 return;
950 }
951
952 if (containsLocation(TopContextLoc, CLoc)) {
953 if (alwaysAdd)
954 rawAddEdge(NewLoc);
955
956 CLocs.push_back(CLoc);
957 return;
958 }
959
960 // Context does not contain the location. Flush it.
961 popLocation();
962 }
Ted Kremenek5c7168c2009-04-22 20:36:26 +0000963
964 // If we reach here, there is no enclosing context. Just add the edge.
965 rawAddEdge(NewLoc);
Ted Kremenek14856d72009-04-06 23:06:54 +0000966}
967
968void EdgeBuilder::addContext(const Stmt *S) {
969 if (!S)
970 return;
971
972 PathDiagnosticLocation L(S, PDB.getSourceManager());
973
974 while (!CLocs.empty()) {
975 const PathDiagnosticLocation &TopContextLoc = CLocs.back();
976
977 // Is the top location context the same as the one for the new location?
978 if (TopContextLoc == L)
979 return;
980
981 if (containsLocation(TopContextLoc, L)) {
Ted Kremenek14856d72009-04-06 23:06:54 +0000982 CLocs.push_back(L);
983 return;
984 }
985
986 // Context does not contain the location. Flush it.
987 popLocation();
988 }
989
990 CLocs.push_back(L);
991}
992
993static void GenerateExtensivePathDiagnostic(PathDiagnostic& PD,
994 PathDiagnosticBuilder &PDB,
995 const ExplodedNode<GRState> *N) {
996
997
998 EdgeBuilder EB(PD, PDB);
999
1000 const ExplodedNode<GRState>* NextNode = N->pred_empty()
1001 ? NULL : *(N->pred_begin());
Ted Kremenek14856d72009-04-06 23:06:54 +00001002 while (NextNode) {
1003 N = NextNode;
1004 NextNode = GetPredecessorNode(N);
1005 ProgramPoint P = N->getLocation();
1006
1007 // Block edges.
1008 if (const BlockEdge *BE = dyn_cast<BlockEdge>(&P)) {
1009 const CFGBlock &Blk = *BE->getSrc();
1010
1011 if (const Stmt *Term = Blk.getTerminator())
1012 EB.addContext(Term);
1013
Ted Kremenek14856d72009-04-06 23:06:54 +00001014 continue;
1015 }
1016
1017 if (const BlockEntrance *BE = dyn_cast<BlockEntrance>(&P)) {
1018 if (const Stmt* S = BE->getFirstStmt()) {
1019 if (IsControlFlowExpr(S))
1020 EB.addContext(S);
1021 else
Ted Kremenek581329c2009-04-07 04:53:35 +00001022 EB.addContext(PDB.getEnclosingStmtLocation(S).asStmt());
Ted Kremenek14856d72009-04-06 23:06:54 +00001023 }
1024
1025 continue;
1026 }
1027
1028 PathDiagnosticPiece* p =
Ted Kremenek581329c2009-04-07 04:53:35 +00001029 PDB.getReport().VisitNode(N, NextNode, PDB.getGraph(),
1030 PDB.getBugReporter(), PDB.getNodeMapClosure());
Ted Kremenek14856d72009-04-06 23:06:54 +00001031
1032 if (p) {
1033 EB.addEdge(p->getLocation(), true);
1034 PD.push_front(p);
1035 }
1036 }
1037}
1038
1039
1040#else
1041
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +00001042static void GenExtAddEdge(PathDiagnostic& PD,
1043 PathDiagnosticBuilder &PDB,
1044 PathDiagnosticLocation NewLoc,
1045 PathDiagnosticLocation &PrevLoc,
Ted Kremenekc3f83ad2009-04-01 17:18:21 +00001046 bool allowBlockJump = false) {
Ted Kremenek14856d72009-04-06 23:06:54 +00001047
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +00001048 if (const Stmt *S = NewLoc.asStmt()) {
1049 if (IsControlFlowExpr(S))
1050 return;
1051 }
1052
1053
1054 if (!PrevLoc.isValid()) {
1055 PrevLoc = NewLoc;
1056 return;
1057 }
1058
1059 if (NewLoc == PrevLoc)
1060 return;
Ted Kremenek14856d72009-04-06 23:06:54 +00001061
Ted Kremenek0dc65be2009-04-01 19:43:28 +00001062 // Are we jumping between statements within the same compound statement?
Ted Kremenekc3f83ad2009-04-01 17:18:21 +00001063 if (!allowBlockJump)
1064 if (const Stmt *PS = PrevLoc.asStmt())
1065 if (const Stmt *NS = NewLoc.asStmt()) {
1066 const Stmt *parentPS = PDB.getParent(PS);
Ted Kremenek28de78b2009-04-02 03:30:55 +00001067 if (parentPS && isa<CompoundStmt>(parentPS) &&
1068 parentPS == PDB.getParent(NS))
Ted Kremenekc3f83ad2009-04-01 17:18:21 +00001069 return;
1070 }
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +00001071
Ted Kremenek9e2d98d2009-04-01 21:12:06 +00001072 // Add an extra edge when jumping between contexts.
1073 while (1) {
1074 if (const Stmt *PS = PrevLoc.asStmt())
1075 if (const Stmt *NS = NewLoc.asStmt()) {
1076 PathDiagnosticLocation X = PDB.getEnclosingStmtLocation(PS);
1077 // FIXME: We need a version of getParent that ignores '()' and casts.
1078 const Stmt *parentX = PDB.getParent(X.asStmt());
Ted Kremenek14856d72009-04-06 23:06:54 +00001079
Ted Kremenek9e2d98d2009-04-01 21:12:06 +00001080 const PathDiagnosticLocation &Y = PDB.getEnclosingStmtLocation(NS);
1081 // FIXME: We need a version of getParent that ignores '()' and casts.
1082 const Stmt *parentY = PDB.getParent(Y.asStmt());
Ted Kremenek14856d72009-04-06 23:06:54 +00001083
Ted Kremenek0ddaff32009-04-02 03:44:00 +00001084 if (parentX && IsControlFlowExpr(parentX)) {
1085 if (parentX == parentY)
Ted Kremenek9e2d98d2009-04-01 21:12:06 +00001086 break;
Ted Kremenek9e2d98d2009-04-01 21:12:06 +00001087 else {
Ted Kremenek0ddaff32009-04-02 03:44:00 +00001088 if (const Stmt *grandparentX = PDB.getParent(parentX)) {
1089 const PathDiagnosticLocation &W =
Ted Kremenek14856d72009-04-06 23:06:54 +00001090 PDB.getEnclosingStmtLocation(grandparentX);
Ted Kremenek0ddaff32009-04-02 03:44:00 +00001091
1092 if (W != Y) X = W;
1093 }
Ted Kremenek9e2d98d2009-04-01 21:12:06 +00001094 }
1095 }
1096
1097 if (X != Y && PrevLoc.asLocation() != X.asLocation()) {
1098 PD.push_front(new PathDiagnosticControlFlowPiece(X, PrevLoc));
1099 PrevLoc = X;
1100 }
1101 }
1102 break;
1103 }
1104
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +00001105 PD.push_front(new PathDiagnosticControlFlowPiece(NewLoc, PrevLoc));
Ted Kremenekc3f83ad2009-04-01 17:18:21 +00001106 PrevLoc = NewLoc;
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +00001107}
1108
1109static bool IsNestedDeclStmt(const Stmt *S, ParentMap &PM) {
1110 const DeclStmt *DS = dyn_cast<DeclStmt>(S);
Ted Kremenek14856d72009-04-06 23:06:54 +00001111
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +00001112 if (!DS)
1113 return false;
1114
1115 const Stmt *Parent = PM.getParent(DS);
1116 if (!Parent)
1117 return false;
1118
1119 if (const ForStmt *FS = dyn_cast<ForStmt>(Parent))
1120 return FS->getInit() == DS;
Ted Kremenek14856d72009-04-06 23:06:54 +00001121
Ted Kremeneka42c4c92009-04-01 18:48:52 +00001122 // FIXME: In the future IfStmt/WhileStmt may contain DeclStmts in their
1123 // condition.
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +00001124
1125 return false;
1126}
1127
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +00001128static void GenerateExtensivePathDiagnostic(PathDiagnostic& PD,
1129 PathDiagnosticBuilder &PDB,
1130 const ExplodedNode<GRState> *N) {
Ted Kremenek14856d72009-04-06 23:06:54 +00001131
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +00001132 SourceManager& SMgr = PDB.getSourceManager();
1133 const ExplodedNode<GRState>* NextNode = N->pred_empty()
Ted Kremenek14856d72009-04-06 23:06:54 +00001134 ? NULL : *(N->pred_begin());
1135
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +00001136 PathDiagnosticLocation PrevLoc;
1137
1138 while (NextNode) {
1139 N = NextNode;
1140 NextNode = GetPredecessorNode(N);
1141 ProgramPoint P = N->getLocation();
1142
1143 // Block edges.
1144 if (const BlockEdge *BE = dyn_cast<BlockEdge>(&P)) {
1145 const CFGBlock &Blk = *BE->getSrc();
Ted Kremenek14856d72009-04-06 23:06:54 +00001146
Ted Kremenek51a735c2009-04-01 17:52:26 +00001147 // Add a special edge for the entrance into the function/method.
1148 if (&Blk == &PDB.getCFG().getEntry()) {
1149 FullSourceLoc L = FullSourceLoc(PDB.getCodeDecl().getLocation(), SMgr);
1150 GenExtAddEdge(PD, PDB, L.getSpellingLoc(), PrevLoc);
1151 continue;
1152 }
1153
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +00001154 if (const Stmt *Term = Blk.getTerminator()) {
Ted Kremeneka42c4c92009-04-01 18:48:52 +00001155 const Stmt *Cond = Blk.getTerminatorCondition();
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +00001156 if (!Cond || !IsControlFlowExpr(Cond)) {
Ted Kremeneka42c4c92009-04-01 18:48:52 +00001157 // For terminators that are control-flow expressions like '&&', '?',
1158 // have the condition be the anchor point for the control-flow edge
1159 // instead of the terminator.
1160 const Stmt *X = isa<Expr>(Term) ? (Cond ? Cond : Term) : Term;
1161 GenExtAddEdge(PD, PDB, PathDiagnosticLocation(X, SMgr), PrevLoc,true);
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +00001162 continue;
1163 }
1164 }
1165
1166 // Only handle blocks with more than 1 statement here, as the blocks
1167 // with one statement are handled at BlockEntrances.
1168 if (Blk.size() > 1) {
1169 const Stmt *S = *Blk.rbegin();
1170
1171 // We don't add control-flow edges for DeclStmt's that appear in
1172 // the condition of if/while/for or are control-flow merge expressions.
1173 if (!IsControlFlowExpr(S) && !IsNestedDeclStmt(S, PDB.getParentMap())) {
1174 GenExtAddEdge(PD, PDB, PathDiagnosticLocation(S, SMgr), PrevLoc);
1175 }
1176 }
Ted Kremenek14856d72009-04-06 23:06:54 +00001177
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +00001178 continue;
1179 }
1180
1181 if (const BlockEntrance *BE = dyn_cast<BlockEntrance>(&P)) {
1182 if (const Stmt* S = BE->getFirstStmt()) {
1183 if (!IsControlFlowExpr(S) && !IsNestedDeclStmt(S, PDB.getParentMap())) {
Ted Kremenekc3f83ad2009-04-01 17:18:21 +00001184 if (PrevLoc.isValid()) {
Ted Kremenek51a735c2009-04-01 17:52:26 +00001185 // Are we jumping within the same enclosing statement?
Ted Kremenekc3f83ad2009-04-01 17:18:21 +00001186 if (PDB.getEnclosingStmtLocation(S) ==
1187 PDB.getEnclosingStmtLocation(PrevLoc))
Ted Kremenek14856d72009-04-06 23:06:54 +00001188 continue;
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +00001189 }
1190
1191 GenExtAddEdge(PD, PDB, PDB.getEnclosingStmtLocation(S), PrevLoc);
1192 }
1193 }
1194
1195 continue;
1196 }
Ted Kremenek14856d72009-04-06 23:06:54 +00001197
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +00001198 PathDiagnosticPiece* p =
Ted Kremenek14856d72009-04-06 23:06:54 +00001199 PDB.getReport().VisitNode(N, NextNode, PDB.getGraph(),
1200 PDB.getBugReporter(), PDB.getNodeMapClosure());
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +00001201
1202 if (p) {
Ted Kremeneka42c4c92009-04-01 18:48:52 +00001203 GenExtAddEdge(PD, PDB, p->getLocation(), PrevLoc, true);
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +00001204 PD.push_front(p);
1205 }
1206 }
1207}
Ted Kremenek14856d72009-04-06 23:06:54 +00001208#endif
1209
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +00001210//===----------------------------------------------------------------------===//
Ted Kremenekcf118d42009-02-04 23:49:09 +00001211// Methods for BugType and subclasses.
1212//===----------------------------------------------------------------------===//
1213BugType::~BugType() {}
1214void BugType::FlushReports(BugReporter &BR) {}
Ted Kremenekbb77e9b2008-05-01 22:50:36 +00001215
Ted Kremenekcf118d42009-02-04 23:49:09 +00001216//===----------------------------------------------------------------------===//
1217// Methods for BugReport and subclasses.
1218//===----------------------------------------------------------------------===//
1219BugReport::~BugReport() {}
1220RangedBugReport::~RangedBugReport() {}
1221
1222Stmt* BugReport::getStmt(BugReporter& BR) const {
Ted Kremenek200ed922008-05-02 23:21:21 +00001223 ProgramPoint ProgP = EndNode->getLocation();
Ted Kremenekbd7efa82008-04-17 23:44:37 +00001224 Stmt *S = NULL;
1225
Ted Kremenekcf118d42009-02-04 23:49:09 +00001226 if (BlockEntrance* BE = dyn_cast<BlockEntrance>(&ProgP)) {
Ted Kremenekb697b102009-02-23 22:44:26 +00001227 if (BE->getBlock() == &BR.getCFG()->getExit()) S = GetPreviousStmt(EndNode);
Ted Kremenekcf118d42009-02-04 23:49:09 +00001228 }
1229 if (!S) S = GetStmt(ProgP);
1230
Ted Kremenekbb77e9b2008-05-01 22:50:36 +00001231 return S;
1232}
1233
1234PathDiagnosticPiece*
1235BugReport::getEndPath(BugReporter& BR,
Ted Kremenek3148eb42009-01-24 00:55:43 +00001236 const ExplodedNode<GRState>* EndPathNode) {
Ted Kremenekbb77e9b2008-05-01 22:50:36 +00001237
1238 Stmt* S = getStmt(BR);
Ted Kremenek61f3e052008-04-03 04:42:52 +00001239
1240 if (!S)
1241 return NULL;
1242
Ted Kremenekc9fa2f72008-05-01 23:13:35 +00001243 FullSourceLoc L(S->getLocStart(), BR.getContext().getSourceManager());
Ted Kremenek1fbfd5b2009-03-06 23:58:11 +00001244 PathDiagnosticPiece* P = new PathDiagnosticEventPiece(L, getDescription());
Ted Kremenek61f3e052008-04-03 04:42:52 +00001245
Ted Kremenekde7161f2008-04-03 18:00:37 +00001246 const SourceRange *Beg, *End;
Ted Kremenekbb77e9b2008-05-01 22:50:36 +00001247 getRanges(BR, Beg, End);
Ted Kremenekcf118d42009-02-04 23:49:09 +00001248
Ted Kremenekbb77e9b2008-05-01 22:50:36 +00001249 for (; Beg != End; ++Beg)
1250 P->addRange(*Beg);
Ted Kremenek61f3e052008-04-03 04:42:52 +00001251
1252 return P;
1253}
1254
Ted Kremenekbb77e9b2008-05-01 22:50:36 +00001255void BugReport::getRanges(BugReporter& BR, const SourceRange*& beg,
1256 const SourceRange*& end) {
1257
1258 if (Expr* E = dyn_cast_or_null<Expr>(getStmt(BR))) {
1259 R = E->getSourceRange();
Ted Kremenek9b5e5052009-02-27 20:05:10 +00001260 assert(R.isValid());
Ted Kremenekbb77e9b2008-05-01 22:50:36 +00001261 beg = &R;
1262 end = beg+1;
1263 }
1264 else
1265 beg = end = 0;
Ted Kremenekf1ae7052008-04-03 17:57:38 +00001266}
1267
Ted Kremenekcf118d42009-02-04 23:49:09 +00001268SourceLocation BugReport::getLocation() const {
1269 if (EndNode)
Ted Kremenek9b5e5052009-02-27 20:05:10 +00001270 if (Stmt* S = GetCurrentOrPreviousStmt(EndNode)) {
1271 // For member expressions, return the location of the '.' or '->'.
1272 if (MemberExpr* ME = dyn_cast<MemberExpr>(S))
1273 return ME->getMemberLoc();
1274
Ted Kremenekcf118d42009-02-04 23:49:09 +00001275 return S->getLocStart();
Ted Kremenek9b5e5052009-02-27 20:05:10 +00001276 }
Ted Kremenekcf118d42009-02-04 23:49:09 +00001277
1278 return FullSourceLoc();
Ted Kremenekd2f642b2008-04-14 17:39:48 +00001279}
1280
Ted Kremenek3148eb42009-01-24 00:55:43 +00001281PathDiagnosticPiece* BugReport::VisitNode(const ExplodedNode<GRState>* N,
1282 const ExplodedNode<GRState>* PrevN,
1283 const ExplodedGraph<GRState>& G,
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001284 BugReporter& BR,
1285 NodeResolver &NR) {
Ted Kremenek50a6d0c2008-04-09 21:41:14 +00001286 return NULL;
1287}
1288
Ted Kremenekcf118d42009-02-04 23:49:09 +00001289//===----------------------------------------------------------------------===//
1290// Methods for BugReporter and subclasses.
1291//===----------------------------------------------------------------------===//
1292
1293BugReportEquivClass::~BugReportEquivClass() {
1294 for (iterator I=begin(), E=end(); I!=E; ++I) delete *I;
1295}
1296
1297GRBugReporter::~GRBugReporter() { FlushReports(); }
1298BugReporterData::~BugReporterData() {}
1299
1300ExplodedGraph<GRState>&
1301GRBugReporter::getGraph() { return Eng.getGraph(); }
1302
1303GRStateManager&
1304GRBugReporter::getStateManager() { return Eng.getStateManager(); }
1305
1306BugReporter::~BugReporter() { FlushReports(); }
1307
1308void BugReporter::FlushReports() {
1309 if (BugTypes.isEmpty())
1310 return;
1311
1312 // First flush the warnings for each BugType. This may end up creating new
1313 // warnings and new BugTypes. Because ImmutableSet is a functional data
1314 // structure, we do not need to worry about the iterators being invalidated.
1315 for (BugTypesTy::iterator I=BugTypes.begin(), E=BugTypes.end(); I!=E; ++I)
1316 const_cast<BugType*>(*I)->FlushReports(*this);
1317
1318 // Iterate through BugTypes a second time. BugTypes may have been updated
1319 // with new BugType objects and new warnings.
1320 for (BugTypesTy::iterator I=BugTypes.begin(), E=BugTypes.end(); I!=E; ++I) {
1321 BugType *BT = const_cast<BugType*>(*I);
1322
1323 typedef llvm::FoldingSet<BugReportEquivClass> SetTy;
1324 SetTy& EQClasses = BT->EQClasses;
1325
1326 for (SetTy::iterator EI=EQClasses.begin(), EE=EQClasses.end(); EI!=EE;++EI){
1327 BugReportEquivClass& EQ = *EI;
1328 FlushReport(EQ);
1329 }
Ted Kremeneka43a1eb2008-04-23 23:02:12 +00001330
Ted Kremenekcf118d42009-02-04 23:49:09 +00001331 // Delete the BugType object. This will also delete the equivalence
1332 // classes.
1333 delete BT;
Ted Kremenek94826a72008-04-03 04:59:14 +00001334 }
Ted Kremenekcf118d42009-02-04 23:49:09 +00001335
1336 // Remove all references to the BugType objects.
1337 BugTypes = F.GetEmptySet();
1338}
1339
1340//===----------------------------------------------------------------------===//
1341// PathDiagnostics generation.
1342//===----------------------------------------------------------------------===//
1343
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001344static std::pair<std::pair<ExplodedGraph<GRState>*, NodeBackMap*>,
Ted Kremenekcf118d42009-02-04 23:49:09 +00001345 std::pair<ExplodedNode<GRState>*, unsigned> >
1346MakeReportGraph(const ExplodedGraph<GRState>* G,
1347 const ExplodedNode<GRState>** NStart,
1348 const ExplodedNode<GRState>** NEnd) {
Ted Kremenek94826a72008-04-03 04:59:14 +00001349
Ted Kremenekcf118d42009-02-04 23:49:09 +00001350 // Create the trimmed graph. It will contain the shortest paths from the
1351 // error nodes to the root. In the new graph we should only have one
1352 // error node unless there are two or more error nodes with the same minimum
1353 // path length.
1354 ExplodedGraph<GRState>* GTrim;
1355 InterExplodedGraphMap<GRState>* NMap;
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001356
1357 llvm::DenseMap<const void*, const void*> InverseMap;
1358 llvm::tie(GTrim, NMap) = G->Trim(NStart, NEnd, &InverseMap);
Ted Kremenekcf118d42009-02-04 23:49:09 +00001359
1360 // Create owning pointers for GTrim and NMap just to ensure that they are
1361 // released when this function exists.
1362 llvm::OwningPtr<ExplodedGraph<GRState> > AutoReleaseGTrim(GTrim);
1363 llvm::OwningPtr<InterExplodedGraphMap<GRState> > AutoReleaseNMap(NMap);
1364
1365 // Find the (first) error node in the trimmed graph. We just need to consult
1366 // the node map (NMap) which maps from nodes in the original graph to nodes
1367 // in the new graph.
1368 const ExplodedNode<GRState>* N = 0;
1369 unsigned NodeIndex = 0;
1370
1371 for (const ExplodedNode<GRState>** I = NStart; I != NEnd; ++I)
1372 if ((N = NMap->getMappedNode(*I))) {
1373 NodeIndex = (I - NStart) / sizeof(*I);
1374 break;
1375 }
1376
1377 assert(N && "No error node found in the trimmed graph.");
1378
1379 // Create a new (third!) graph with a single path. This is the graph
1380 // that will be returned to the caller.
Ted Kremenek3148eb42009-01-24 00:55:43 +00001381 ExplodedGraph<GRState> *GNew =
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001382 new ExplodedGraph<GRState>(GTrim->getCFG(), GTrim->getCodeDecl(),
1383 GTrim->getContext());
Ted Kremenekcf118d42009-02-04 23:49:09 +00001384
Ted Kremenek10aa5542009-03-12 23:41:59 +00001385 // Sometimes the trimmed graph can contain a cycle. Perform a reverse BFS
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001386 // to the root node, and then construct a new graph that contains only
1387 // a single path.
Ted Kremenek3148eb42009-01-24 00:55:43 +00001388 llvm::DenseMap<const void*,unsigned> Visited;
Ted Kremenek10aa5542009-03-12 23:41:59 +00001389 std::queue<const ExplodedNode<GRState>*> WS;
1390 WS.push(N);
1391
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001392 unsigned cnt = 0;
Ted Kremenek3148eb42009-01-24 00:55:43 +00001393 const ExplodedNode<GRState>* Root = 0;
Ted Kremenekc1da4412008-06-17 19:14:06 +00001394
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001395 while (!WS.empty()) {
Ted Kremenek10aa5542009-03-12 23:41:59 +00001396 const ExplodedNode<GRState>* Node = WS.front();
1397 WS.pop();
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001398
1399 if (Visited.find(Node) != Visited.end())
1400 continue;
1401
1402 Visited[Node] = cnt++;
1403
1404 if (Node->pred_empty()) {
1405 Root = Node;
1406 break;
1407 }
1408
Ted Kremenek3148eb42009-01-24 00:55:43 +00001409 for (ExplodedNode<GRState>::const_pred_iterator I=Node->pred_begin(),
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001410 E=Node->pred_end(); I!=E; ++I)
Ted Kremenek10aa5542009-03-12 23:41:59 +00001411 WS.push(*I);
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001412 }
Ted Kremenekcf118d42009-02-04 23:49:09 +00001413
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001414 assert (Root);
1415
Ted Kremenek10aa5542009-03-12 23:41:59 +00001416 // Now walk from the root down the BFS path, always taking the successor
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001417 // with the lowest number.
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001418 ExplodedNode<GRState> *Last = 0, *First = 0;
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001419 NodeBackMap *BM = new NodeBackMap();
Ted Kremenekcf118d42009-02-04 23:49:09 +00001420
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001421 for ( N = Root ;;) {
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001422 // Lookup the number associated with the current node.
Ted Kremenek3148eb42009-01-24 00:55:43 +00001423 llvm::DenseMap<const void*,unsigned>::iterator I = Visited.find(N);
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001424 assert (I != Visited.end());
1425
1426 // Create the equivalent node in the new graph with the same state
1427 // and location.
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001428 ExplodedNode<GRState>* NewN =
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001429 GNew->getNode(N->getLocation(), N->getState());
1430
1431 // Store the mapping to the original node.
1432 llvm::DenseMap<const void*, const void*>::iterator IMitr=InverseMap.find(N);
1433 assert(IMitr != InverseMap.end() && "No mapping to original node.");
1434 (*BM)[NewN] = (const ExplodedNode<GRState>*) IMitr->second;
Ted Kremenekcf118d42009-02-04 23:49:09 +00001435
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001436 // Link up the new node with the previous node.
1437 if (Last)
1438 NewN->addPredecessor(Last);
Ted Kremeneka43a1eb2008-04-23 23:02:12 +00001439
1440 Last = NewN;
Ted Kremenekcf118d42009-02-04 23:49:09 +00001441
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001442 // Are we at the final node?
1443 if (I->second == 0) {
1444 First = NewN;
Ted Kremenekc1da4412008-06-17 19:14:06 +00001445 break;
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001446 }
Ted Kremenekcf118d42009-02-04 23:49:09 +00001447
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001448 // Find the next successor node. We choose the node that is marked
1449 // with the lowest DFS number.
Ted Kremenek3148eb42009-01-24 00:55:43 +00001450 ExplodedNode<GRState>::const_succ_iterator SI = N->succ_begin();
1451 ExplodedNode<GRState>::const_succ_iterator SE = N->succ_end();
Ted Kremenekc1da4412008-06-17 19:14:06 +00001452 N = 0;
1453
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001454 for (unsigned MinVal = 0; SI != SE; ++SI) {
Ted Kremenekcf118d42009-02-04 23:49:09 +00001455
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001456 I = Visited.find(*SI);
1457
1458 if (I == Visited.end())
1459 continue;
1460
1461 if (!N || I->second < MinVal) {
1462 N = *SI;
1463 MinVal = I->second;
Ted Kremenekc1da4412008-06-17 19:14:06 +00001464 }
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001465 }
Ted Kremenekcf118d42009-02-04 23:49:09 +00001466
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001467 assert (N);
Ted Kremeneka43a1eb2008-04-23 23:02:12 +00001468 }
Ted Kremenekcf118d42009-02-04 23:49:09 +00001469
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001470 assert (First);
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001471 return std::make_pair(std::make_pair(GNew, BM),
1472 std::make_pair(First, NodeIndex));
Ted Kremeneka43a1eb2008-04-23 23:02:12 +00001473}
1474
Ted Kremenek0e5c8d42009-03-10 05:16:17 +00001475/// CompactPathDiagnostic - This function postprocesses a PathDiagnostic object
1476/// and collapses PathDiagosticPieces that are expanded by macros.
1477static void CompactPathDiagnostic(PathDiagnostic &PD, const SourceManager& SM) {
1478 typedef std::vector<std::pair<PathDiagnosticMacroPiece*, SourceLocation> >
1479 MacroStackTy;
1480
1481 typedef std::vector<PathDiagnosticPiece*>
1482 PiecesTy;
1483
1484 MacroStackTy MacroStack;
1485 PiecesTy Pieces;
1486
1487 for (PathDiagnostic::iterator I = PD.begin(), E = PD.end(); I!=E; ++I) {
1488 // Get the location of the PathDiagnosticPiece.
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +00001489 const FullSourceLoc Loc = I->getLocation().asLocation();
Ted Kremenek0e5c8d42009-03-10 05:16:17 +00001490
1491 // Determine the instantiation location, which is the location we group
1492 // related PathDiagnosticPieces.
1493 SourceLocation InstantiationLoc = Loc.isMacroID() ?
1494 SM.getInstantiationLoc(Loc) :
1495 SourceLocation();
1496
1497 if (Loc.isFileID()) {
1498 MacroStack.clear();
1499 Pieces.push_back(&*I);
1500 continue;
1501 }
1502
1503 assert(Loc.isMacroID());
1504
1505 // Is the PathDiagnosticPiece within the same macro group?
1506 if (!MacroStack.empty() && InstantiationLoc == MacroStack.back().second) {
1507 MacroStack.back().first->push_back(&*I);
1508 continue;
1509 }
1510
1511 // We aren't in the same group. Are we descending into a new macro
1512 // or are part of an old one?
1513 PathDiagnosticMacroPiece *MacroGroup = 0;
1514
1515 SourceLocation ParentInstantiationLoc = InstantiationLoc.isMacroID() ?
1516 SM.getInstantiationLoc(Loc) :
1517 SourceLocation();
1518
1519 // Walk the entire macro stack.
1520 while (!MacroStack.empty()) {
1521 if (InstantiationLoc == MacroStack.back().second) {
1522 MacroGroup = MacroStack.back().first;
1523 break;
1524 }
1525
1526 if (ParentInstantiationLoc == MacroStack.back().second) {
1527 MacroGroup = MacroStack.back().first;
1528 break;
1529 }
1530
1531 MacroStack.pop_back();
1532 }
1533
1534 if (!MacroGroup || ParentInstantiationLoc == MacroStack.back().second) {
1535 // Create a new macro group and add it to the stack.
1536 PathDiagnosticMacroPiece *NewGroup = new PathDiagnosticMacroPiece(Loc);
1537
1538 if (MacroGroup)
1539 MacroGroup->push_back(NewGroup);
1540 else {
1541 assert(InstantiationLoc.isFileID());
1542 Pieces.push_back(NewGroup);
1543 }
1544
1545 MacroGroup = NewGroup;
1546 MacroStack.push_back(std::make_pair(MacroGroup, InstantiationLoc));
1547 }
1548
1549 // Finally, add the PathDiagnosticPiece to the group.
1550 MacroGroup->push_back(&*I);
1551 }
1552
1553 // Now take the pieces and construct a new PathDiagnostic.
1554 PD.resetPath(false);
1555
1556 for (PiecesTy::iterator I=Pieces.begin(), E=Pieces.end(); I!=E; ++I) {
1557 if (PathDiagnosticMacroPiece *MP=dyn_cast<PathDiagnosticMacroPiece>(*I))
1558 if (!MP->containsEvent()) {
1559 delete MP;
1560 continue;
1561 }
1562
1563 PD.push_back(*I);
1564 }
1565}
1566
Ted Kremenek7dc86642009-03-31 20:22:36 +00001567void GRBugReporter::GeneratePathDiagnostic(PathDiagnostic& PD,
1568 BugReportEquivClass& EQ) {
1569
1570 std::vector<const ExplodedNode<GRState>*> Nodes;
1571
Ted Kremenekcf118d42009-02-04 23:49:09 +00001572 for (BugReportEquivClass::iterator I=EQ.begin(), E=EQ.end(); I!=E; ++I) {
1573 const ExplodedNode<GRState>* N = I->getEndNode();
1574 if (N) Nodes.push_back(N);
1575 }
1576
1577 if (Nodes.empty())
1578 return;
Ted Kremeneka43a1eb2008-04-23 23:02:12 +00001579
1580 // Construct a new graph that contains only a single path from the error
Ted Kremenekcf118d42009-02-04 23:49:09 +00001581 // node to a root.
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001582 const std::pair<std::pair<ExplodedGraph<GRState>*, NodeBackMap*>,
Ted Kremenek7dc86642009-03-31 20:22:36 +00001583 std::pair<ExplodedNode<GRState>*, unsigned> >&
1584 GPair = MakeReportGraph(&getGraph(), &Nodes[0], &Nodes[0] + Nodes.size());
Ted Kremeneka43a1eb2008-04-23 23:02:12 +00001585
Ted Kremenekcf118d42009-02-04 23:49:09 +00001586 // Find the BugReport with the original location.
1587 BugReport *R = 0;
1588 unsigned i = 0;
1589 for (BugReportEquivClass::iterator I=EQ.begin(), E=EQ.end(); I!=E; ++I, ++i)
1590 if (i == GPair.second.second) { R = *I; break; }
1591
1592 assert(R && "No original report found for sliced graph.");
Ted Kremeneka43a1eb2008-04-23 23:02:12 +00001593
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001594 llvm::OwningPtr<ExplodedGraph<GRState> > ReportGraph(GPair.first.first);
1595 llvm::OwningPtr<NodeBackMap> BackMap(GPair.first.second);
Ted Kremenekcf118d42009-02-04 23:49:09 +00001596 const ExplodedNode<GRState> *N = GPair.second.first;
Ted Kremenek7dc86642009-03-31 20:22:36 +00001597
Ted Kremenekcf118d42009-02-04 23:49:09 +00001598 // Start building the path diagnostic...
1599 if (PathDiagnosticPiece* Piece = R->getEndPath(*this, N))
Ted Kremenekbd7efa82008-04-17 23:44:37 +00001600 PD.push_back(Piece);
1601 else
1602 return;
Ted Kremenek7dc86642009-03-31 20:22:36 +00001603
1604 PathDiagnosticBuilder PDB(*this, ReportGraph.get(), R, BackMap.get(),
1605 getStateManager().getCodeDecl(),
Ted Kremenekbabdd7b2009-03-27 05:06:10 +00001606 getPathDiagnosticClient());
Ted Kremenekbd7efa82008-04-17 23:44:37 +00001607
Ted Kremenek7dc86642009-03-31 20:22:36 +00001608 switch (PDB.getGenerationScheme()) {
1609 case PathDiagnosticClient::Extensive:
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +00001610 GenerateExtensivePathDiagnostic(PD,PDB, N);
1611 break;
Ted Kremenek7dc86642009-03-31 20:22:36 +00001612 case PathDiagnosticClient::Minimal:
1613 GenerateMinimalPathDiagnostic(PD, PDB, N);
1614 break;
1615 }
Ted Kremenek7dc86642009-03-31 20:22:36 +00001616}
1617
Ted Kremenekcf118d42009-02-04 23:49:09 +00001618void BugReporter::Register(BugType *BT) {
1619 BugTypes = F.Add(BugTypes, BT);
Ted Kremenek76d90c82008-05-16 18:33:14 +00001620}
1621
Ted Kremenekcf118d42009-02-04 23:49:09 +00001622void BugReporter::EmitReport(BugReport* R) {
1623 // Compute the bug report's hash to determine its equivalence class.
1624 llvm::FoldingSetNodeID ID;
1625 R->Profile(ID);
Ted Kremenek61f3e052008-04-03 04:42:52 +00001626
Ted Kremenekcf118d42009-02-04 23:49:09 +00001627 // Lookup the equivance class. If there isn't one, create it.
1628 BugType& BT = R->getBugType();
1629 Register(&BT);
1630 void *InsertPos;
1631 BugReportEquivClass* EQ = BT.EQClasses.FindNodeOrInsertPos(ID, InsertPos);
1632
1633 if (!EQ) {
1634 EQ = new BugReportEquivClass(R);
1635 BT.EQClasses.InsertNode(EQ, InsertPos);
1636 }
1637 else
1638 EQ->AddReport(R);
Ted Kremenek61f3e052008-04-03 04:42:52 +00001639}
1640
Ted Kremenekcf118d42009-02-04 23:49:09 +00001641void BugReporter::FlushReport(BugReportEquivClass& EQ) {
1642 assert(!EQ.Reports.empty());
1643 BugReport &R = **EQ.begin();
1644
1645 // FIXME: Make sure we use the 'R' for the path that was actually used.
1646 // Probably doesn't make a difference in practice.
1647 BugType& BT = R.getBugType();
1648
1649 llvm::OwningPtr<PathDiagnostic> D(new PathDiagnostic(R.getBugType().getName(),
1650 R.getDescription(),
1651 BT.getCategory()));
1652 GeneratePathDiagnostic(*D.get(), EQ);
Ted Kremenek072192b2008-04-30 23:47:44 +00001653
1654 // Get the meta data.
Ted Kremenek072192b2008-04-30 23:47:44 +00001655 std::pair<const char**, const char**> Meta = R.getExtraDescriptiveText();
Ted Kremenek3148eb42009-01-24 00:55:43 +00001656 for (const char** s = Meta.first; s != Meta.second; ++s) D->addMeta(*s);
Ted Kremenek75840e12008-04-18 01:56:37 +00001657
Ted Kremenek3148eb42009-01-24 00:55:43 +00001658 // Emit a summary diagnostic to the regular Diagnostics engine.
Ted Kremenekc0959972008-07-02 21:24:01 +00001659 PathDiagnosticClient* PD = getPathDiagnosticClient();
Ted Kremenek3148eb42009-01-24 00:55:43 +00001660 const SourceRange *Beg = 0, *End = 0;
1661 R.getRanges(*this, Beg, End);
1662 Diagnostic& Diag = getDiagnostic();
Ted Kremenekcf118d42009-02-04 23:49:09 +00001663 FullSourceLoc L(R.getLocation(), getSourceManager());
Ted Kremenekd90e7082009-02-07 22:36:41 +00001664 unsigned ErrorDiag = Diag.getCustomDiagID(Diagnostic::Warning,
1665 R.getDescription().c_str());
Ted Kremenek57202072008-07-14 17:40:50 +00001666
Ted Kremenek3148eb42009-01-24 00:55:43 +00001667 switch (End-Beg) {
Chris Lattner0a14eee2008-11-18 07:04:44 +00001668 default: assert(0 && "Don't handle this many ranges yet!");
1669 case 0: Diag.Report(L, ErrorDiag); break;
1670 case 1: Diag.Report(L, ErrorDiag) << Beg[0]; break;
1671 case 2: Diag.Report(L, ErrorDiag) << Beg[0] << Beg[1]; break;
1672 case 3: Diag.Report(L, ErrorDiag) << Beg[0] << Beg[1] << Beg[2]; break;
Ted Kremenek2f0e89e2008-04-18 22:56:53 +00001673 }
Ted Kremenek3148eb42009-01-24 00:55:43 +00001674
1675 // Emit a full diagnostic for the path if we have a PathDiagnosticClient.
1676 if (!PD)
1677 return;
1678
1679 if (D->empty()) {
Ted Kremenek1fbfd5b2009-03-06 23:58:11 +00001680 PathDiagnosticPiece* piece =
1681 new PathDiagnosticEventPiece(L, R.getDescription());
1682
Ted Kremenek3148eb42009-01-24 00:55:43 +00001683 for ( ; Beg != End; ++Beg) piece->addRange(*Beg);
1684 D->push_back(piece);
1685 }
1686
1687 PD->HandlePathDiagnostic(D.take());
Ted Kremenek61f3e052008-04-03 04:42:52 +00001688}
Ted Kremenek57202072008-07-14 17:40:50 +00001689
Ted Kremenek8c036c72008-09-20 04:23:38 +00001690void BugReporter::EmitBasicReport(const char* name, const char* str,
1691 SourceLocation Loc,
1692 SourceRange* RBeg, unsigned NumRanges) {
1693 EmitBasicReport(name, "", str, Loc, RBeg, NumRanges);
1694}
Ted Kremenekcf118d42009-02-04 23:49:09 +00001695
Ted Kremenek8c036c72008-09-20 04:23:38 +00001696void BugReporter::EmitBasicReport(const char* name, const char* category,
1697 const char* str, SourceLocation Loc,
1698 SourceRange* RBeg, unsigned NumRanges) {
1699
Ted Kremenekcf118d42009-02-04 23:49:09 +00001700 // 'BT' will be owned by BugReporter as soon as we call 'EmitReport'.
1701 BugType *BT = new BugType(name, category);
Chris Lattner0a14eee2008-11-18 07:04:44 +00001702 FullSourceLoc L = getContext().getFullLoc(Loc);
Ted Kremenekcf118d42009-02-04 23:49:09 +00001703 RangedBugReport *R = new DiagBugReport(*BT, str, L);
1704 for ( ; NumRanges > 0 ; --NumRanges, ++RBeg) R->addRange(*RBeg);
1705 EmitReport(R);
Ted Kremenek57202072008-07-14 17:40:50 +00001706}