blob: 23de85709ad8d59dafc4327d08250212fd5a71fd [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 Kremenek8966bc12009-05-06 21:39:49 +000033BugReporterVisitor::~BugReporterVisitor() {}
34BugReporterContext::~BugReporterContext() {
35 for (visitor_iterator I = visitor_begin(), E = visitor_end(); I != E; ++I)
36 if ((*I)->isOwnedByReporterContext()) delete *I;
37}
38
Ted Kremenekcf118d42009-02-04 23:49:09 +000039//===----------------------------------------------------------------------===//
Ted Kremenek31061982009-03-31 23:00:32 +000040// Helper routines for walking the ExplodedGraph and fetching statements.
Ted Kremenekcf118d42009-02-04 23:49:09 +000041//===----------------------------------------------------------------------===//
Ted Kremenek61f3e052008-04-03 04:42:52 +000042
Ted Kremenekb697b102009-02-23 22:44:26 +000043static inline Stmt* GetStmt(ProgramPoint P) {
44 if (const PostStmt* PS = dyn_cast<PostStmt>(&P))
Ted Kremenek61f3e052008-04-03 04:42:52 +000045 return PS->getStmt();
Ted Kremenekb697b102009-02-23 22:44:26 +000046 else if (const BlockEdge* BE = dyn_cast<BlockEdge>(&P))
Ted Kremenek61f3e052008-04-03 04:42:52 +000047 return BE->getSrc()->getTerminator();
Ted Kremenek61f3e052008-04-03 04:42:52 +000048
Ted Kremenekb697b102009-02-23 22:44:26 +000049 return 0;
Ted Kremenek706e3cf2008-04-07 23:35:17 +000050}
51
Ted Kremenek3148eb42009-01-24 00:55:43 +000052static inline const ExplodedNode<GRState>*
Ted Kremenekb697b102009-02-23 22:44:26 +000053GetPredecessorNode(const ExplodedNode<GRState>* N) {
Ted Kremenekbd7efa82008-04-17 23:44:37 +000054 return N->pred_empty() ? NULL : *(N->pred_begin());
55}
Ted Kremenek2673c9f2008-04-25 19:01:27 +000056
Ted Kremenekb697b102009-02-23 22:44:26 +000057static inline const ExplodedNode<GRState>*
58GetSuccessorNode(const ExplodedNode<GRState>* N) {
59 return N->succ_empty() ? NULL : *(N->succ_begin());
Ted Kremenekbd7efa82008-04-17 23:44:37 +000060}
61
Ted Kremenekb697b102009-02-23 22:44:26 +000062static Stmt* GetPreviousStmt(const ExplodedNode<GRState>* N) {
63 for (N = GetPredecessorNode(N); N; N = GetPredecessorNode(N))
64 if (Stmt *S = GetStmt(N->getLocation()))
65 return S;
66
67 return 0;
Ted Kremenek3148eb42009-01-24 00:55:43 +000068}
69
Ted Kremenekb697b102009-02-23 22:44:26 +000070static Stmt* GetNextStmt(const ExplodedNode<GRState>* N) {
71 for (N = GetSuccessorNode(N); N; N = GetSuccessorNode(N))
Ted Kremenekf5ab8e62009-03-28 17:33:57 +000072 if (Stmt *S = GetStmt(N->getLocation())) {
73 // Check if the statement is '?' or '&&'/'||'. These are "merges",
74 // not actual statement points.
75 switch (S->getStmtClass()) {
76 case Stmt::ChooseExprClass:
77 case Stmt::ConditionalOperatorClass: continue;
78 case Stmt::BinaryOperatorClass: {
79 BinaryOperator::Opcode Op = cast<BinaryOperator>(S)->getOpcode();
80 if (Op == BinaryOperator::LAnd || Op == BinaryOperator::LOr)
81 continue;
82 break;
83 }
84 default:
85 break;
86 }
Ted Kremenekb697b102009-02-23 22:44:26 +000087 return S;
Ted Kremenekf5ab8e62009-03-28 17:33:57 +000088 }
Ted Kremenekb697b102009-02-23 22:44:26 +000089
90 return 0;
91}
92
93static inline Stmt* GetCurrentOrPreviousStmt(const ExplodedNode<GRState>* N) {
94 if (Stmt *S = GetStmt(N->getLocation()))
95 return S;
96
97 return GetPreviousStmt(N);
98}
99
100static inline Stmt* GetCurrentOrNextStmt(const ExplodedNode<GRState>* N) {
101 if (Stmt *S = GetStmt(N->getLocation()))
102 return S;
103
104 return GetNextStmt(N);
105}
106
107//===----------------------------------------------------------------------===//
Ted Kremenek31061982009-03-31 23:00:32 +0000108// PathDiagnosticBuilder and its associated routines and helper objects.
Ted Kremenekb697b102009-02-23 22:44:26 +0000109//===----------------------------------------------------------------------===//
Ted Kremenekb479dad2009-02-23 23:13:51 +0000110
Ted Kremenek7dc86642009-03-31 20:22:36 +0000111typedef llvm::DenseMap<const ExplodedNode<GRState>*,
112const ExplodedNode<GRState>*> NodeBackMap;
113
Ted Kremenekbabdd7b2009-03-27 05:06:10 +0000114namespace {
Ted Kremenek7dc86642009-03-31 20:22:36 +0000115class VISIBILITY_HIDDEN NodeMapClosure : public BugReport::NodeResolver {
116 NodeBackMap& M;
117public:
118 NodeMapClosure(NodeBackMap *m) : M(*m) {}
119 ~NodeMapClosure() {}
120
121 const ExplodedNode<GRState>* getOriginalNode(const ExplodedNode<GRState>* N) {
122 NodeBackMap::iterator I = M.find(N);
123 return I == M.end() ? 0 : I->second;
124 }
125};
126
Ted Kremenek8966bc12009-05-06 21:39:49 +0000127class VISIBILITY_HIDDEN PathDiagnosticBuilder : public BugReporterContext {
Ted Kremenek7dc86642009-03-31 20:22:36 +0000128 BugReport *R;
Ted Kremenekbabdd7b2009-03-27 05:06:10 +0000129 PathDiagnosticClient *PDC;
Ted Kremenek00605e02009-03-27 20:55:39 +0000130 llvm::OwningPtr<ParentMap> PM;
Ted Kremenek7dc86642009-03-31 20:22:36 +0000131 NodeMapClosure NMC;
Ted Kremenekbabdd7b2009-03-27 05:06:10 +0000132public:
Ted Kremenek8966bc12009-05-06 21:39:49 +0000133 PathDiagnosticBuilder(GRBugReporter &br,
Ted Kremenek7dc86642009-03-31 20:22:36 +0000134 BugReport *r, NodeBackMap *Backmap,
Ted Kremenek8966bc12009-05-06 21:39:49 +0000135 PathDiagnosticClient *pdc)
136 : BugReporterContext(br),
137 R(r), PDC(pdc), NMC(Backmap)
138 {
139 addVisitor(R);
140 }
Ted Kremenekbabdd7b2009-03-27 05:06:10 +0000141
Ted Kremenek00605e02009-03-27 20:55:39 +0000142 PathDiagnosticLocation ExecutionContinues(const ExplodedNode<GRState>* N);
Ted Kremenekbabdd7b2009-03-27 05:06:10 +0000143
Ted Kremenek00605e02009-03-27 20:55:39 +0000144 PathDiagnosticLocation ExecutionContinues(llvm::raw_string_ostream& os,
145 const ExplodedNode<GRState>* N);
146
147 ParentMap& getParentMap() {
Ted Kremenek8966bc12009-05-06 21:39:49 +0000148 if (PM.get() == 0)
149 PM.reset(new ParentMap(getCodeDecl().getBody(getASTContext())));
Ted Kremenek00605e02009-03-27 20:55:39 +0000150 return *PM.get();
151 }
Ted Kremenekbabdd7b2009-03-27 05:06:10 +0000152
Ted Kremenekc3f83ad2009-04-01 17:18:21 +0000153 const Stmt *getParent(const Stmt *S) {
154 return getParentMap().getParent(S);
155 }
Ted Kremenek8966bc12009-05-06 21:39:49 +0000156
157 virtual NodeMapClosure& getNodeResolver() { return NMC; }
Ted Kremenek7dc86642009-03-31 20:22:36 +0000158 BugReport& getReport() { return *R; }
Douglas Gregor72971342009-04-18 00:02:19 +0000159
Ted Kremenekd8c938b2009-03-27 21:16:25 +0000160 PathDiagnosticLocation getEnclosingStmtLocation(const Stmt *S);
161
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000162 PathDiagnosticLocation
163 getEnclosingStmtLocation(const PathDiagnosticLocation &L) {
164 if (const Stmt *S = L.asStmt())
165 return getEnclosingStmtLocation(S);
166
167 return L;
168 }
169
Ted Kremenek7dc86642009-03-31 20:22:36 +0000170 PathDiagnosticClient::PathGenerationScheme getGenerationScheme() const {
171 return PDC ? PDC->getGenerationScheme() : PathDiagnosticClient::Extensive;
172 }
173
Ted Kremenekbabdd7b2009-03-27 05:06:10 +0000174 bool supportsLogicalOpControlFlow() const {
175 return PDC ? PDC->supportsLogicalOpControlFlow() : true;
176 }
177};
178} // end anonymous namespace
179
Ted Kremenek00605e02009-03-27 20:55:39 +0000180PathDiagnosticLocation
181PathDiagnosticBuilder::ExecutionContinues(const ExplodedNode<GRState>* N) {
182 if (Stmt *S = GetNextStmt(N))
Ted Kremenek8966bc12009-05-06 21:39:49 +0000183 return PathDiagnosticLocation(S, getSourceManager());
Ted Kremenek00605e02009-03-27 20:55:39 +0000184
Ted Kremenek8966bc12009-05-06 21:39:49 +0000185 return FullSourceLoc(getCodeDecl().getBodyRBrace(getASTContext()),
186 getSourceManager());
Ted Kremenek082cb8d2009-03-12 18:41:53 +0000187}
188
Ted Kremenek00605e02009-03-27 20:55:39 +0000189PathDiagnosticLocation
Ted Kremenekbabdd7b2009-03-27 05:06:10 +0000190PathDiagnosticBuilder::ExecutionContinues(llvm::raw_string_ostream& os,
191 const ExplodedNode<GRState>* N) {
192
Ted Kremenek143ca222008-05-06 18:11:09 +0000193 // Slow, but probably doesn't matter.
Ted Kremenekb697b102009-02-23 22:44:26 +0000194 if (os.str().empty())
195 os << ' ';
Ted Kremenek143ca222008-05-06 18:11:09 +0000196
Ted Kremenek00605e02009-03-27 20:55:39 +0000197 const PathDiagnosticLocation &Loc = ExecutionContinues(N);
Ted Kremenek082cb8d2009-03-12 18:41:53 +0000198
Ted Kremenek00605e02009-03-27 20:55:39 +0000199 if (Loc.asStmt())
Ted Kremenekb697b102009-02-23 22:44:26 +0000200 os << "Execution continues on line "
Ted Kremenek8966bc12009-05-06 21:39:49 +0000201 << getSourceManager().getInstantiationLineNumber(Loc.asLocation())
202 << '.';
Ted Kremenekb697b102009-02-23 22:44:26 +0000203 else
Ted Kremenekb479dad2009-02-23 23:13:51 +0000204 os << "Execution jumps to the end of the "
Ted Kremenek8966bc12009-05-06 21:39:49 +0000205 << (isa<ObjCMethodDecl>(getCodeDecl()) ? "method" : "function") << '.';
Ted Kremenek082cb8d2009-03-12 18:41:53 +0000206
207 return Loc;
Ted Kremenek143ca222008-05-06 18:11:09 +0000208}
209
Ted Kremenekd8c938b2009-03-27 21:16:25 +0000210PathDiagnosticLocation
211PathDiagnosticBuilder::getEnclosingStmtLocation(const Stmt *S) {
212 assert(S && "Null Stmt* passed to getEnclosingStmtLocation");
Ted Kremenekc42e07e2009-05-05 22:19:17 +0000213 ParentMap &P = getParentMap();
Ted Kremenek8966bc12009-05-06 21:39:49 +0000214 SourceManager &SMgr = getSourceManager();
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000215
Ted Kremenekc42e07e2009-05-05 22:19:17 +0000216 while (isa<Expr>(S) && P.isConsumedExpr(cast<Expr>(S))) {
Ted Kremenekd8c938b2009-03-27 21:16:25 +0000217 const Stmt *Parent = P.getParent(S);
218
Ted Kremenekaf3e3d52009-03-28 03:37:59 +0000219 if (!Parent)
220 break;
Ted Kremenekd8c938b2009-03-27 21:16:25 +0000221
Ted Kremenekaf3e3d52009-03-28 03:37:59 +0000222 switch (Parent->getStmtClass()) {
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000223 case Stmt::BinaryOperatorClass: {
224 const BinaryOperator *B = cast<BinaryOperator>(Parent);
225 if (B->isLogicalOp())
226 return PathDiagnosticLocation(S, SMgr);
227 break;
228 }
229
Ted Kremenekaf3e3d52009-03-28 03:37:59 +0000230 case Stmt::CompoundStmtClass:
231 case Stmt::StmtExprClass:
Ted Kremenek1d9a23a2009-03-28 04:08:14 +0000232 return PathDiagnosticLocation(S, SMgr);
233 case Stmt::ChooseExprClass:
234 // Similar to '?' if we are referring to condition, just have the edge
235 // point to the entire choose expression.
236 if (cast<ChooseExpr>(Parent)->getCond() == S)
237 return PathDiagnosticLocation(Parent, SMgr);
238 else
239 return PathDiagnosticLocation(S, SMgr);
240 case Stmt::ConditionalOperatorClass:
241 // For '?', if we are referring to condition, just have the edge point
242 // to the entire '?' expression.
243 if (cast<ConditionalOperator>(Parent)->getCond() == S)
244 return PathDiagnosticLocation(Parent, SMgr);
245 else
246 return PathDiagnosticLocation(S, SMgr);
Ted Kremenekaf3e3d52009-03-28 03:37:59 +0000247 case Stmt::DoStmtClass:
Ted Kremenekaf3e3d52009-03-28 03:37:59 +0000248 return PathDiagnosticLocation(S, SMgr);
Ted Kremenekaf3e3d52009-03-28 03:37:59 +0000249 case Stmt::ForStmtClass:
250 if (cast<ForStmt>(Parent)->getBody() == S)
251 return PathDiagnosticLocation(S, SMgr);
252 break;
253 case Stmt::IfStmtClass:
254 if (cast<IfStmt>(Parent)->getCond() != S)
255 return PathDiagnosticLocation(S, SMgr);
Ted Kremenek8bd4d032009-04-28 04:23:15 +0000256 break;
Ted Kremenekaf3e3d52009-03-28 03:37:59 +0000257 case Stmt::ObjCForCollectionStmtClass:
258 if (cast<ObjCForCollectionStmt>(Parent)->getBody() == S)
259 return PathDiagnosticLocation(S, SMgr);
260 break;
261 case Stmt::WhileStmtClass:
262 if (cast<WhileStmt>(Parent)->getCond() != S)
263 return PathDiagnosticLocation(S, SMgr);
264 break;
265 default:
266 break;
267 }
268
Ted Kremenekd8c938b2009-03-27 21:16:25 +0000269 S = Parent;
270 }
271
272 assert(S && "Cannot have null Stmt for PathDiagnosticLocation");
273 return PathDiagnosticLocation(S, SMgr);
274}
275
Ted Kremenekcf118d42009-02-04 23:49:09 +0000276//===----------------------------------------------------------------------===//
Ted Kremenek31061982009-03-31 23:00:32 +0000277// ScanNotableSymbols: closure-like callback for scanning Store bindings.
278//===----------------------------------------------------------------------===//
279
280static const VarDecl*
281GetMostRecentVarDeclBinding(const ExplodedNode<GRState>* N,
282 GRStateManager& VMgr, SVal X) {
283
284 for ( ; N ; N = N->pred_empty() ? 0 : *N->pred_begin()) {
285
286 ProgramPoint P = N->getLocation();
287
288 if (!isa<PostStmt>(P))
289 continue;
290
291 DeclRefExpr* DR = dyn_cast<DeclRefExpr>(cast<PostStmt>(P).getStmt());
292
293 if (!DR)
294 continue;
295
296 SVal Y = VMgr.GetSVal(N->getState(), DR);
297
298 if (X != Y)
299 continue;
300
301 VarDecl* VD = dyn_cast<VarDecl>(DR->getDecl());
302
303 if (!VD)
304 continue;
305
306 return VD;
307 }
308
309 return 0;
310}
311
312namespace {
313class VISIBILITY_HIDDEN NotableSymbolHandler
314: public StoreManager::BindingsHandler {
315
316 SymbolRef Sym;
317 const GRState* PrevSt;
318 const Stmt* S;
319 GRStateManager& VMgr;
320 const ExplodedNode<GRState>* Pred;
321 PathDiagnostic& PD;
322 BugReporter& BR;
323
324public:
325
326 NotableSymbolHandler(SymbolRef sym, const GRState* prevst, const Stmt* s,
327 GRStateManager& vmgr, const ExplodedNode<GRState>* pred,
328 PathDiagnostic& pd, BugReporter& br)
329 : Sym(sym), PrevSt(prevst), S(s), VMgr(vmgr), Pred(pred), PD(pd), BR(br) {}
330
331 bool HandleBinding(StoreManager& SMgr, Store store, const MemRegion* R,
332 SVal V) {
333
334 SymbolRef ScanSym = V.getAsSymbol();
335
336 if (ScanSym != Sym)
337 return true;
338
339 // Check if the previous state has this binding.
340 SVal X = VMgr.GetSVal(PrevSt, loc::MemRegionVal(R));
341
342 if (X == V) // Same binding?
343 return true;
344
345 // Different binding. Only handle assignments for now. We don't pull
346 // this check out of the loop because we will eventually handle other
347 // cases.
348
349 VarDecl *VD = 0;
350
351 if (const BinaryOperator* B = dyn_cast<BinaryOperator>(S)) {
352 if (!B->isAssignmentOp())
353 return true;
354
355 // What variable did we assign to?
356 DeclRefExpr* DR = dyn_cast<DeclRefExpr>(B->getLHS()->IgnoreParenCasts());
357
358 if (!DR)
359 return true;
360
361 VD = dyn_cast<VarDecl>(DR->getDecl());
362 }
363 else if (const DeclStmt* DS = dyn_cast<DeclStmt>(S)) {
364 // FIXME: Eventually CFGs won't have DeclStmts. Right now we
365 // assume that each DeclStmt has a single Decl. This invariant
366 // holds by contruction in the CFG.
367 VD = dyn_cast<VarDecl>(*DS->decl_begin());
368 }
369
370 if (!VD)
371 return true;
372
373 // What is the most recently referenced variable with this binding?
374 const VarDecl* MostRecent = GetMostRecentVarDeclBinding(Pred, VMgr, V);
375
376 if (!MostRecent)
377 return true;
378
379 // Create the diagnostic.
380 FullSourceLoc L(S->getLocStart(), BR.getSourceManager());
381
382 if (Loc::IsLocType(VD->getType())) {
383 std::string msg = "'" + std::string(VD->getNameAsString()) +
384 "' now aliases '" + MostRecent->getNameAsString() + "'";
385
386 PD.push_front(new PathDiagnosticEventPiece(L, msg));
387 }
388
389 return true;
390 }
391};
392}
393
394static void HandleNotableSymbol(const ExplodedNode<GRState>* N,
395 const Stmt* S,
396 SymbolRef Sym, BugReporter& BR,
397 PathDiagnostic& PD) {
398
399 const ExplodedNode<GRState>* Pred = N->pred_empty() ? 0 : *N->pred_begin();
400 const GRState* PrevSt = Pred ? Pred->getState() : 0;
401
402 if (!PrevSt)
403 return;
404
405 // Look at the region bindings of the current state that map to the
406 // specified symbol. Are any of them not in the previous state?
407 GRStateManager& VMgr = cast<GRBugReporter>(BR).getStateManager();
408 NotableSymbolHandler H(Sym, PrevSt, S, VMgr, Pred, PD, BR);
409 cast<GRBugReporter>(BR).getStateManager().iterBindings(N->getState(), H);
410}
411
412namespace {
413class VISIBILITY_HIDDEN ScanNotableSymbols
414: public StoreManager::BindingsHandler {
415
416 llvm::SmallSet<SymbolRef, 10> AlreadyProcessed;
417 const ExplodedNode<GRState>* N;
418 Stmt* S;
419 GRBugReporter& BR;
420 PathDiagnostic& PD;
421
422public:
423 ScanNotableSymbols(const ExplodedNode<GRState>* n, Stmt* s, GRBugReporter& br,
424 PathDiagnostic& pd)
425 : N(n), S(s), BR(br), PD(pd) {}
426
427 bool HandleBinding(StoreManager& SMgr, Store store,
428 const MemRegion* R, SVal V) {
429
430 SymbolRef ScanSym = V.getAsSymbol();
431
432 if (!ScanSym)
433 return true;
434
435 if (!BR.isNotable(ScanSym))
436 return true;
437
438 if (AlreadyProcessed.count(ScanSym))
439 return true;
440
441 AlreadyProcessed.insert(ScanSym);
442
443 HandleNotableSymbol(N, S, ScanSym, BR, PD);
444 return true;
445 }
446};
447} // end anonymous namespace
448
449//===----------------------------------------------------------------------===//
450// "Minimal" path diagnostic generation algorithm.
451//===----------------------------------------------------------------------===//
452
Ted Kremenek14856d72009-04-06 23:06:54 +0000453static void CompactPathDiagnostic(PathDiagnostic &PD, const SourceManager& SM);
454
Ted Kremenek31061982009-03-31 23:00:32 +0000455static void GenerateMinimalPathDiagnostic(PathDiagnostic& PD,
456 PathDiagnosticBuilder &PDB,
457 const ExplodedNode<GRState> *N) {
Ted Kremenek8966bc12009-05-06 21:39:49 +0000458
Ted Kremenek31061982009-03-31 23:00:32 +0000459 SourceManager& SMgr = PDB.getSourceManager();
460 const ExplodedNode<GRState>* NextNode = N->pred_empty()
461 ? NULL : *(N->pred_begin());
462 while (NextNode) {
463 N = NextNode;
464 NextNode = GetPredecessorNode(N);
465
466 ProgramPoint P = N->getLocation();
467
468 if (const BlockEdge* BE = dyn_cast<BlockEdge>(&P)) {
469 CFGBlock* Src = BE->getSrc();
470 CFGBlock* Dst = BE->getDst();
471 Stmt* T = Src->getTerminator();
472
473 if (!T)
474 continue;
475
476 FullSourceLoc Start(T->getLocStart(), SMgr);
477
478 switch (T->getStmtClass()) {
479 default:
480 break;
481
482 case Stmt::GotoStmtClass:
483 case Stmt::IndirectGotoStmtClass: {
484 Stmt* S = GetNextStmt(N);
485
486 if (!S)
487 continue;
488
489 std::string sbuf;
490 llvm::raw_string_ostream os(sbuf);
491 const PathDiagnosticLocation &End = PDB.getEnclosingStmtLocation(S);
492
493 os << "Control jumps to line "
494 << End.asLocation().getInstantiationLineNumber();
495 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
496 os.str()));
497 break;
498 }
499
500 case Stmt::SwitchStmtClass: {
501 // Figure out what case arm we took.
502 std::string sbuf;
503 llvm::raw_string_ostream os(sbuf);
504
505 if (Stmt* S = Dst->getLabel()) {
506 PathDiagnosticLocation End(S, SMgr);
507
508 switch (S->getStmtClass()) {
509 default:
510 os << "No cases match in the switch statement. "
511 "Control jumps to line "
512 << End.asLocation().getInstantiationLineNumber();
513 break;
514 case Stmt::DefaultStmtClass:
515 os << "Control jumps to the 'default' case at line "
516 << End.asLocation().getInstantiationLineNumber();
517 break;
518
519 case Stmt::CaseStmtClass: {
520 os << "Control jumps to 'case ";
521 CaseStmt* Case = cast<CaseStmt>(S);
522 Expr* LHS = Case->getLHS()->IgnoreParenCasts();
523
524 // Determine if it is an enum.
525 bool GetRawInt = true;
526
527 if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(LHS)) {
528 // FIXME: Maybe this should be an assertion. Are there cases
529 // were it is not an EnumConstantDecl?
530 EnumConstantDecl* D =
531 dyn_cast<EnumConstantDecl>(DR->getDecl());
532
533 if (D) {
534 GetRawInt = false;
535 os << D->getNameAsString();
536 }
537 }
Eli Friedman9ec64d62009-04-26 19:04:51 +0000538
539 if (GetRawInt)
Ted Kremenek8966bc12009-05-06 21:39:49 +0000540 os << LHS->EvaluateAsInt(PDB.getASTContext());
Eli Friedman9ec64d62009-04-26 19:04:51 +0000541
Ted Kremenek31061982009-03-31 23:00:32 +0000542 os << ":' at line "
543 << End.asLocation().getInstantiationLineNumber();
544 break;
545 }
546 }
547 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
548 os.str()));
549 }
550 else {
551 os << "'Default' branch taken. ";
552 const PathDiagnosticLocation &End = PDB.ExecutionContinues(os, N);
553 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
554 os.str()));
555 }
556
557 break;
558 }
559
560 case Stmt::BreakStmtClass:
561 case Stmt::ContinueStmtClass: {
562 std::string sbuf;
563 llvm::raw_string_ostream os(sbuf);
564 PathDiagnosticLocation End = PDB.ExecutionContinues(os, N);
565 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
566 os.str()));
567 break;
568 }
569
570 // Determine control-flow for ternary '?'.
571 case Stmt::ConditionalOperatorClass: {
572 std::string sbuf;
573 llvm::raw_string_ostream os(sbuf);
574 os << "'?' condition is ";
575
576 if (*(Src->succ_begin()+1) == Dst)
577 os << "false";
578 else
579 os << "true";
580
581 PathDiagnosticLocation End = PDB.ExecutionContinues(N);
582
583 if (const Stmt *S = End.asStmt())
584 End = PDB.getEnclosingStmtLocation(S);
585
586 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
587 os.str()));
588 break;
589 }
590
591 // Determine control-flow for short-circuited '&&' and '||'.
592 case Stmt::BinaryOperatorClass: {
593 if (!PDB.supportsLogicalOpControlFlow())
594 break;
595
596 BinaryOperator *B = cast<BinaryOperator>(T);
597 std::string sbuf;
598 llvm::raw_string_ostream os(sbuf);
599 os << "Left side of '";
600
601 if (B->getOpcode() == BinaryOperator::LAnd) {
602 os << "&&" << "' is ";
603
604 if (*(Src->succ_begin()+1) == Dst) {
605 os << "false";
606 PathDiagnosticLocation End(B->getLHS(), SMgr);
607 PathDiagnosticLocation Start(B->getOperatorLoc(), SMgr);
608 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
609 os.str()));
610 }
611 else {
612 os << "true";
613 PathDiagnosticLocation Start(B->getLHS(), SMgr);
614 PathDiagnosticLocation End = PDB.ExecutionContinues(N);
615 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
616 os.str()));
617 }
618 }
619 else {
620 assert(B->getOpcode() == BinaryOperator::LOr);
621 os << "||" << "' is ";
622
623 if (*(Src->succ_begin()+1) == Dst) {
624 os << "false";
625 PathDiagnosticLocation Start(B->getLHS(), SMgr);
626 PathDiagnosticLocation End = PDB.ExecutionContinues(N);
627 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
628 os.str()));
629 }
630 else {
631 os << "true";
632 PathDiagnosticLocation End(B->getLHS(), SMgr);
633 PathDiagnosticLocation Start(B->getOperatorLoc(), SMgr);
634 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
635 os.str()));
636 }
637 }
638
639 break;
640 }
641
642 case Stmt::DoStmtClass: {
643 if (*(Src->succ_begin()) == Dst) {
644 std::string sbuf;
645 llvm::raw_string_ostream os(sbuf);
646
647 os << "Loop condition is true. ";
648 PathDiagnosticLocation End = PDB.ExecutionContinues(os, N);
649
650 if (const Stmt *S = End.asStmt())
651 End = PDB.getEnclosingStmtLocation(S);
652
653 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
654 os.str()));
655 }
656 else {
657 PathDiagnosticLocation End = PDB.ExecutionContinues(N);
658
659 if (const Stmt *S = End.asStmt())
660 End = PDB.getEnclosingStmtLocation(S);
661
662 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
663 "Loop condition is false. Exiting loop"));
664 }
665
666 break;
667 }
668
669 case Stmt::WhileStmtClass:
670 case Stmt::ForStmtClass: {
671 if (*(Src->succ_begin()+1) == Dst) {
672 std::string sbuf;
673 llvm::raw_string_ostream os(sbuf);
674
675 os << "Loop condition is false. ";
676 PathDiagnosticLocation End = PDB.ExecutionContinues(os, N);
677 if (const Stmt *S = End.asStmt())
678 End = PDB.getEnclosingStmtLocation(S);
679
680 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
681 os.str()));
682 }
683 else {
684 PathDiagnosticLocation End = PDB.ExecutionContinues(N);
685 if (const Stmt *S = End.asStmt())
686 End = PDB.getEnclosingStmtLocation(S);
687
688 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000689 "Loop condition is true. Entering loop body"));
Ted Kremenek31061982009-03-31 23:00:32 +0000690 }
691
692 break;
693 }
694
695 case Stmt::IfStmtClass: {
696 PathDiagnosticLocation End = PDB.ExecutionContinues(N);
697
698 if (const Stmt *S = End.asStmt())
699 End = PDB.getEnclosingStmtLocation(S);
700
701 if (*(Src->succ_begin()+1) == Dst)
702 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000703 "Taking false branch"));
Ted Kremenek31061982009-03-31 23:00:32 +0000704 else
705 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000706 "Taking true branch"));
Ted Kremenek31061982009-03-31 23:00:32 +0000707
708 break;
709 }
710 }
711 }
712
Ted Kremenekdd986cc2009-05-07 00:45:33 +0000713 if (NextNode) {
714 for (BugReporterContext::visitor_iterator I = PDB.visitor_begin(),
715 E = PDB.visitor_end(); I!=E; ++I) {
716 if (PathDiagnosticPiece* p = (*I)->VisitNode(N, NextNode, PDB))
717 PD.push_front(p);
718 }
Ted Kremenek8966bc12009-05-06 21:39:49 +0000719 }
Ted Kremenek31061982009-03-31 23:00:32 +0000720
721 if (const PostStmt* PS = dyn_cast<PostStmt>(&P)) {
722 // Scan the region bindings, and see if a "notable" symbol has a new
723 // lval binding.
724 ScanNotableSymbols SNS(N, PS->getStmt(), PDB.getBugReporter(), PD);
725 PDB.getStateManager().iterBindings(N->getState(), SNS);
726 }
727 }
Ted Kremenek14856d72009-04-06 23:06:54 +0000728
729 // After constructing the full PathDiagnostic, do a pass over it to compact
730 // PathDiagnosticPieces that occur within a macro.
731 CompactPathDiagnostic(PD, PDB.getSourceManager());
Ted Kremenek31061982009-03-31 23:00:32 +0000732}
733
734//===----------------------------------------------------------------------===//
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000735// "Extensive" PathDiagnostic generation.
736//===----------------------------------------------------------------------===//
737
738static bool IsControlFlowExpr(const Stmt *S) {
739 const Expr *E = dyn_cast<Expr>(S);
Ted Kremenek14856d72009-04-06 23:06:54 +0000740
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000741 if (!E)
742 return false;
743
744 E = E->IgnoreParenCasts();
745
746 if (isa<ConditionalOperator>(E))
747 return true;
748
749 if (const BinaryOperator *B = dyn_cast<BinaryOperator>(E))
750 if (B->isLogicalOp())
751 return true;
752
753 return false;
754}
755
Ted Kremenek14856d72009-04-06 23:06:54 +0000756namespace {
Ted Kremenek8f9b1b32009-05-01 16:08:09 +0000757class VISIBILITY_HIDDEN ContextLocation : public PathDiagnosticLocation {
758 bool IsDead;
759public:
760 ContextLocation(const PathDiagnosticLocation &L, bool isdead = false)
761 : PathDiagnosticLocation(L), IsDead(isdead) {}
762
763 void markDead() { IsDead = true; }
764 bool isDead() const { return IsDead; }
765};
766
Ted Kremenek14856d72009-04-06 23:06:54 +0000767class VISIBILITY_HIDDEN EdgeBuilder {
Ted Kremenek8f9b1b32009-05-01 16:08:09 +0000768 std::vector<ContextLocation> CLocs;
769 typedef std::vector<ContextLocation>::iterator iterator;
Ted Kremenek14856d72009-04-06 23:06:54 +0000770 PathDiagnostic &PD;
771 PathDiagnosticBuilder &PDB;
772 PathDiagnosticLocation PrevLoc;
Ted Kremenek8f9b1b32009-05-01 16:08:09 +0000773
774 bool IsConsumedExpr(const PathDiagnosticLocation &L);
775
Ted Kremenek14856d72009-04-06 23:06:54 +0000776 bool containsLocation(const PathDiagnosticLocation &Container,
777 const PathDiagnosticLocation &Containee);
778
779 PathDiagnosticLocation getContextLocation(const PathDiagnosticLocation &L);
Ted Kremenek14856d72009-04-06 23:06:54 +0000780
781 void popLocation() {
Ted Kremenek8f9b1b32009-05-01 16:08:09 +0000782 if (!CLocs.back().isDead() && CLocs.back().asLocation().isFileID()) {
783 PathDiagnosticLocation L = CLocs.back();
Ted Kremenekc2924d02009-04-23 16:19:29 +0000784
Ted Kremenek6f132352009-04-23 16:44:22 +0000785 if (const Stmt *S = L.asStmt()) {
786 while (1) {
787 // Adjust the location for some expressions that are best referenced
788 // by one of their subexpressions.
789 if (const ParenExpr *PE = dyn_cast<ParenExpr>(S))
790 S = PE->IgnoreParens();
791 else if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(S))
792 S = CO->getCond();
793 else if (const ChooseExpr *CE = dyn_cast<ChooseExpr>(S))
794 S = CE->getCond();
795 else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(S))
796 S = BE->getLHS();
797 else
798 break;
799 }
800
Ted Kremenekc2924d02009-04-23 16:19:29 +0000801 L = PathDiagnosticLocation(S, L.getManager());
802 }
803
Ted Kremenek5c7168c2009-04-22 20:36:26 +0000804 // For contexts, we only one the first character as the range.
805 L = PathDiagnosticLocation(L.asLocation(), L.getManager());
Ted Kremenek4f5be3b2009-04-22 20:51:59 +0000806 rawAddEdge(L);
Ted Kremenek5c7168c2009-04-22 20:36:26 +0000807 }
Ted Kremenek14856d72009-04-06 23:06:54 +0000808 CLocs.pop_back();
809 }
810
811 PathDiagnosticLocation IgnoreParens(const PathDiagnosticLocation &L);
812
813public:
814 EdgeBuilder(PathDiagnostic &pd, PathDiagnosticBuilder &pdb)
815 : PD(pd), PDB(pdb) {
Ted Kremeneka301a672009-04-22 18:16:20 +0000816
817 // If the PathDiagnostic already has pieces, add the enclosing statement
818 // of the first piece as a context as well.
Ted Kremenek14856d72009-04-06 23:06:54 +0000819 if (!PD.empty()) {
820 PrevLoc = PD.begin()->getLocation();
821
822 if (const Stmt *S = PrevLoc.asStmt())
Ted Kremeneke1baed32009-05-05 23:13:38 +0000823 addExtendedContext(PDB.getEnclosingStmtLocation(S).asStmt());
Ted Kremenek14856d72009-04-06 23:06:54 +0000824 }
825 }
826
827 ~EdgeBuilder() {
828 while (!CLocs.empty()) popLocation();
Ted Kremeneka301a672009-04-22 18:16:20 +0000829
830 // Finally, add an initial edge from the start location of the first
831 // statement (if it doesn't already exist).
Sebastian Redld3a413d2009-04-26 20:35:05 +0000832 // FIXME: Should handle CXXTryStmt if analyser starts supporting C++.
833 if (const CompoundStmt *CS =
Ted Kremenek8966bc12009-05-06 21:39:49 +0000834 PDB.getCodeDecl().getCompoundBody(PDB.getASTContext()))
Ted Kremeneka301a672009-04-22 18:16:20 +0000835 if (!CS->body_empty()) {
836 SourceLocation Loc = (*CS->body_begin())->getLocStart();
837 rawAddEdge(PathDiagnosticLocation(Loc, PDB.getSourceManager()));
838 }
839
Ted Kremenek14856d72009-04-06 23:06:54 +0000840 }
841
842 void addEdge(PathDiagnosticLocation NewLoc, bool alwaysAdd = false);
843
844 void addEdge(const Stmt *S, bool alwaysAdd = false) {
845 addEdge(PathDiagnosticLocation(S, PDB.getSourceManager()), alwaysAdd);
846 }
847
Ted Kremenek8bd4d032009-04-28 04:23:15 +0000848 void rawAddEdge(PathDiagnosticLocation NewLoc);
849
Ted Kremenek14856d72009-04-06 23:06:54 +0000850 void addContext(const Stmt *S);
Ted Kremeneke1baed32009-05-05 23:13:38 +0000851 void addExtendedContext(const Stmt *S);
Ted Kremenek14856d72009-04-06 23:06:54 +0000852};
853} // end anonymous namespace
854
855
856PathDiagnosticLocation
857EdgeBuilder::getContextLocation(const PathDiagnosticLocation &L) {
858 if (const Stmt *S = L.asStmt()) {
859 if (IsControlFlowExpr(S))
860 return L;
861
862 return PDB.getEnclosingStmtLocation(S);
863 }
864
865 return L;
866}
867
868bool EdgeBuilder::containsLocation(const PathDiagnosticLocation &Container,
869 const PathDiagnosticLocation &Containee) {
870
871 if (Container == Containee)
872 return true;
873
874 if (Container.asDecl())
875 return true;
876
877 if (const Stmt *S = Containee.asStmt())
878 if (const Stmt *ContainerS = Container.asStmt()) {
879 while (S) {
880 if (S == ContainerS)
881 return true;
882 S = PDB.getParent(S);
883 }
884 return false;
885 }
886
887 // Less accurate: compare using source ranges.
888 SourceRange ContainerR = Container.asRange();
889 SourceRange ContaineeR = Containee.asRange();
890
891 SourceManager &SM = PDB.getSourceManager();
892 SourceLocation ContainerRBeg = SM.getInstantiationLoc(ContainerR.getBegin());
893 SourceLocation ContainerREnd = SM.getInstantiationLoc(ContainerR.getEnd());
894 SourceLocation ContaineeRBeg = SM.getInstantiationLoc(ContaineeR.getBegin());
895 SourceLocation ContaineeREnd = SM.getInstantiationLoc(ContaineeR.getEnd());
896
897 unsigned ContainerBegLine = SM.getInstantiationLineNumber(ContainerRBeg);
898 unsigned ContainerEndLine = SM.getInstantiationLineNumber(ContainerREnd);
899 unsigned ContaineeBegLine = SM.getInstantiationLineNumber(ContaineeRBeg);
900 unsigned ContaineeEndLine = SM.getInstantiationLineNumber(ContaineeREnd);
901
902 assert(ContainerBegLine <= ContainerEndLine);
903 assert(ContaineeBegLine <= ContaineeEndLine);
904
905 return (ContainerBegLine <= ContaineeBegLine &&
906 ContainerEndLine >= ContaineeEndLine &&
907 (ContainerBegLine != ContaineeBegLine ||
908 SM.getInstantiationColumnNumber(ContainerRBeg) <=
909 SM.getInstantiationColumnNumber(ContaineeRBeg)) &&
910 (ContainerEndLine != ContaineeEndLine ||
911 SM.getInstantiationColumnNumber(ContainerREnd) >=
912 SM.getInstantiationColumnNumber(ContainerREnd)));
913}
914
915PathDiagnosticLocation
916EdgeBuilder::IgnoreParens(const PathDiagnosticLocation &L) {
917 if (const Expr* E = dyn_cast_or_null<Expr>(L.asStmt()))
918 return PathDiagnosticLocation(E->IgnoreParenCasts(),
919 PDB.getSourceManager());
920 return L;
921}
922
923void EdgeBuilder::rawAddEdge(PathDiagnosticLocation NewLoc) {
924 if (!PrevLoc.isValid()) {
925 PrevLoc = NewLoc;
926 return;
927 }
928
929 if (NewLoc.asLocation() == PrevLoc.asLocation())
930 return;
931
932 // FIXME: Ignore intra-macro edges for now.
933 if (NewLoc.asLocation().getInstantiationLoc() ==
934 PrevLoc.asLocation().getInstantiationLoc())
935 return;
936
937 PD.push_front(new PathDiagnosticControlFlowPiece(NewLoc, PrevLoc));
938 PrevLoc = NewLoc;
939}
940
941void EdgeBuilder::addEdge(PathDiagnosticLocation NewLoc, bool alwaysAdd) {
Ted Kremeneka301a672009-04-22 18:16:20 +0000942
943 if (!alwaysAdd && NewLoc.asLocation().isMacroID())
944 return;
945
Ted Kremenek14856d72009-04-06 23:06:54 +0000946 const PathDiagnosticLocation &CLoc = getContextLocation(NewLoc);
947
948 while (!CLocs.empty()) {
Ted Kremenek8f9b1b32009-05-01 16:08:09 +0000949 ContextLocation &TopContextLoc = CLocs.back();
Ted Kremenek14856d72009-04-06 23:06:54 +0000950
951 // Is the top location context the same as the one for the new location?
952 if (TopContextLoc == CLoc) {
Ted Kremenek8f9b1b32009-05-01 16:08:09 +0000953 if (alwaysAdd) {
Ted Kremenek4c6f8d32009-05-04 18:15:17 +0000954 if (IsConsumedExpr(TopContextLoc) &&
955 !IsControlFlowExpr(TopContextLoc.asStmt()))
Ted Kremenek8f9b1b32009-05-01 16:08:09 +0000956 TopContextLoc.markDead();
957
Ted Kremenek14856d72009-04-06 23:06:54 +0000958 rawAddEdge(NewLoc);
Ted Kremenek8f9b1b32009-05-01 16:08:09 +0000959 }
Ted Kremenek14856d72009-04-06 23:06:54 +0000960
961 return;
962 }
963
964 if (containsLocation(TopContextLoc, CLoc)) {
Ted Kremenek8f9b1b32009-05-01 16:08:09 +0000965 if (alwaysAdd) {
Ted Kremenek14856d72009-04-06 23:06:54 +0000966 rawAddEdge(NewLoc);
Ted Kremenek8f9b1b32009-05-01 16:08:09 +0000967
Ted Kremenek4c6f8d32009-05-04 18:15:17 +0000968 if (IsConsumedExpr(CLoc) && !IsControlFlowExpr(CLoc.asStmt())) {
Ted Kremenek8f9b1b32009-05-01 16:08:09 +0000969 CLocs.push_back(ContextLocation(CLoc, true));
970 return;
971 }
972 }
973
Ted Kremenek14856d72009-04-06 23:06:54 +0000974 CLocs.push_back(CLoc);
975 return;
976 }
977
978 // Context does not contain the location. Flush it.
979 popLocation();
980 }
Ted Kremenek5c7168c2009-04-22 20:36:26 +0000981
982 // If we reach here, there is no enclosing context. Just add the edge.
983 rawAddEdge(NewLoc);
Ted Kremenek14856d72009-04-06 23:06:54 +0000984}
985
Ted Kremenek8f9b1b32009-05-01 16:08:09 +0000986bool EdgeBuilder::IsConsumedExpr(const PathDiagnosticLocation &L) {
987 if (const Expr *X = dyn_cast_or_null<Expr>(L.asStmt()))
988 return PDB.getParentMap().isConsumedExpr(X) && !IsControlFlowExpr(X);
989
990 return false;
991}
992
Ted Kremeneke1baed32009-05-05 23:13:38 +0000993void EdgeBuilder::addExtendedContext(const Stmt *S) {
994 if (!S)
995 return;
996
997 const Stmt *Parent = PDB.getParent(S);
998 while (Parent) {
999 if (isa<CompoundStmt>(Parent))
1000 Parent = PDB.getParent(Parent);
1001 else
1002 break;
1003 }
1004
1005 if (Parent) {
1006 switch (Parent->getStmtClass()) {
1007 case Stmt::DoStmtClass:
1008 case Stmt::ObjCAtSynchronizedStmtClass:
1009 addContext(Parent);
1010 default:
1011 break;
1012 }
1013 }
1014
1015 addContext(S);
1016}
1017
Ted Kremenek14856d72009-04-06 23:06:54 +00001018void EdgeBuilder::addContext(const Stmt *S) {
1019 if (!S)
1020 return;
1021
1022 PathDiagnosticLocation L(S, PDB.getSourceManager());
1023
1024 while (!CLocs.empty()) {
1025 const PathDiagnosticLocation &TopContextLoc = CLocs.back();
1026
1027 // Is the top location context the same as the one for the new location?
1028 if (TopContextLoc == L)
1029 return;
1030
1031 if (containsLocation(TopContextLoc, L)) {
Ted Kremenek14856d72009-04-06 23:06:54 +00001032 CLocs.push_back(L);
1033 return;
1034 }
1035
1036 // Context does not contain the location. Flush it.
1037 popLocation();
1038 }
1039
1040 CLocs.push_back(L);
1041}
1042
1043static void GenerateExtensivePathDiagnostic(PathDiagnostic& PD,
1044 PathDiagnosticBuilder &PDB,
1045 const ExplodedNode<GRState> *N) {
1046
1047
1048 EdgeBuilder EB(PD, PDB);
1049
1050 const ExplodedNode<GRState>* NextNode = N->pred_empty()
1051 ? NULL : *(N->pred_begin());
Ted Kremenek14856d72009-04-06 23:06:54 +00001052 while (NextNode) {
1053 N = NextNode;
1054 NextNode = GetPredecessorNode(N);
1055 ProgramPoint P = N->getLocation();
1056
Ted Kremenekdd986cc2009-05-07 00:45:33 +00001057 do {
1058 // Block edges.
1059 if (const BlockEdge *BE = dyn_cast<BlockEdge>(&P)) {
1060 const CFGBlock &Blk = *BE->getSrc();
1061 const Stmt *Term = Blk.getTerminator();
1062
1063 if (Term)
1064 EB.addContext(Term);
Ted Kremenek14856d72009-04-06 23:06:54 +00001065
Ted Kremenekdd986cc2009-05-07 00:45:33 +00001066 // Are we jumping to the head of a loop? Add a special diagnostic.
1067 if (const Stmt *Loop = BE->getSrc()->getLoopTarget()) {
1068
1069 PathDiagnosticLocation L(Loop, PDB.getSourceManager());
1070 PathDiagnosticEventPiece *p =
1071 new PathDiagnosticEventPiece(L,
1072 "Looping back to the head of the loop");
1073
1074 EB.addEdge(p->getLocation(), true);
1075 PD.push_front(p);
1076
1077 if (!Term) {
1078 const CompoundStmt *CS = NULL;
1079 if (const ForStmt *FS = dyn_cast<ForStmt>(Loop))
1080 CS = dyn_cast<CompoundStmt>(FS->getBody());
1081 else if (const WhileStmt *WS = dyn_cast<WhileStmt>(Loop))
1082 CS = dyn_cast<CompoundStmt>(WS->getBody());
1083
1084 if (CS)
1085 EB.rawAddEdge(PathDiagnosticLocation(CS->getRBracLoc(),
1086 PDB.getSourceManager()));
1087 }
Ted Kremenek8bd4d032009-04-28 04:23:15 +00001088 }
Ted Kremenekdd986cc2009-05-07 00:45:33 +00001089
1090 break;
Ted Kremenek14856d72009-04-06 23:06:54 +00001091 }
1092
Ted Kremenekdd986cc2009-05-07 00:45:33 +00001093 if (const BlockEntrance *BE = dyn_cast<BlockEntrance>(&P)) {
1094 if (const Stmt* S = BE->getFirstStmt()) {
1095 if (IsControlFlowExpr(S)) {
1096 // Add the proper context for '&&', '||', and '?'.
1097 EB.addContext(S);
1098 }
1099 else
1100 EB.addExtendedContext(PDB.getEnclosingStmtLocation(S).asStmt());
1101 }
1102
1103 break;
1104 }
1105 } while (0);
1106
1107 if (!NextNode)
Ted Kremenek14856d72009-04-06 23:06:54 +00001108 continue;
Ted Kremenek14856d72009-04-06 23:06:54 +00001109
Ted Kremenek8966bc12009-05-06 21:39:49 +00001110 for (BugReporterContext::visitor_iterator I = PDB.visitor_begin(),
1111 E = PDB.visitor_end(); I!=E; ++I) {
1112 if (PathDiagnosticPiece* p = (*I)->VisitNode(N, NextNode, PDB)) {
1113 const PathDiagnosticLocation &Loc = p->getLocation();
1114 EB.addEdge(Loc, true);
1115 PD.push_front(p);
1116 if (const Stmt *S = Loc.asStmt())
1117 EB.addExtendedContext(PDB.getEnclosingStmtLocation(S).asStmt());
1118 }
1119 }
Ted Kremenek14856d72009-04-06 23:06:54 +00001120 }
1121}
1122
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +00001123//===----------------------------------------------------------------------===//
Ted Kremenekcf118d42009-02-04 23:49:09 +00001124// Methods for BugType and subclasses.
1125//===----------------------------------------------------------------------===//
1126BugType::~BugType() {}
1127void BugType::FlushReports(BugReporter &BR) {}
Ted Kremenekbb77e9b2008-05-01 22:50:36 +00001128
Ted Kremenekcf118d42009-02-04 23:49:09 +00001129//===----------------------------------------------------------------------===//
1130// Methods for BugReport and subclasses.
1131//===----------------------------------------------------------------------===//
1132BugReport::~BugReport() {}
1133RangedBugReport::~RangedBugReport() {}
1134
1135Stmt* BugReport::getStmt(BugReporter& BR) const {
Ted Kremenek200ed922008-05-02 23:21:21 +00001136 ProgramPoint ProgP = EndNode->getLocation();
Ted Kremenekbd7efa82008-04-17 23:44:37 +00001137 Stmt *S = NULL;
1138
Ted Kremenekcf118d42009-02-04 23:49:09 +00001139 if (BlockEntrance* BE = dyn_cast<BlockEntrance>(&ProgP)) {
Ted Kremenekb697b102009-02-23 22:44:26 +00001140 if (BE->getBlock() == &BR.getCFG()->getExit()) S = GetPreviousStmt(EndNode);
Ted Kremenekcf118d42009-02-04 23:49:09 +00001141 }
1142 if (!S) S = GetStmt(ProgP);
1143
Ted Kremenekbb77e9b2008-05-01 22:50:36 +00001144 return S;
1145}
1146
1147PathDiagnosticPiece*
Ted Kremenek8966bc12009-05-06 21:39:49 +00001148BugReport::getEndPath(BugReporterContext& BRC,
Ted Kremenek3148eb42009-01-24 00:55:43 +00001149 const ExplodedNode<GRState>* EndPathNode) {
Ted Kremenekbb77e9b2008-05-01 22:50:36 +00001150
Ted Kremenek8966bc12009-05-06 21:39:49 +00001151 Stmt* S = getStmt(BRC.getBugReporter());
Ted Kremenek61f3e052008-04-03 04:42:52 +00001152
1153 if (!S)
1154 return NULL;
1155
Ted Kremenek8966bc12009-05-06 21:39:49 +00001156 FullSourceLoc L(S->getLocStart(), BRC.getSourceManager());
Ted Kremenek1fbfd5b2009-03-06 23:58:11 +00001157 PathDiagnosticPiece* P = new PathDiagnosticEventPiece(L, getDescription());
Ted Kremenek61f3e052008-04-03 04:42:52 +00001158
Ted Kremenekde7161f2008-04-03 18:00:37 +00001159 const SourceRange *Beg, *End;
Ted Kremenek8966bc12009-05-06 21:39:49 +00001160 getRanges(BRC.getBugReporter(), Beg, End);
Ted Kremenekcf118d42009-02-04 23:49:09 +00001161
Ted Kremenekbb77e9b2008-05-01 22:50:36 +00001162 for (; Beg != End; ++Beg)
1163 P->addRange(*Beg);
Ted Kremenek61f3e052008-04-03 04:42:52 +00001164
1165 return P;
1166}
1167
Ted Kremenekbb77e9b2008-05-01 22:50:36 +00001168void BugReport::getRanges(BugReporter& BR, const SourceRange*& beg,
1169 const SourceRange*& end) {
1170
1171 if (Expr* E = dyn_cast_or_null<Expr>(getStmt(BR))) {
1172 R = E->getSourceRange();
Ted Kremenek9b5e5052009-02-27 20:05:10 +00001173 assert(R.isValid());
Ted Kremenekbb77e9b2008-05-01 22:50:36 +00001174 beg = &R;
1175 end = beg+1;
1176 }
1177 else
1178 beg = end = 0;
Ted Kremenekf1ae7052008-04-03 17:57:38 +00001179}
1180
Ted Kremenekcf118d42009-02-04 23:49:09 +00001181SourceLocation BugReport::getLocation() const {
1182 if (EndNode)
Ted Kremenek9b5e5052009-02-27 20:05:10 +00001183 if (Stmt* S = GetCurrentOrPreviousStmt(EndNode)) {
1184 // For member expressions, return the location of the '.' or '->'.
1185 if (MemberExpr* ME = dyn_cast<MemberExpr>(S))
1186 return ME->getMemberLoc();
1187
Ted Kremenekcf118d42009-02-04 23:49:09 +00001188 return S->getLocStart();
Ted Kremenek9b5e5052009-02-27 20:05:10 +00001189 }
Ted Kremenekcf118d42009-02-04 23:49:09 +00001190
1191 return FullSourceLoc();
Ted Kremenekd2f642b2008-04-14 17:39:48 +00001192}
1193
Ted Kremenek3148eb42009-01-24 00:55:43 +00001194PathDiagnosticPiece* BugReport::VisitNode(const ExplodedNode<GRState>* N,
1195 const ExplodedNode<GRState>* PrevN,
Ted Kremenek8966bc12009-05-06 21:39:49 +00001196 BugReporterContext &BRC) {
Ted Kremenek50a6d0c2008-04-09 21:41:14 +00001197 return NULL;
1198}
1199
Ted Kremenekcf118d42009-02-04 23:49:09 +00001200//===----------------------------------------------------------------------===//
1201// Methods for BugReporter and subclasses.
1202//===----------------------------------------------------------------------===//
1203
1204BugReportEquivClass::~BugReportEquivClass() {
Ted Kremenek8966bc12009-05-06 21:39:49 +00001205 for (iterator I=begin(), E=end(); I!=E; ++I) delete *I;
Ted Kremenekcf118d42009-02-04 23:49:09 +00001206}
1207
1208GRBugReporter::~GRBugReporter() { FlushReports(); }
1209BugReporterData::~BugReporterData() {}
1210
1211ExplodedGraph<GRState>&
1212GRBugReporter::getGraph() { return Eng.getGraph(); }
1213
1214GRStateManager&
1215GRBugReporter::getStateManager() { return Eng.getStateManager(); }
1216
1217BugReporter::~BugReporter() { FlushReports(); }
1218
1219void BugReporter::FlushReports() {
1220 if (BugTypes.isEmpty())
1221 return;
1222
1223 // First flush the warnings for each BugType. This may end up creating new
1224 // warnings and new BugTypes. Because ImmutableSet is a functional data
1225 // structure, we do not need to worry about the iterators being invalidated.
1226 for (BugTypesTy::iterator I=BugTypes.begin(), E=BugTypes.end(); I!=E; ++I)
1227 const_cast<BugType*>(*I)->FlushReports(*this);
1228
1229 // Iterate through BugTypes a second time. BugTypes may have been updated
1230 // with new BugType objects and new warnings.
1231 for (BugTypesTy::iterator I=BugTypes.begin(), E=BugTypes.end(); I!=E; ++I) {
1232 BugType *BT = const_cast<BugType*>(*I);
1233
1234 typedef llvm::FoldingSet<BugReportEquivClass> SetTy;
1235 SetTy& EQClasses = BT->EQClasses;
1236
1237 for (SetTy::iterator EI=EQClasses.begin(), EE=EQClasses.end(); EI!=EE;++EI){
1238 BugReportEquivClass& EQ = *EI;
1239 FlushReport(EQ);
1240 }
Ted Kremeneka43a1eb2008-04-23 23:02:12 +00001241
Ted Kremenekcf118d42009-02-04 23:49:09 +00001242 // Delete the BugType object. This will also delete the equivalence
1243 // classes.
1244 delete BT;
Ted Kremenek94826a72008-04-03 04:59:14 +00001245 }
Ted Kremenekcf118d42009-02-04 23:49:09 +00001246
1247 // Remove all references to the BugType objects.
1248 BugTypes = F.GetEmptySet();
1249}
1250
1251//===----------------------------------------------------------------------===//
1252// PathDiagnostics generation.
1253//===----------------------------------------------------------------------===//
1254
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001255static std::pair<std::pair<ExplodedGraph<GRState>*, NodeBackMap*>,
Ted Kremenekcf118d42009-02-04 23:49:09 +00001256 std::pair<ExplodedNode<GRState>*, unsigned> >
1257MakeReportGraph(const ExplodedGraph<GRState>* G,
1258 const ExplodedNode<GRState>** NStart,
1259 const ExplodedNode<GRState>** NEnd) {
Ted Kremenek94826a72008-04-03 04:59:14 +00001260
Ted Kremenekcf118d42009-02-04 23:49:09 +00001261 // Create the trimmed graph. It will contain the shortest paths from the
1262 // error nodes to the root. In the new graph we should only have one
1263 // error node unless there are two or more error nodes with the same minimum
1264 // path length.
1265 ExplodedGraph<GRState>* GTrim;
1266 InterExplodedGraphMap<GRState>* NMap;
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001267
1268 llvm::DenseMap<const void*, const void*> InverseMap;
1269 llvm::tie(GTrim, NMap) = G->Trim(NStart, NEnd, &InverseMap);
Ted Kremenekcf118d42009-02-04 23:49:09 +00001270
1271 // Create owning pointers for GTrim and NMap just to ensure that they are
1272 // released when this function exists.
1273 llvm::OwningPtr<ExplodedGraph<GRState> > AutoReleaseGTrim(GTrim);
1274 llvm::OwningPtr<InterExplodedGraphMap<GRState> > AutoReleaseNMap(NMap);
1275
1276 // Find the (first) error node in the trimmed graph. We just need to consult
1277 // the node map (NMap) which maps from nodes in the original graph to nodes
1278 // in the new graph.
1279 const ExplodedNode<GRState>* N = 0;
1280 unsigned NodeIndex = 0;
1281
1282 for (const ExplodedNode<GRState>** I = NStart; I != NEnd; ++I)
1283 if ((N = NMap->getMappedNode(*I))) {
1284 NodeIndex = (I - NStart) / sizeof(*I);
1285 break;
1286 }
1287
1288 assert(N && "No error node found in the trimmed graph.");
1289
1290 // Create a new (third!) graph with a single path. This is the graph
1291 // that will be returned to the caller.
Ted Kremenek3148eb42009-01-24 00:55:43 +00001292 ExplodedGraph<GRState> *GNew =
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001293 new ExplodedGraph<GRState>(GTrim->getCFG(), GTrim->getCodeDecl(),
1294 GTrim->getContext());
Ted Kremenekcf118d42009-02-04 23:49:09 +00001295
Ted Kremenek10aa5542009-03-12 23:41:59 +00001296 // Sometimes the trimmed graph can contain a cycle. Perform a reverse BFS
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001297 // to the root node, and then construct a new graph that contains only
1298 // a single path.
Ted Kremenek3148eb42009-01-24 00:55:43 +00001299 llvm::DenseMap<const void*,unsigned> Visited;
Ted Kremenek10aa5542009-03-12 23:41:59 +00001300 std::queue<const ExplodedNode<GRState>*> WS;
1301 WS.push(N);
1302
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001303 unsigned cnt = 0;
Ted Kremenek3148eb42009-01-24 00:55:43 +00001304 const ExplodedNode<GRState>* Root = 0;
Ted Kremenekc1da4412008-06-17 19:14:06 +00001305
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001306 while (!WS.empty()) {
Ted Kremenek10aa5542009-03-12 23:41:59 +00001307 const ExplodedNode<GRState>* Node = WS.front();
1308 WS.pop();
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001309
1310 if (Visited.find(Node) != Visited.end())
1311 continue;
1312
1313 Visited[Node] = cnt++;
1314
1315 if (Node->pred_empty()) {
1316 Root = Node;
1317 break;
1318 }
1319
Ted Kremenek3148eb42009-01-24 00:55:43 +00001320 for (ExplodedNode<GRState>::const_pred_iterator I=Node->pred_begin(),
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001321 E=Node->pred_end(); I!=E; ++I)
Ted Kremenek10aa5542009-03-12 23:41:59 +00001322 WS.push(*I);
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001323 }
Ted Kremenekcf118d42009-02-04 23:49:09 +00001324
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001325 assert (Root);
1326
Ted Kremenek10aa5542009-03-12 23:41:59 +00001327 // Now walk from the root down the BFS path, always taking the successor
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001328 // with the lowest number.
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001329 ExplodedNode<GRState> *Last = 0, *First = 0;
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001330 NodeBackMap *BM = new NodeBackMap();
Ted Kremenekcf118d42009-02-04 23:49:09 +00001331
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001332 for ( N = Root ;;) {
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001333 // Lookup the number associated with the current node.
Ted Kremenek3148eb42009-01-24 00:55:43 +00001334 llvm::DenseMap<const void*,unsigned>::iterator I = Visited.find(N);
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001335 assert (I != Visited.end());
1336
1337 // Create the equivalent node in the new graph with the same state
1338 // and location.
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001339 ExplodedNode<GRState>* NewN =
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001340 GNew->getNode(N->getLocation(), N->getState());
1341
1342 // Store the mapping to the original node.
1343 llvm::DenseMap<const void*, const void*>::iterator IMitr=InverseMap.find(N);
1344 assert(IMitr != InverseMap.end() && "No mapping to original node.");
1345 (*BM)[NewN] = (const ExplodedNode<GRState>*) IMitr->second;
Ted Kremenekcf118d42009-02-04 23:49:09 +00001346
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001347 // Link up the new node with the previous node.
1348 if (Last)
1349 NewN->addPredecessor(Last);
Ted Kremeneka43a1eb2008-04-23 23:02:12 +00001350
1351 Last = NewN;
Ted Kremenekcf118d42009-02-04 23:49:09 +00001352
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001353 // Are we at the final node?
1354 if (I->second == 0) {
1355 First = NewN;
Ted Kremenekc1da4412008-06-17 19:14:06 +00001356 break;
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001357 }
Ted Kremenekcf118d42009-02-04 23:49:09 +00001358
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001359 // Find the next successor node. We choose the node that is marked
1360 // with the lowest DFS number.
Ted Kremenek3148eb42009-01-24 00:55:43 +00001361 ExplodedNode<GRState>::const_succ_iterator SI = N->succ_begin();
1362 ExplodedNode<GRState>::const_succ_iterator SE = N->succ_end();
Ted Kremenekc1da4412008-06-17 19:14:06 +00001363 N = 0;
1364
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001365 for (unsigned MinVal = 0; SI != SE; ++SI) {
Ted Kremenekcf118d42009-02-04 23:49:09 +00001366
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001367 I = Visited.find(*SI);
1368
1369 if (I == Visited.end())
1370 continue;
1371
1372 if (!N || I->second < MinVal) {
1373 N = *SI;
1374 MinVal = I->second;
Ted Kremenekc1da4412008-06-17 19:14:06 +00001375 }
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001376 }
Ted Kremenekcf118d42009-02-04 23:49:09 +00001377
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001378 assert (N);
Ted Kremeneka43a1eb2008-04-23 23:02:12 +00001379 }
Ted Kremenekcf118d42009-02-04 23:49:09 +00001380
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001381 assert (First);
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001382 return std::make_pair(std::make_pair(GNew, BM),
1383 std::make_pair(First, NodeIndex));
Ted Kremeneka43a1eb2008-04-23 23:02:12 +00001384}
1385
Ted Kremenek0e5c8d42009-03-10 05:16:17 +00001386/// CompactPathDiagnostic - This function postprocesses a PathDiagnostic object
1387/// and collapses PathDiagosticPieces that are expanded by macros.
1388static void CompactPathDiagnostic(PathDiagnostic &PD, const SourceManager& SM) {
1389 typedef std::vector<std::pair<PathDiagnosticMacroPiece*, SourceLocation> >
1390 MacroStackTy;
1391
1392 typedef std::vector<PathDiagnosticPiece*>
1393 PiecesTy;
1394
1395 MacroStackTy MacroStack;
1396 PiecesTy Pieces;
1397
1398 for (PathDiagnostic::iterator I = PD.begin(), E = PD.end(); I!=E; ++I) {
1399 // Get the location of the PathDiagnosticPiece.
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +00001400 const FullSourceLoc Loc = I->getLocation().asLocation();
Ted Kremenek0e5c8d42009-03-10 05:16:17 +00001401
1402 // Determine the instantiation location, which is the location we group
1403 // related PathDiagnosticPieces.
1404 SourceLocation InstantiationLoc = Loc.isMacroID() ?
1405 SM.getInstantiationLoc(Loc) :
1406 SourceLocation();
1407
1408 if (Loc.isFileID()) {
1409 MacroStack.clear();
1410 Pieces.push_back(&*I);
1411 continue;
1412 }
1413
1414 assert(Loc.isMacroID());
1415
1416 // Is the PathDiagnosticPiece within the same macro group?
1417 if (!MacroStack.empty() && InstantiationLoc == MacroStack.back().second) {
1418 MacroStack.back().first->push_back(&*I);
1419 continue;
1420 }
1421
1422 // We aren't in the same group. Are we descending into a new macro
1423 // or are part of an old one?
1424 PathDiagnosticMacroPiece *MacroGroup = 0;
1425
1426 SourceLocation ParentInstantiationLoc = InstantiationLoc.isMacroID() ?
1427 SM.getInstantiationLoc(Loc) :
1428 SourceLocation();
1429
1430 // Walk the entire macro stack.
1431 while (!MacroStack.empty()) {
1432 if (InstantiationLoc == MacroStack.back().second) {
1433 MacroGroup = MacroStack.back().first;
1434 break;
1435 }
1436
1437 if (ParentInstantiationLoc == MacroStack.back().second) {
1438 MacroGroup = MacroStack.back().first;
1439 break;
1440 }
1441
1442 MacroStack.pop_back();
1443 }
1444
1445 if (!MacroGroup || ParentInstantiationLoc == MacroStack.back().second) {
1446 // Create a new macro group and add it to the stack.
1447 PathDiagnosticMacroPiece *NewGroup = new PathDiagnosticMacroPiece(Loc);
1448
1449 if (MacroGroup)
1450 MacroGroup->push_back(NewGroup);
1451 else {
1452 assert(InstantiationLoc.isFileID());
1453 Pieces.push_back(NewGroup);
1454 }
1455
1456 MacroGroup = NewGroup;
1457 MacroStack.push_back(std::make_pair(MacroGroup, InstantiationLoc));
1458 }
1459
1460 // Finally, add the PathDiagnosticPiece to the group.
1461 MacroGroup->push_back(&*I);
1462 }
1463
1464 // Now take the pieces and construct a new PathDiagnostic.
1465 PD.resetPath(false);
1466
1467 for (PiecesTy::iterator I=Pieces.begin(), E=Pieces.end(); I!=E; ++I) {
1468 if (PathDiagnosticMacroPiece *MP=dyn_cast<PathDiagnosticMacroPiece>(*I))
1469 if (!MP->containsEvent()) {
1470 delete MP;
1471 continue;
1472 }
1473
1474 PD.push_back(*I);
1475 }
1476}
1477
Ted Kremenek7dc86642009-03-31 20:22:36 +00001478void GRBugReporter::GeneratePathDiagnostic(PathDiagnostic& PD,
Ted Kremenek8966bc12009-05-06 21:39:49 +00001479 BugReportEquivClass& EQ) {
Ted Kremenek7dc86642009-03-31 20:22:36 +00001480
1481 std::vector<const ExplodedNode<GRState>*> Nodes;
1482
Ted Kremenekcf118d42009-02-04 23:49:09 +00001483 for (BugReportEquivClass::iterator I=EQ.begin(), E=EQ.end(); I!=E; ++I) {
1484 const ExplodedNode<GRState>* N = I->getEndNode();
1485 if (N) Nodes.push_back(N);
1486 }
1487
1488 if (Nodes.empty())
1489 return;
Ted Kremeneka43a1eb2008-04-23 23:02:12 +00001490
1491 // Construct a new graph that contains only a single path from the error
Ted Kremenekcf118d42009-02-04 23:49:09 +00001492 // node to a root.
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001493 const std::pair<std::pair<ExplodedGraph<GRState>*, NodeBackMap*>,
Ted Kremenek7dc86642009-03-31 20:22:36 +00001494 std::pair<ExplodedNode<GRState>*, unsigned> >&
1495 GPair = MakeReportGraph(&getGraph(), &Nodes[0], &Nodes[0] + Nodes.size());
Ted Kremeneka43a1eb2008-04-23 23:02:12 +00001496
Ted Kremenekcf118d42009-02-04 23:49:09 +00001497 // Find the BugReport with the original location.
1498 BugReport *R = 0;
1499 unsigned i = 0;
1500 for (BugReportEquivClass::iterator I=EQ.begin(), E=EQ.end(); I!=E; ++I, ++i)
1501 if (i == GPair.second.second) { R = *I; break; }
1502
1503 assert(R && "No original report found for sliced graph.");
Ted Kremeneka43a1eb2008-04-23 23:02:12 +00001504
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001505 llvm::OwningPtr<ExplodedGraph<GRState> > ReportGraph(GPair.first.first);
1506 llvm::OwningPtr<NodeBackMap> BackMap(GPair.first.second);
Ted Kremenekcf118d42009-02-04 23:49:09 +00001507 const ExplodedNode<GRState> *N = GPair.second.first;
Ted Kremenek7dc86642009-03-31 20:22:36 +00001508
Ted Kremenek8966bc12009-05-06 21:39:49 +00001509 // Start building the path diagnostic...
1510 PathDiagnosticBuilder PDB(*this, R, BackMap.get(), getPathDiagnosticClient());
1511
1512 if (PathDiagnosticPiece* Piece = R->getEndPath(PDB, N))
Ted Kremenekbd7efa82008-04-17 23:44:37 +00001513 PD.push_back(Piece);
1514 else
1515 return;
Ted Kremenekdd986cc2009-05-07 00:45:33 +00001516
1517 R->registerInitialVisitors(PDB, N);
Ted Kremenekbd7efa82008-04-17 23:44:37 +00001518
Ted Kremenek7dc86642009-03-31 20:22:36 +00001519 switch (PDB.getGenerationScheme()) {
1520 case PathDiagnosticClient::Extensive:
Ted Kremenek8966bc12009-05-06 21:39:49 +00001521 GenerateExtensivePathDiagnostic(PD, PDB, N);
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +00001522 break;
Ted Kremenek7dc86642009-03-31 20:22:36 +00001523 case PathDiagnosticClient::Minimal:
1524 GenerateMinimalPathDiagnostic(PD, PDB, N);
1525 break;
1526 }
Ted Kremenek7dc86642009-03-31 20:22:36 +00001527}
1528
Ted Kremenekcf118d42009-02-04 23:49:09 +00001529void BugReporter::Register(BugType *BT) {
1530 BugTypes = F.Add(BugTypes, BT);
Ted Kremenek76d90c82008-05-16 18:33:14 +00001531}
1532
Ted Kremenekcf118d42009-02-04 23:49:09 +00001533void BugReporter::EmitReport(BugReport* R) {
1534 // Compute the bug report's hash to determine its equivalence class.
1535 llvm::FoldingSetNodeID ID;
1536 R->Profile(ID);
Ted Kremenek61f3e052008-04-03 04:42:52 +00001537
Ted Kremenekcf118d42009-02-04 23:49:09 +00001538 // Lookup the equivance class. If there isn't one, create it.
1539 BugType& BT = R->getBugType();
1540 Register(&BT);
1541 void *InsertPos;
1542 BugReportEquivClass* EQ = BT.EQClasses.FindNodeOrInsertPos(ID, InsertPos);
1543
1544 if (!EQ) {
1545 EQ = new BugReportEquivClass(R);
1546 BT.EQClasses.InsertNode(EQ, InsertPos);
1547 }
1548 else
1549 EQ->AddReport(R);
Ted Kremenek61f3e052008-04-03 04:42:52 +00001550}
1551
Ted Kremenekcf118d42009-02-04 23:49:09 +00001552void BugReporter::FlushReport(BugReportEquivClass& EQ) {
1553 assert(!EQ.Reports.empty());
1554 BugReport &R = **EQ.begin();
Ted Kremenekd49967f2009-04-29 21:58:13 +00001555 PathDiagnosticClient* PD = getPathDiagnosticClient();
Ted Kremenekcf118d42009-02-04 23:49:09 +00001556
1557 // FIXME: Make sure we use the 'R' for the path that was actually used.
1558 // Probably doesn't make a difference in practice.
1559 BugType& BT = R.getBugType();
1560
Ted Kremenekd49967f2009-04-29 21:58:13 +00001561 llvm::OwningPtr<PathDiagnostic>
1562 D(new PathDiagnostic(R.getBugType().getName(),
Ted Kremenekda0e8422009-04-29 22:05:03 +00001563 !PD || PD->useVerboseDescription()
Ted Kremenekd49967f2009-04-29 21:58:13 +00001564 ? R.getDescription() : R.getShortDescription(),
1565 BT.getCategory()));
1566
Ted Kremenekcf118d42009-02-04 23:49:09 +00001567 GeneratePathDiagnostic(*D.get(), EQ);
Ted Kremenek072192b2008-04-30 23:47:44 +00001568
1569 // Get the meta data.
Ted Kremenek072192b2008-04-30 23:47:44 +00001570 std::pair<const char**, const char**> Meta = R.getExtraDescriptiveText();
Ted Kremenek3148eb42009-01-24 00:55:43 +00001571 for (const char** s = Meta.first; s != Meta.second; ++s) D->addMeta(*s);
Ted Kremenek75840e12008-04-18 01:56:37 +00001572
Ted Kremenek3148eb42009-01-24 00:55:43 +00001573 // Emit a summary diagnostic to the regular Diagnostics engine.
Ted Kremenek3148eb42009-01-24 00:55:43 +00001574 const SourceRange *Beg = 0, *End = 0;
1575 R.getRanges(*this, Beg, End);
1576 Diagnostic& Diag = getDiagnostic();
Ted Kremenekcf118d42009-02-04 23:49:09 +00001577 FullSourceLoc L(R.getLocation(), getSourceManager());
Ted Kremenekd90e7082009-02-07 22:36:41 +00001578 unsigned ErrorDiag = Diag.getCustomDiagID(Diagnostic::Warning,
1579 R.getDescription().c_str());
Ted Kremenek57202072008-07-14 17:40:50 +00001580
Ted Kremenek3148eb42009-01-24 00:55:43 +00001581 switch (End-Beg) {
Chris Lattner0a14eee2008-11-18 07:04:44 +00001582 default: assert(0 && "Don't handle this many ranges yet!");
1583 case 0: Diag.Report(L, ErrorDiag); break;
1584 case 1: Diag.Report(L, ErrorDiag) << Beg[0]; break;
1585 case 2: Diag.Report(L, ErrorDiag) << Beg[0] << Beg[1]; break;
1586 case 3: Diag.Report(L, ErrorDiag) << Beg[0] << Beg[1] << Beg[2]; break;
Ted Kremenek2f0e89e2008-04-18 22:56:53 +00001587 }
Ted Kremenek3148eb42009-01-24 00:55:43 +00001588
1589 // Emit a full diagnostic for the path if we have a PathDiagnosticClient.
1590 if (!PD)
1591 return;
1592
1593 if (D->empty()) {
Ted Kremenek1fbfd5b2009-03-06 23:58:11 +00001594 PathDiagnosticPiece* piece =
1595 new PathDiagnosticEventPiece(L, R.getDescription());
1596
Ted Kremenek3148eb42009-01-24 00:55:43 +00001597 for ( ; Beg != End; ++Beg) piece->addRange(*Beg);
1598 D->push_back(piece);
1599 }
1600
1601 PD->HandlePathDiagnostic(D.take());
Ted Kremenek61f3e052008-04-03 04:42:52 +00001602}
Ted Kremenek57202072008-07-14 17:40:50 +00001603
Ted Kremenek8c036c72008-09-20 04:23:38 +00001604void BugReporter::EmitBasicReport(const char* name, const char* str,
1605 SourceLocation Loc,
1606 SourceRange* RBeg, unsigned NumRanges) {
1607 EmitBasicReport(name, "", str, Loc, RBeg, NumRanges);
1608}
Ted Kremenekcf118d42009-02-04 23:49:09 +00001609
Ted Kremenek8c036c72008-09-20 04:23:38 +00001610void BugReporter::EmitBasicReport(const char* name, const char* category,
1611 const char* str, SourceLocation Loc,
1612 SourceRange* RBeg, unsigned NumRanges) {
1613
Ted Kremenekcf118d42009-02-04 23:49:09 +00001614 // 'BT' will be owned by BugReporter as soon as we call 'EmitReport'.
1615 BugType *BT = new BugType(name, category);
Chris Lattner0a14eee2008-11-18 07:04:44 +00001616 FullSourceLoc L = getContext().getFullLoc(Loc);
Ted Kremenekcf118d42009-02-04 23:49:09 +00001617 RangedBugReport *R = new DiagBugReport(*BT, str, L);
1618 for ( ; NumRanges > 0 ; --NumRanges, ++RBeg) R->addRange(*RBeg);
1619 EmitReport(R);
Ted Kremenek57202072008-07-14 17:40:50 +00001620}