blob: dcc88febec9f6a4407c93b1238b44f541d7b2bb4 [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:
Ted Kremenekaf3e3d52009-03-28 03:37:59 +0000252 return PathDiagnosticLocation(S, SMgr);
Ted Kremenekaf3e3d52009-03-28 03:37:59 +0000253 case Stmt::ForStmtClass:
254 if (cast<ForStmt>(Parent)->getBody() == S)
255 return PathDiagnosticLocation(S, SMgr);
256 break;
257 case Stmt::IfStmtClass:
258 if (cast<IfStmt>(Parent)->getCond() != S)
259 return PathDiagnosticLocation(S, SMgr);
Ted Kremenek8bd4d032009-04-28 04:23:15 +0000260 break;
Ted Kremenekaf3e3d52009-03-28 03:37:59 +0000261 case Stmt::ObjCForCollectionStmtClass:
262 if (cast<ObjCForCollectionStmt>(Parent)->getBody() == S)
263 return PathDiagnosticLocation(S, SMgr);
264 break;
265 case Stmt::WhileStmtClass:
266 if (cast<WhileStmt>(Parent)->getCond() != S)
267 return PathDiagnosticLocation(S, SMgr);
268 break;
269 default:
270 break;
271 }
272
Ted Kremenekd8c938b2009-03-27 21:16:25 +0000273 S = Parent;
274 }
275
276 assert(S && "Cannot have null Stmt for PathDiagnosticLocation");
277 return PathDiagnosticLocation(S, SMgr);
278}
279
Ted Kremenekcf118d42009-02-04 23:49:09 +0000280//===----------------------------------------------------------------------===//
Ted Kremenek31061982009-03-31 23:00:32 +0000281// ScanNotableSymbols: closure-like callback for scanning Store bindings.
282//===----------------------------------------------------------------------===//
283
284static const VarDecl*
285GetMostRecentVarDeclBinding(const ExplodedNode<GRState>* N,
286 GRStateManager& VMgr, SVal X) {
287
288 for ( ; N ; N = N->pred_empty() ? 0 : *N->pred_begin()) {
289
290 ProgramPoint P = N->getLocation();
291
292 if (!isa<PostStmt>(P))
293 continue;
294
295 DeclRefExpr* DR = dyn_cast<DeclRefExpr>(cast<PostStmt>(P).getStmt());
296
297 if (!DR)
298 continue;
299
300 SVal Y = VMgr.GetSVal(N->getState(), DR);
301
302 if (X != Y)
303 continue;
304
305 VarDecl* VD = dyn_cast<VarDecl>(DR->getDecl());
306
307 if (!VD)
308 continue;
309
310 return VD;
311 }
312
313 return 0;
314}
315
316namespace {
317class VISIBILITY_HIDDEN NotableSymbolHandler
318: public StoreManager::BindingsHandler {
319
320 SymbolRef Sym;
321 const GRState* PrevSt;
322 const Stmt* S;
323 GRStateManager& VMgr;
324 const ExplodedNode<GRState>* Pred;
325 PathDiagnostic& PD;
326 BugReporter& BR;
327
328public:
329
330 NotableSymbolHandler(SymbolRef sym, const GRState* prevst, const Stmt* s,
331 GRStateManager& vmgr, const ExplodedNode<GRState>* pred,
332 PathDiagnostic& pd, BugReporter& br)
333 : Sym(sym), PrevSt(prevst), S(s), VMgr(vmgr), Pred(pred), PD(pd), BR(br) {}
334
335 bool HandleBinding(StoreManager& SMgr, Store store, const MemRegion* R,
336 SVal V) {
337
338 SymbolRef ScanSym = V.getAsSymbol();
339
340 if (ScanSym != Sym)
341 return true;
342
343 // Check if the previous state has this binding.
344 SVal X = VMgr.GetSVal(PrevSt, loc::MemRegionVal(R));
345
346 if (X == V) // Same binding?
347 return true;
348
349 // Different binding. Only handle assignments for now. We don't pull
350 // this check out of the loop because we will eventually handle other
351 // cases.
352
353 VarDecl *VD = 0;
354
355 if (const BinaryOperator* B = dyn_cast<BinaryOperator>(S)) {
356 if (!B->isAssignmentOp())
357 return true;
358
359 // What variable did we assign to?
360 DeclRefExpr* DR = dyn_cast<DeclRefExpr>(B->getLHS()->IgnoreParenCasts());
361
362 if (!DR)
363 return true;
364
365 VD = dyn_cast<VarDecl>(DR->getDecl());
366 }
367 else if (const DeclStmt* DS = dyn_cast<DeclStmt>(S)) {
368 // FIXME: Eventually CFGs won't have DeclStmts. Right now we
369 // assume that each DeclStmt has a single Decl. This invariant
370 // holds by contruction in the CFG.
371 VD = dyn_cast<VarDecl>(*DS->decl_begin());
372 }
373
374 if (!VD)
375 return true;
376
377 // What is the most recently referenced variable with this binding?
378 const VarDecl* MostRecent = GetMostRecentVarDeclBinding(Pred, VMgr, V);
379
380 if (!MostRecent)
381 return true;
382
383 // Create the diagnostic.
384 FullSourceLoc L(S->getLocStart(), BR.getSourceManager());
385
386 if (Loc::IsLocType(VD->getType())) {
387 std::string msg = "'" + std::string(VD->getNameAsString()) +
388 "' now aliases '" + MostRecent->getNameAsString() + "'";
389
390 PD.push_front(new PathDiagnosticEventPiece(L, msg));
391 }
392
393 return true;
394 }
395};
396}
397
398static void HandleNotableSymbol(const ExplodedNode<GRState>* N,
399 const Stmt* S,
400 SymbolRef Sym, BugReporter& BR,
401 PathDiagnostic& PD) {
402
403 const ExplodedNode<GRState>* Pred = N->pred_empty() ? 0 : *N->pred_begin();
404 const GRState* PrevSt = Pred ? Pred->getState() : 0;
405
406 if (!PrevSt)
407 return;
408
409 // Look at the region bindings of the current state that map to the
410 // specified symbol. Are any of them not in the previous state?
411 GRStateManager& VMgr = cast<GRBugReporter>(BR).getStateManager();
412 NotableSymbolHandler H(Sym, PrevSt, S, VMgr, Pred, PD, BR);
413 cast<GRBugReporter>(BR).getStateManager().iterBindings(N->getState(), H);
414}
415
416namespace {
417class VISIBILITY_HIDDEN ScanNotableSymbols
418: public StoreManager::BindingsHandler {
419
420 llvm::SmallSet<SymbolRef, 10> AlreadyProcessed;
421 const ExplodedNode<GRState>* N;
422 Stmt* S;
423 GRBugReporter& BR;
424 PathDiagnostic& PD;
425
426public:
427 ScanNotableSymbols(const ExplodedNode<GRState>* n, Stmt* s, GRBugReporter& br,
428 PathDiagnostic& pd)
429 : N(n), S(s), BR(br), PD(pd) {}
430
431 bool HandleBinding(StoreManager& SMgr, Store store,
432 const MemRegion* R, SVal V) {
433
434 SymbolRef ScanSym = V.getAsSymbol();
435
436 if (!ScanSym)
437 return true;
438
439 if (!BR.isNotable(ScanSym))
440 return true;
441
442 if (AlreadyProcessed.count(ScanSym))
443 return true;
444
445 AlreadyProcessed.insert(ScanSym);
446
447 HandleNotableSymbol(N, S, ScanSym, BR, PD);
448 return true;
449 }
450};
451} // end anonymous namespace
452
453//===----------------------------------------------------------------------===//
454// "Minimal" path diagnostic generation algorithm.
455//===----------------------------------------------------------------------===//
456
Ted Kremenek14856d72009-04-06 23:06:54 +0000457static void CompactPathDiagnostic(PathDiagnostic &PD, const SourceManager& SM);
458
Ted Kremenek31061982009-03-31 23:00:32 +0000459static void GenerateMinimalPathDiagnostic(PathDiagnostic& PD,
460 PathDiagnosticBuilder &PDB,
461 const ExplodedNode<GRState> *N) {
462 ASTContext& Ctx = PDB.getContext();
463 SourceManager& SMgr = PDB.getSourceManager();
464 const ExplodedNode<GRState>* NextNode = N->pred_empty()
465 ? NULL : *(N->pred_begin());
466 while (NextNode) {
467 N = NextNode;
468 NextNode = GetPredecessorNode(N);
469
470 ProgramPoint P = N->getLocation();
471
472 if (const BlockEdge* BE = dyn_cast<BlockEdge>(&P)) {
473 CFGBlock* Src = BE->getSrc();
474 CFGBlock* Dst = BE->getDst();
475 Stmt* T = Src->getTerminator();
476
477 if (!T)
478 continue;
479
480 FullSourceLoc Start(T->getLocStart(), SMgr);
481
482 switch (T->getStmtClass()) {
483 default:
484 break;
485
486 case Stmt::GotoStmtClass:
487 case Stmt::IndirectGotoStmtClass: {
488 Stmt* S = GetNextStmt(N);
489
490 if (!S)
491 continue;
492
493 std::string sbuf;
494 llvm::raw_string_ostream os(sbuf);
495 const PathDiagnosticLocation &End = PDB.getEnclosingStmtLocation(S);
496
497 os << "Control jumps to line "
498 << End.asLocation().getInstantiationLineNumber();
499 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
500 os.str()));
501 break;
502 }
503
504 case Stmt::SwitchStmtClass: {
505 // Figure out what case arm we took.
506 std::string sbuf;
507 llvm::raw_string_ostream os(sbuf);
508
509 if (Stmt* S = Dst->getLabel()) {
510 PathDiagnosticLocation End(S, SMgr);
511
512 switch (S->getStmtClass()) {
513 default:
514 os << "No cases match in the switch statement. "
515 "Control jumps to line "
516 << End.asLocation().getInstantiationLineNumber();
517 break;
518 case Stmt::DefaultStmtClass:
519 os << "Control jumps to the 'default' case at line "
520 << End.asLocation().getInstantiationLineNumber();
521 break;
522
523 case Stmt::CaseStmtClass: {
524 os << "Control jumps to 'case ";
525 CaseStmt* Case = cast<CaseStmt>(S);
526 Expr* LHS = Case->getLHS()->IgnoreParenCasts();
527
528 // Determine if it is an enum.
529 bool GetRawInt = true;
530
531 if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(LHS)) {
532 // FIXME: Maybe this should be an assertion. Are there cases
533 // were it is not an EnumConstantDecl?
534 EnumConstantDecl* D =
535 dyn_cast<EnumConstantDecl>(DR->getDecl());
536
537 if (D) {
538 GetRawInt = false;
539 os << D->getNameAsString();
540 }
541 }
Eli Friedman9ec64d62009-04-26 19:04:51 +0000542
543 if (GetRawInt)
544 os << LHS->EvaluateAsInt(Ctx);
545
Ted Kremenek31061982009-03-31 23:00:32 +0000546 os << ":' at line "
547 << End.asLocation().getInstantiationLineNumber();
548 break;
549 }
550 }
551 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
552 os.str()));
553 }
554 else {
555 os << "'Default' branch taken. ";
556 const PathDiagnosticLocation &End = PDB.ExecutionContinues(os, N);
557 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
558 os.str()));
559 }
560
561 break;
562 }
563
564 case Stmt::BreakStmtClass:
565 case Stmt::ContinueStmtClass: {
566 std::string sbuf;
567 llvm::raw_string_ostream os(sbuf);
568 PathDiagnosticLocation End = PDB.ExecutionContinues(os, N);
569 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
570 os.str()));
571 break;
572 }
573
574 // Determine control-flow for ternary '?'.
575 case Stmt::ConditionalOperatorClass: {
576 std::string sbuf;
577 llvm::raw_string_ostream os(sbuf);
578 os << "'?' condition is ";
579
580 if (*(Src->succ_begin()+1) == Dst)
581 os << "false";
582 else
583 os << "true";
584
585 PathDiagnosticLocation End = PDB.ExecutionContinues(N);
586
587 if (const Stmt *S = End.asStmt())
588 End = PDB.getEnclosingStmtLocation(S);
589
590 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
591 os.str()));
592 break;
593 }
594
595 // Determine control-flow for short-circuited '&&' and '||'.
596 case Stmt::BinaryOperatorClass: {
597 if (!PDB.supportsLogicalOpControlFlow())
598 break;
599
600 BinaryOperator *B = cast<BinaryOperator>(T);
601 std::string sbuf;
602 llvm::raw_string_ostream os(sbuf);
603 os << "Left side of '";
604
605 if (B->getOpcode() == BinaryOperator::LAnd) {
606 os << "&&" << "' is ";
607
608 if (*(Src->succ_begin()+1) == Dst) {
609 os << "false";
610 PathDiagnosticLocation End(B->getLHS(), SMgr);
611 PathDiagnosticLocation Start(B->getOperatorLoc(), SMgr);
612 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
613 os.str()));
614 }
615 else {
616 os << "true";
617 PathDiagnosticLocation Start(B->getLHS(), SMgr);
618 PathDiagnosticLocation End = PDB.ExecutionContinues(N);
619 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
620 os.str()));
621 }
622 }
623 else {
624 assert(B->getOpcode() == BinaryOperator::LOr);
625 os << "||" << "' is ";
626
627 if (*(Src->succ_begin()+1) == Dst) {
628 os << "false";
629 PathDiagnosticLocation Start(B->getLHS(), SMgr);
630 PathDiagnosticLocation End = PDB.ExecutionContinues(N);
631 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
632 os.str()));
633 }
634 else {
635 os << "true";
636 PathDiagnosticLocation End(B->getLHS(), SMgr);
637 PathDiagnosticLocation Start(B->getOperatorLoc(), SMgr);
638 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
639 os.str()));
640 }
641 }
642
643 break;
644 }
645
646 case Stmt::DoStmtClass: {
647 if (*(Src->succ_begin()) == Dst) {
648 std::string sbuf;
649 llvm::raw_string_ostream os(sbuf);
650
651 os << "Loop condition is true. ";
652 PathDiagnosticLocation End = PDB.ExecutionContinues(os, N);
653
654 if (const Stmt *S = End.asStmt())
655 End = PDB.getEnclosingStmtLocation(S);
656
657 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
658 os.str()));
659 }
660 else {
661 PathDiagnosticLocation End = PDB.ExecutionContinues(N);
662
663 if (const Stmt *S = End.asStmt())
664 End = PDB.getEnclosingStmtLocation(S);
665
666 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
667 "Loop condition is false. Exiting loop"));
668 }
669
670 break;
671 }
672
673 case Stmt::WhileStmtClass:
674 case Stmt::ForStmtClass: {
675 if (*(Src->succ_begin()+1) == Dst) {
676 std::string sbuf;
677 llvm::raw_string_ostream os(sbuf);
678
679 os << "Loop condition is false. ";
680 PathDiagnosticLocation End = PDB.ExecutionContinues(os, N);
681 if (const Stmt *S = End.asStmt())
682 End = PDB.getEnclosingStmtLocation(S);
683
684 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
685 os.str()));
686 }
687 else {
688 PathDiagnosticLocation End = PDB.ExecutionContinues(N);
689 if (const Stmt *S = End.asStmt())
690 End = PDB.getEnclosingStmtLocation(S);
691
692 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000693 "Loop condition is true. Entering loop body"));
Ted Kremenek31061982009-03-31 23:00:32 +0000694 }
695
696 break;
697 }
698
699 case Stmt::IfStmtClass: {
700 PathDiagnosticLocation End = PDB.ExecutionContinues(N);
701
702 if (const Stmt *S = End.asStmt())
703 End = PDB.getEnclosingStmtLocation(S);
704
705 if (*(Src->succ_begin()+1) == Dst)
706 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000707 "Taking false branch"));
Ted Kremenek31061982009-03-31 23:00:32 +0000708 else
709 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000710 "Taking true branch"));
Ted Kremenek31061982009-03-31 23:00:32 +0000711
712 break;
713 }
714 }
715 }
716
717 if (PathDiagnosticPiece* p =
718 PDB.getReport().VisitNode(N, NextNode, PDB.getGraph(),
719 PDB.getBugReporter(),
720 PDB.getNodeMapClosure())) {
721 PD.push_front(p);
722 }
723
724 if (const PostStmt* PS = dyn_cast<PostStmt>(&P)) {
725 // Scan the region bindings, and see if a "notable" symbol has a new
726 // lval binding.
727 ScanNotableSymbols SNS(N, PS->getStmt(), PDB.getBugReporter(), PD);
728 PDB.getStateManager().iterBindings(N->getState(), SNS);
729 }
730 }
Ted Kremenek14856d72009-04-06 23:06:54 +0000731
732 // After constructing the full PathDiagnostic, do a pass over it to compact
733 // PathDiagnosticPieces that occur within a macro.
734 CompactPathDiagnostic(PD, PDB.getSourceManager());
Ted Kremenek31061982009-03-31 23:00:32 +0000735}
736
737//===----------------------------------------------------------------------===//
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000738// "Extensive" PathDiagnostic generation.
739//===----------------------------------------------------------------------===//
740
741static bool IsControlFlowExpr(const Stmt *S) {
742 const Expr *E = dyn_cast<Expr>(S);
Ted Kremenek14856d72009-04-06 23:06:54 +0000743
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000744 if (!E)
745 return false;
746
747 E = E->IgnoreParenCasts();
748
749 if (isa<ConditionalOperator>(E))
750 return true;
751
752 if (const BinaryOperator *B = dyn_cast<BinaryOperator>(E))
753 if (B->isLogicalOp())
754 return true;
755
756 return false;
757}
758
Ted Kremenek14856d72009-04-06 23:06:54 +0000759namespace {
Ted Kremenek8f9b1b32009-05-01 16:08:09 +0000760class VISIBILITY_HIDDEN ContextLocation : public PathDiagnosticLocation {
761 bool IsDead;
762public:
763 ContextLocation(const PathDiagnosticLocation &L, bool isdead = false)
764 : PathDiagnosticLocation(L), IsDead(isdead) {}
765
766 void markDead() { IsDead = true; }
767 bool isDead() const { return IsDead; }
768};
769
Ted Kremenek14856d72009-04-06 23:06:54 +0000770class VISIBILITY_HIDDEN EdgeBuilder {
Ted Kremenek8f9b1b32009-05-01 16:08:09 +0000771 std::vector<ContextLocation> CLocs;
772 typedef std::vector<ContextLocation>::iterator iterator;
Ted Kremenek14856d72009-04-06 23:06:54 +0000773 PathDiagnostic &PD;
774 PathDiagnosticBuilder &PDB;
775 PathDiagnosticLocation PrevLoc;
Ted Kremenek8f9b1b32009-05-01 16:08:09 +0000776
777 bool IsConsumedExpr(const PathDiagnosticLocation &L);
778
Ted Kremenek14856d72009-04-06 23:06:54 +0000779 bool containsLocation(const PathDiagnosticLocation &Container,
780 const PathDiagnosticLocation &Containee);
781
782 PathDiagnosticLocation getContextLocation(const PathDiagnosticLocation &L);
Ted Kremenek14856d72009-04-06 23:06:54 +0000783
784 void popLocation() {
Ted Kremenek8f9b1b32009-05-01 16:08:09 +0000785 if (!CLocs.back().isDead() && CLocs.back().asLocation().isFileID()) {
786 PathDiagnosticLocation L = CLocs.back();
Ted Kremenekc2924d02009-04-23 16:19:29 +0000787
Ted Kremenek6f132352009-04-23 16:44:22 +0000788 if (const Stmt *S = L.asStmt()) {
789 while (1) {
790 // Adjust the location for some expressions that are best referenced
791 // by one of their subexpressions.
792 if (const ParenExpr *PE = dyn_cast<ParenExpr>(S))
793 S = PE->IgnoreParens();
794 else if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(S))
795 S = CO->getCond();
796 else if (const ChooseExpr *CE = dyn_cast<ChooseExpr>(S))
797 S = CE->getCond();
798 else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(S))
799 S = BE->getLHS();
Ted Kremenek8bd4d032009-04-28 04:23:15 +0000800 else if (const DoStmt *DS = dyn_cast<DoStmt>(S))
801 S = DS->getCond();
Ted Kremenek6f132352009-04-23 16:44:22 +0000802 else
803 break;
804 }
805
Ted Kremenekc2924d02009-04-23 16:19:29 +0000806 L = PathDiagnosticLocation(S, L.getManager());
807 }
808
Ted Kremenek5c7168c2009-04-22 20:36:26 +0000809 // For contexts, we only one the first character as the range.
810 L = PathDiagnosticLocation(L.asLocation(), L.getManager());
Ted Kremenek4f5be3b2009-04-22 20:51:59 +0000811 rawAddEdge(L);
Ted Kremenek5c7168c2009-04-22 20:36:26 +0000812 }
Ted Kremenek14856d72009-04-06 23:06:54 +0000813 CLocs.pop_back();
814 }
815
816 PathDiagnosticLocation IgnoreParens(const PathDiagnosticLocation &L);
817
818public:
819 EdgeBuilder(PathDiagnostic &pd, PathDiagnosticBuilder &pdb)
820 : PD(pd), PDB(pdb) {
Ted Kremeneka301a672009-04-22 18:16:20 +0000821
822 // If the PathDiagnostic already has pieces, add the enclosing statement
823 // of the first piece as a context as well.
Ted Kremenek14856d72009-04-06 23:06:54 +0000824 if (!PD.empty()) {
825 PrevLoc = PD.begin()->getLocation();
826
827 if (const Stmt *S = PrevLoc.asStmt())
828 addContext(PDB.getEnclosingStmtLocation(S).asStmt());
829 }
830 }
831
832 ~EdgeBuilder() {
833 while (!CLocs.empty()) popLocation();
Ted Kremeneka301a672009-04-22 18:16:20 +0000834
835 // Finally, add an initial edge from the start location of the first
836 // statement (if it doesn't already exist).
Sebastian Redld3a413d2009-04-26 20:35:05 +0000837 // FIXME: Should handle CXXTryStmt if analyser starts supporting C++.
838 if (const CompoundStmt *CS =
839 PDB.getCodeDecl().getCompoundBody(PDB.getContext()))
Ted Kremeneka301a672009-04-22 18:16:20 +0000840 if (!CS->body_empty()) {
841 SourceLocation Loc = (*CS->body_begin())->getLocStart();
842 rawAddEdge(PathDiagnosticLocation(Loc, PDB.getSourceManager()));
843 }
844
Ted Kremenek14856d72009-04-06 23:06:54 +0000845 }
846
847 void addEdge(PathDiagnosticLocation NewLoc, bool alwaysAdd = false);
848
849 void addEdge(const Stmt *S, bool alwaysAdd = false) {
850 addEdge(PathDiagnosticLocation(S, PDB.getSourceManager()), alwaysAdd);
851 }
852
Ted Kremenek8bd4d032009-04-28 04:23:15 +0000853 void rawAddEdge(PathDiagnosticLocation NewLoc);
854
Ted Kremenek14856d72009-04-06 23:06:54 +0000855 void addContext(const Stmt *S);
856};
857} // end anonymous namespace
858
859
860PathDiagnosticLocation
861EdgeBuilder::getContextLocation(const PathDiagnosticLocation &L) {
862 if (const Stmt *S = L.asStmt()) {
863 if (IsControlFlowExpr(S))
864 return L;
865
866 return PDB.getEnclosingStmtLocation(S);
867 }
868
869 return L;
870}
871
872bool EdgeBuilder::containsLocation(const PathDiagnosticLocation &Container,
873 const PathDiagnosticLocation &Containee) {
874
875 if (Container == Containee)
876 return true;
877
878 if (Container.asDecl())
879 return true;
880
881 if (const Stmt *S = Containee.asStmt())
882 if (const Stmt *ContainerS = Container.asStmt()) {
883 while (S) {
884 if (S == ContainerS)
885 return true;
886 S = PDB.getParent(S);
887 }
888 return false;
889 }
890
891 // Less accurate: compare using source ranges.
892 SourceRange ContainerR = Container.asRange();
893 SourceRange ContaineeR = Containee.asRange();
894
895 SourceManager &SM = PDB.getSourceManager();
896 SourceLocation ContainerRBeg = SM.getInstantiationLoc(ContainerR.getBegin());
897 SourceLocation ContainerREnd = SM.getInstantiationLoc(ContainerR.getEnd());
898 SourceLocation ContaineeRBeg = SM.getInstantiationLoc(ContaineeR.getBegin());
899 SourceLocation ContaineeREnd = SM.getInstantiationLoc(ContaineeR.getEnd());
900
901 unsigned ContainerBegLine = SM.getInstantiationLineNumber(ContainerRBeg);
902 unsigned ContainerEndLine = SM.getInstantiationLineNumber(ContainerREnd);
903 unsigned ContaineeBegLine = SM.getInstantiationLineNumber(ContaineeRBeg);
904 unsigned ContaineeEndLine = SM.getInstantiationLineNumber(ContaineeREnd);
905
906 assert(ContainerBegLine <= ContainerEndLine);
907 assert(ContaineeBegLine <= ContaineeEndLine);
908
909 return (ContainerBegLine <= ContaineeBegLine &&
910 ContainerEndLine >= ContaineeEndLine &&
911 (ContainerBegLine != ContaineeBegLine ||
912 SM.getInstantiationColumnNumber(ContainerRBeg) <=
913 SM.getInstantiationColumnNumber(ContaineeRBeg)) &&
914 (ContainerEndLine != ContaineeEndLine ||
915 SM.getInstantiationColumnNumber(ContainerREnd) >=
916 SM.getInstantiationColumnNumber(ContainerREnd)));
917}
918
919PathDiagnosticLocation
920EdgeBuilder::IgnoreParens(const PathDiagnosticLocation &L) {
921 if (const Expr* E = dyn_cast_or_null<Expr>(L.asStmt()))
922 return PathDiagnosticLocation(E->IgnoreParenCasts(),
923 PDB.getSourceManager());
924 return L;
925}
926
927void EdgeBuilder::rawAddEdge(PathDiagnosticLocation NewLoc) {
928 if (!PrevLoc.isValid()) {
929 PrevLoc = NewLoc;
930 return;
931 }
932
933 if (NewLoc.asLocation() == PrevLoc.asLocation())
934 return;
935
936 // FIXME: Ignore intra-macro edges for now.
937 if (NewLoc.asLocation().getInstantiationLoc() ==
938 PrevLoc.asLocation().getInstantiationLoc())
939 return;
940
941 PD.push_front(new PathDiagnosticControlFlowPiece(NewLoc, PrevLoc));
942 PrevLoc = NewLoc;
943}
944
945void EdgeBuilder::addEdge(PathDiagnosticLocation NewLoc, bool alwaysAdd) {
Ted Kremeneka301a672009-04-22 18:16:20 +0000946
947 if (!alwaysAdd && NewLoc.asLocation().isMacroID())
948 return;
949
Ted Kremenek14856d72009-04-06 23:06:54 +0000950 const PathDiagnosticLocation &CLoc = getContextLocation(NewLoc);
951
952 while (!CLocs.empty()) {
Ted Kremenek8f9b1b32009-05-01 16:08:09 +0000953 ContextLocation &TopContextLoc = CLocs.back();
Ted Kremenek14856d72009-04-06 23:06:54 +0000954
955 // Is the top location context the same as the one for the new location?
956 if (TopContextLoc == CLoc) {
Ted Kremenek8f9b1b32009-05-01 16:08:09 +0000957 if (alwaysAdd) {
958 if (IsConsumedExpr(TopContextLoc))
959 TopContextLoc.markDead();
960
Ted Kremenek14856d72009-04-06 23:06:54 +0000961 rawAddEdge(NewLoc);
Ted Kremenek8f9b1b32009-05-01 16:08:09 +0000962 }
Ted Kremenek14856d72009-04-06 23:06:54 +0000963
964 return;
965 }
966
967 if (containsLocation(TopContextLoc, CLoc)) {
Ted Kremenek8f9b1b32009-05-01 16:08:09 +0000968 if (alwaysAdd) {
Ted Kremenek14856d72009-04-06 23:06:54 +0000969 rawAddEdge(NewLoc);
Ted Kremenek8f9b1b32009-05-01 16:08:09 +0000970
971 if (IsConsumedExpr(CLoc)) {
972 CLocs.push_back(ContextLocation(CLoc, true));
973 return;
974 }
975 }
976
Ted Kremenek14856d72009-04-06 23:06:54 +0000977 CLocs.push_back(CLoc);
978 return;
979 }
980
981 // Context does not contain the location. Flush it.
982 popLocation();
983 }
Ted Kremenek5c7168c2009-04-22 20:36:26 +0000984
985 // If we reach here, there is no enclosing context. Just add the edge.
986 rawAddEdge(NewLoc);
Ted Kremenek14856d72009-04-06 23:06:54 +0000987}
988
Ted Kremenek8f9b1b32009-05-01 16:08:09 +0000989bool EdgeBuilder::IsConsumedExpr(const PathDiagnosticLocation &L) {
990 if (const Expr *X = dyn_cast_or_null<Expr>(L.asStmt()))
991 return PDB.getParentMap().isConsumedExpr(X) && !IsControlFlowExpr(X);
992
993 return false;
994}
995
Ted Kremenek14856d72009-04-06 23:06:54 +0000996void EdgeBuilder::addContext(const Stmt *S) {
997 if (!S)
998 return;
999
1000 PathDiagnosticLocation L(S, PDB.getSourceManager());
1001
1002 while (!CLocs.empty()) {
1003 const PathDiagnosticLocation &TopContextLoc = CLocs.back();
1004
1005 // Is the top location context the same as the one for the new location?
1006 if (TopContextLoc == L)
1007 return;
1008
1009 if (containsLocation(TopContextLoc, L)) {
Ted Kremenek14856d72009-04-06 23:06:54 +00001010 CLocs.push_back(L);
1011 return;
1012 }
1013
1014 // Context does not contain the location. Flush it.
1015 popLocation();
1016 }
1017
1018 CLocs.push_back(L);
1019}
1020
1021static void GenerateExtensivePathDiagnostic(PathDiagnostic& PD,
1022 PathDiagnosticBuilder &PDB,
1023 const ExplodedNode<GRState> *N) {
1024
1025
1026 EdgeBuilder EB(PD, PDB);
1027
1028 const ExplodedNode<GRState>* NextNode = N->pred_empty()
1029 ? NULL : *(N->pred_begin());
Ted Kremenek14856d72009-04-06 23:06:54 +00001030 while (NextNode) {
1031 N = NextNode;
1032 NextNode = GetPredecessorNode(N);
1033 ProgramPoint P = N->getLocation();
1034
1035 // Block edges.
1036 if (const BlockEdge *BE = dyn_cast<BlockEdge>(&P)) {
1037 const CFGBlock &Blk = *BE->getSrc();
Ted Kremenek8bd4d032009-04-28 04:23:15 +00001038 const Stmt *Term = Blk.getTerminator();
1039
Ted Kremeneka902d552009-04-28 04:28:12 +00001040 if (Term && !isa<DoStmt>(Term))
Ted Kremenek14856d72009-04-06 23:06:54 +00001041 EB.addContext(Term);
1042
Ted Kremenek8bd4d032009-04-28 04:23:15 +00001043 // Are we jumping to the head of a loop? Add a special diagnostic.
1044 if (const Stmt *Loop = BE->getDst()->getLoopTarget()) {
1045
1046 PathDiagnosticLocation L(Loop, PDB.getSourceManager());
1047 PathDiagnosticEventPiece *p =
1048 new PathDiagnosticEventPiece(L,
1049 "Looping back to the head of the loop");
1050
1051 EB.addEdge(p->getLocation(), true);
1052 PD.push_front(p);
1053
1054 if (!Term) {
1055 const CompoundStmt *CS = NULL;
1056 if (const ForStmt *FS = dyn_cast<ForStmt>(Loop))
1057 CS = dyn_cast<CompoundStmt>(FS->getBody());
1058 else if (const WhileStmt *WS = dyn_cast<WhileStmt>(Loop))
1059 CS = dyn_cast<CompoundStmt>(WS->getBody());
1060
1061 if (CS)
1062 EB.rawAddEdge(PathDiagnosticLocation(CS->getRBracLoc(),
1063 PDB.getSourceManager()));
1064 }
1065 }
1066
Ted Kremenek14856d72009-04-06 23:06:54 +00001067 continue;
1068 }
1069
Ted Kremenek8bd4d032009-04-28 04:23:15 +00001070 if (const BlockEntrance *BE = dyn_cast<BlockEntrance>(&P)) {
Ted Kremenek14856d72009-04-06 23:06:54 +00001071 if (const Stmt* S = BE->getFirstStmt()) {
Ted Kremenek8f9b1b32009-05-01 16:08:09 +00001072 if (IsControlFlowExpr(S)) {
1073 // Add the proper context for '&&', '||', and '?'.
Ted Kremenek14856d72009-04-06 23:06:54 +00001074 EB.addContext(S);
Ted Kremenek8f9b1b32009-05-01 16:08:09 +00001075 }
Ted Kremenek14856d72009-04-06 23:06:54 +00001076 else
Ted Kremenek581329c2009-04-07 04:53:35 +00001077 EB.addContext(PDB.getEnclosingStmtLocation(S).asStmt());
Ted Kremenek14856d72009-04-06 23:06:54 +00001078 }
1079
1080 continue;
1081 }
1082
1083 PathDiagnosticPiece* p =
Ted Kremenek581329c2009-04-07 04:53:35 +00001084 PDB.getReport().VisitNode(N, NextNode, PDB.getGraph(),
1085 PDB.getBugReporter(), PDB.getNodeMapClosure());
Ted Kremenek14856d72009-04-06 23:06:54 +00001086
1087 if (p) {
1088 EB.addEdge(p->getLocation(), true);
1089 PD.push_front(p);
1090 }
1091 }
1092}
1093
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +00001094//===----------------------------------------------------------------------===//
Ted Kremenekcf118d42009-02-04 23:49:09 +00001095// Methods for BugType and subclasses.
1096//===----------------------------------------------------------------------===//
1097BugType::~BugType() {}
1098void BugType::FlushReports(BugReporter &BR) {}
Ted Kremenekbb77e9b2008-05-01 22:50:36 +00001099
Ted Kremenekcf118d42009-02-04 23:49:09 +00001100//===----------------------------------------------------------------------===//
1101// Methods for BugReport and subclasses.
1102//===----------------------------------------------------------------------===//
1103BugReport::~BugReport() {}
1104RangedBugReport::~RangedBugReport() {}
1105
1106Stmt* BugReport::getStmt(BugReporter& BR) const {
Ted Kremenek200ed922008-05-02 23:21:21 +00001107 ProgramPoint ProgP = EndNode->getLocation();
Ted Kremenekbd7efa82008-04-17 23:44:37 +00001108 Stmt *S = NULL;
1109
Ted Kremenekcf118d42009-02-04 23:49:09 +00001110 if (BlockEntrance* BE = dyn_cast<BlockEntrance>(&ProgP)) {
Ted Kremenekb697b102009-02-23 22:44:26 +00001111 if (BE->getBlock() == &BR.getCFG()->getExit()) S = GetPreviousStmt(EndNode);
Ted Kremenekcf118d42009-02-04 23:49:09 +00001112 }
1113 if (!S) S = GetStmt(ProgP);
1114
Ted Kremenekbb77e9b2008-05-01 22:50:36 +00001115 return S;
1116}
1117
1118PathDiagnosticPiece*
1119BugReport::getEndPath(BugReporter& BR,
Ted Kremenek3148eb42009-01-24 00:55:43 +00001120 const ExplodedNode<GRState>* EndPathNode) {
Ted Kremenekbb77e9b2008-05-01 22:50:36 +00001121
1122 Stmt* S = getStmt(BR);
Ted Kremenek61f3e052008-04-03 04:42:52 +00001123
1124 if (!S)
1125 return NULL;
1126
Ted Kremenekc9fa2f72008-05-01 23:13:35 +00001127 FullSourceLoc L(S->getLocStart(), BR.getContext().getSourceManager());
Ted Kremenek1fbfd5b2009-03-06 23:58:11 +00001128 PathDiagnosticPiece* P = new PathDiagnosticEventPiece(L, getDescription());
Ted Kremenek61f3e052008-04-03 04:42:52 +00001129
Ted Kremenekde7161f2008-04-03 18:00:37 +00001130 const SourceRange *Beg, *End;
Ted Kremenekbb77e9b2008-05-01 22:50:36 +00001131 getRanges(BR, Beg, End);
Ted Kremenekcf118d42009-02-04 23:49:09 +00001132
Ted Kremenekbb77e9b2008-05-01 22:50:36 +00001133 for (; Beg != End; ++Beg)
1134 P->addRange(*Beg);
Ted Kremenek61f3e052008-04-03 04:42:52 +00001135
1136 return P;
1137}
1138
Ted Kremenekbb77e9b2008-05-01 22:50:36 +00001139void BugReport::getRanges(BugReporter& BR, const SourceRange*& beg,
1140 const SourceRange*& end) {
1141
1142 if (Expr* E = dyn_cast_or_null<Expr>(getStmt(BR))) {
1143 R = E->getSourceRange();
Ted Kremenek9b5e5052009-02-27 20:05:10 +00001144 assert(R.isValid());
Ted Kremenekbb77e9b2008-05-01 22:50:36 +00001145 beg = &R;
1146 end = beg+1;
1147 }
1148 else
1149 beg = end = 0;
Ted Kremenekf1ae7052008-04-03 17:57:38 +00001150}
1151
Ted Kremenekcf118d42009-02-04 23:49:09 +00001152SourceLocation BugReport::getLocation() const {
1153 if (EndNode)
Ted Kremenek9b5e5052009-02-27 20:05:10 +00001154 if (Stmt* S = GetCurrentOrPreviousStmt(EndNode)) {
1155 // For member expressions, return the location of the '.' or '->'.
1156 if (MemberExpr* ME = dyn_cast<MemberExpr>(S))
1157 return ME->getMemberLoc();
1158
Ted Kremenekcf118d42009-02-04 23:49:09 +00001159 return S->getLocStart();
Ted Kremenek9b5e5052009-02-27 20:05:10 +00001160 }
Ted Kremenekcf118d42009-02-04 23:49:09 +00001161
1162 return FullSourceLoc();
Ted Kremenekd2f642b2008-04-14 17:39:48 +00001163}
1164
Ted Kremenek3148eb42009-01-24 00:55:43 +00001165PathDiagnosticPiece* BugReport::VisitNode(const ExplodedNode<GRState>* N,
1166 const ExplodedNode<GRState>* PrevN,
1167 const ExplodedGraph<GRState>& G,
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001168 BugReporter& BR,
1169 NodeResolver &NR) {
Ted Kremenek50a6d0c2008-04-09 21:41:14 +00001170 return NULL;
1171}
1172
Ted Kremenekcf118d42009-02-04 23:49:09 +00001173//===----------------------------------------------------------------------===//
1174// Methods for BugReporter and subclasses.
1175//===----------------------------------------------------------------------===//
1176
1177BugReportEquivClass::~BugReportEquivClass() {
1178 for (iterator I=begin(), E=end(); I!=E; ++I) delete *I;
1179}
1180
1181GRBugReporter::~GRBugReporter() { FlushReports(); }
1182BugReporterData::~BugReporterData() {}
1183
1184ExplodedGraph<GRState>&
1185GRBugReporter::getGraph() { return Eng.getGraph(); }
1186
1187GRStateManager&
1188GRBugReporter::getStateManager() { return Eng.getStateManager(); }
1189
1190BugReporter::~BugReporter() { FlushReports(); }
1191
1192void BugReporter::FlushReports() {
1193 if (BugTypes.isEmpty())
1194 return;
1195
1196 // First flush the warnings for each BugType. This may end up creating new
1197 // warnings and new BugTypes. Because ImmutableSet is a functional data
1198 // structure, we do not need to worry about the iterators being invalidated.
1199 for (BugTypesTy::iterator I=BugTypes.begin(), E=BugTypes.end(); I!=E; ++I)
1200 const_cast<BugType*>(*I)->FlushReports(*this);
1201
1202 // Iterate through BugTypes a second time. BugTypes may have been updated
1203 // with new BugType objects and new warnings.
1204 for (BugTypesTy::iterator I=BugTypes.begin(), E=BugTypes.end(); I!=E; ++I) {
1205 BugType *BT = const_cast<BugType*>(*I);
1206
1207 typedef llvm::FoldingSet<BugReportEquivClass> SetTy;
1208 SetTy& EQClasses = BT->EQClasses;
1209
1210 for (SetTy::iterator EI=EQClasses.begin(), EE=EQClasses.end(); EI!=EE;++EI){
1211 BugReportEquivClass& EQ = *EI;
1212 FlushReport(EQ);
1213 }
Ted Kremeneka43a1eb2008-04-23 23:02:12 +00001214
Ted Kremenekcf118d42009-02-04 23:49:09 +00001215 // Delete the BugType object. This will also delete the equivalence
1216 // classes.
1217 delete BT;
Ted Kremenek94826a72008-04-03 04:59:14 +00001218 }
Ted Kremenekcf118d42009-02-04 23:49:09 +00001219
1220 // Remove all references to the BugType objects.
1221 BugTypes = F.GetEmptySet();
1222}
1223
1224//===----------------------------------------------------------------------===//
1225// PathDiagnostics generation.
1226//===----------------------------------------------------------------------===//
1227
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001228static std::pair<std::pair<ExplodedGraph<GRState>*, NodeBackMap*>,
Ted Kremenekcf118d42009-02-04 23:49:09 +00001229 std::pair<ExplodedNode<GRState>*, unsigned> >
1230MakeReportGraph(const ExplodedGraph<GRState>* G,
1231 const ExplodedNode<GRState>** NStart,
1232 const ExplodedNode<GRState>** NEnd) {
Ted Kremenek94826a72008-04-03 04:59:14 +00001233
Ted Kremenekcf118d42009-02-04 23:49:09 +00001234 // Create the trimmed graph. It will contain the shortest paths from the
1235 // error nodes to the root. In the new graph we should only have one
1236 // error node unless there are two or more error nodes with the same minimum
1237 // path length.
1238 ExplodedGraph<GRState>* GTrim;
1239 InterExplodedGraphMap<GRState>* NMap;
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001240
1241 llvm::DenseMap<const void*, const void*> InverseMap;
1242 llvm::tie(GTrim, NMap) = G->Trim(NStart, NEnd, &InverseMap);
Ted Kremenekcf118d42009-02-04 23:49:09 +00001243
1244 // Create owning pointers for GTrim and NMap just to ensure that they are
1245 // released when this function exists.
1246 llvm::OwningPtr<ExplodedGraph<GRState> > AutoReleaseGTrim(GTrim);
1247 llvm::OwningPtr<InterExplodedGraphMap<GRState> > AutoReleaseNMap(NMap);
1248
1249 // Find the (first) error node in the trimmed graph. We just need to consult
1250 // the node map (NMap) which maps from nodes in the original graph to nodes
1251 // in the new graph.
1252 const ExplodedNode<GRState>* N = 0;
1253 unsigned NodeIndex = 0;
1254
1255 for (const ExplodedNode<GRState>** I = NStart; I != NEnd; ++I)
1256 if ((N = NMap->getMappedNode(*I))) {
1257 NodeIndex = (I - NStart) / sizeof(*I);
1258 break;
1259 }
1260
1261 assert(N && "No error node found in the trimmed graph.");
1262
1263 // Create a new (third!) graph with a single path. This is the graph
1264 // that will be returned to the caller.
Ted Kremenek3148eb42009-01-24 00:55:43 +00001265 ExplodedGraph<GRState> *GNew =
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001266 new ExplodedGraph<GRState>(GTrim->getCFG(), GTrim->getCodeDecl(),
1267 GTrim->getContext());
Ted Kremenekcf118d42009-02-04 23:49:09 +00001268
Ted Kremenek10aa5542009-03-12 23:41:59 +00001269 // Sometimes the trimmed graph can contain a cycle. Perform a reverse BFS
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001270 // to the root node, and then construct a new graph that contains only
1271 // a single path.
Ted Kremenek3148eb42009-01-24 00:55:43 +00001272 llvm::DenseMap<const void*,unsigned> Visited;
Ted Kremenek10aa5542009-03-12 23:41:59 +00001273 std::queue<const ExplodedNode<GRState>*> WS;
1274 WS.push(N);
1275
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001276 unsigned cnt = 0;
Ted Kremenek3148eb42009-01-24 00:55:43 +00001277 const ExplodedNode<GRState>* Root = 0;
Ted Kremenekc1da4412008-06-17 19:14:06 +00001278
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001279 while (!WS.empty()) {
Ted Kremenek10aa5542009-03-12 23:41:59 +00001280 const ExplodedNode<GRState>* Node = WS.front();
1281 WS.pop();
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001282
1283 if (Visited.find(Node) != Visited.end())
1284 continue;
1285
1286 Visited[Node] = cnt++;
1287
1288 if (Node->pred_empty()) {
1289 Root = Node;
1290 break;
1291 }
1292
Ted Kremenek3148eb42009-01-24 00:55:43 +00001293 for (ExplodedNode<GRState>::const_pred_iterator I=Node->pred_begin(),
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001294 E=Node->pred_end(); I!=E; ++I)
Ted Kremenek10aa5542009-03-12 23:41:59 +00001295 WS.push(*I);
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001296 }
Ted Kremenekcf118d42009-02-04 23:49:09 +00001297
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001298 assert (Root);
1299
Ted Kremenek10aa5542009-03-12 23:41:59 +00001300 // Now walk from the root down the BFS path, always taking the successor
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001301 // with the lowest number.
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001302 ExplodedNode<GRState> *Last = 0, *First = 0;
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001303 NodeBackMap *BM = new NodeBackMap();
Ted Kremenekcf118d42009-02-04 23:49:09 +00001304
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001305 for ( N = Root ;;) {
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001306 // Lookup the number associated with the current node.
Ted Kremenek3148eb42009-01-24 00:55:43 +00001307 llvm::DenseMap<const void*,unsigned>::iterator I = Visited.find(N);
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001308 assert (I != Visited.end());
1309
1310 // Create the equivalent node in the new graph with the same state
1311 // and location.
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001312 ExplodedNode<GRState>* NewN =
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001313 GNew->getNode(N->getLocation(), N->getState());
1314
1315 // Store the mapping to the original node.
1316 llvm::DenseMap<const void*, const void*>::iterator IMitr=InverseMap.find(N);
1317 assert(IMitr != InverseMap.end() && "No mapping to original node.");
1318 (*BM)[NewN] = (const ExplodedNode<GRState>*) IMitr->second;
Ted Kremenekcf118d42009-02-04 23:49:09 +00001319
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001320 // Link up the new node with the previous node.
1321 if (Last)
1322 NewN->addPredecessor(Last);
Ted Kremeneka43a1eb2008-04-23 23:02:12 +00001323
1324 Last = NewN;
Ted Kremenekcf118d42009-02-04 23:49:09 +00001325
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001326 // Are we at the final node?
1327 if (I->second == 0) {
1328 First = NewN;
Ted Kremenekc1da4412008-06-17 19:14:06 +00001329 break;
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001330 }
Ted Kremenekcf118d42009-02-04 23:49:09 +00001331
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001332 // Find the next successor node. We choose the node that is marked
1333 // with the lowest DFS number.
Ted Kremenek3148eb42009-01-24 00:55:43 +00001334 ExplodedNode<GRState>::const_succ_iterator SI = N->succ_begin();
1335 ExplodedNode<GRState>::const_succ_iterator SE = N->succ_end();
Ted Kremenekc1da4412008-06-17 19:14:06 +00001336 N = 0;
1337
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001338 for (unsigned MinVal = 0; SI != SE; ++SI) {
Ted Kremenekcf118d42009-02-04 23:49:09 +00001339
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001340 I = Visited.find(*SI);
1341
1342 if (I == Visited.end())
1343 continue;
1344
1345 if (!N || I->second < MinVal) {
1346 N = *SI;
1347 MinVal = I->second;
Ted Kremenekc1da4412008-06-17 19:14:06 +00001348 }
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001349 }
Ted Kremenekcf118d42009-02-04 23:49:09 +00001350
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001351 assert (N);
Ted Kremeneka43a1eb2008-04-23 23:02:12 +00001352 }
Ted Kremenekcf118d42009-02-04 23:49:09 +00001353
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001354 assert (First);
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001355 return std::make_pair(std::make_pair(GNew, BM),
1356 std::make_pair(First, NodeIndex));
Ted Kremeneka43a1eb2008-04-23 23:02:12 +00001357}
1358
Ted Kremenek0e5c8d42009-03-10 05:16:17 +00001359/// CompactPathDiagnostic - This function postprocesses a PathDiagnostic object
1360/// and collapses PathDiagosticPieces that are expanded by macros.
1361static void CompactPathDiagnostic(PathDiagnostic &PD, const SourceManager& SM) {
1362 typedef std::vector<std::pair<PathDiagnosticMacroPiece*, SourceLocation> >
1363 MacroStackTy;
1364
1365 typedef std::vector<PathDiagnosticPiece*>
1366 PiecesTy;
1367
1368 MacroStackTy MacroStack;
1369 PiecesTy Pieces;
1370
1371 for (PathDiagnostic::iterator I = PD.begin(), E = PD.end(); I!=E; ++I) {
1372 // Get the location of the PathDiagnosticPiece.
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +00001373 const FullSourceLoc Loc = I->getLocation().asLocation();
Ted Kremenek0e5c8d42009-03-10 05:16:17 +00001374
1375 // Determine the instantiation location, which is the location we group
1376 // related PathDiagnosticPieces.
1377 SourceLocation InstantiationLoc = Loc.isMacroID() ?
1378 SM.getInstantiationLoc(Loc) :
1379 SourceLocation();
1380
1381 if (Loc.isFileID()) {
1382 MacroStack.clear();
1383 Pieces.push_back(&*I);
1384 continue;
1385 }
1386
1387 assert(Loc.isMacroID());
1388
1389 // Is the PathDiagnosticPiece within the same macro group?
1390 if (!MacroStack.empty() && InstantiationLoc == MacroStack.back().second) {
1391 MacroStack.back().first->push_back(&*I);
1392 continue;
1393 }
1394
1395 // We aren't in the same group. Are we descending into a new macro
1396 // or are part of an old one?
1397 PathDiagnosticMacroPiece *MacroGroup = 0;
1398
1399 SourceLocation ParentInstantiationLoc = InstantiationLoc.isMacroID() ?
1400 SM.getInstantiationLoc(Loc) :
1401 SourceLocation();
1402
1403 // Walk the entire macro stack.
1404 while (!MacroStack.empty()) {
1405 if (InstantiationLoc == MacroStack.back().second) {
1406 MacroGroup = MacroStack.back().first;
1407 break;
1408 }
1409
1410 if (ParentInstantiationLoc == MacroStack.back().second) {
1411 MacroGroup = MacroStack.back().first;
1412 break;
1413 }
1414
1415 MacroStack.pop_back();
1416 }
1417
1418 if (!MacroGroup || ParentInstantiationLoc == MacroStack.back().second) {
1419 // Create a new macro group and add it to the stack.
1420 PathDiagnosticMacroPiece *NewGroup = new PathDiagnosticMacroPiece(Loc);
1421
1422 if (MacroGroup)
1423 MacroGroup->push_back(NewGroup);
1424 else {
1425 assert(InstantiationLoc.isFileID());
1426 Pieces.push_back(NewGroup);
1427 }
1428
1429 MacroGroup = NewGroup;
1430 MacroStack.push_back(std::make_pair(MacroGroup, InstantiationLoc));
1431 }
1432
1433 // Finally, add the PathDiagnosticPiece to the group.
1434 MacroGroup->push_back(&*I);
1435 }
1436
1437 // Now take the pieces and construct a new PathDiagnostic.
1438 PD.resetPath(false);
1439
1440 for (PiecesTy::iterator I=Pieces.begin(), E=Pieces.end(); I!=E; ++I) {
1441 if (PathDiagnosticMacroPiece *MP=dyn_cast<PathDiagnosticMacroPiece>(*I))
1442 if (!MP->containsEvent()) {
1443 delete MP;
1444 continue;
1445 }
1446
1447 PD.push_back(*I);
1448 }
1449}
1450
Ted Kremenek7dc86642009-03-31 20:22:36 +00001451void GRBugReporter::GeneratePathDiagnostic(PathDiagnostic& PD,
1452 BugReportEquivClass& EQ) {
1453
1454 std::vector<const ExplodedNode<GRState>*> Nodes;
1455
Ted Kremenekcf118d42009-02-04 23:49:09 +00001456 for (BugReportEquivClass::iterator I=EQ.begin(), E=EQ.end(); I!=E; ++I) {
1457 const ExplodedNode<GRState>* N = I->getEndNode();
1458 if (N) Nodes.push_back(N);
1459 }
1460
1461 if (Nodes.empty())
1462 return;
Ted Kremeneka43a1eb2008-04-23 23:02:12 +00001463
1464 // Construct a new graph that contains only a single path from the error
Ted Kremenekcf118d42009-02-04 23:49:09 +00001465 // node to a root.
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001466 const std::pair<std::pair<ExplodedGraph<GRState>*, NodeBackMap*>,
Ted Kremenek7dc86642009-03-31 20:22:36 +00001467 std::pair<ExplodedNode<GRState>*, unsigned> >&
1468 GPair = MakeReportGraph(&getGraph(), &Nodes[0], &Nodes[0] + Nodes.size());
Ted Kremeneka43a1eb2008-04-23 23:02:12 +00001469
Ted Kremenekcf118d42009-02-04 23:49:09 +00001470 // Find the BugReport with the original location.
1471 BugReport *R = 0;
1472 unsigned i = 0;
1473 for (BugReportEquivClass::iterator I=EQ.begin(), E=EQ.end(); I!=E; ++I, ++i)
1474 if (i == GPair.second.second) { R = *I; break; }
1475
1476 assert(R && "No original report found for sliced graph.");
Ted Kremeneka43a1eb2008-04-23 23:02:12 +00001477
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001478 llvm::OwningPtr<ExplodedGraph<GRState> > ReportGraph(GPair.first.first);
1479 llvm::OwningPtr<NodeBackMap> BackMap(GPair.first.second);
Ted Kremenekcf118d42009-02-04 23:49:09 +00001480 const ExplodedNode<GRState> *N = GPair.second.first;
Ted Kremenek7dc86642009-03-31 20:22:36 +00001481
Ted Kremenekcf118d42009-02-04 23:49:09 +00001482 // Start building the path diagnostic...
1483 if (PathDiagnosticPiece* Piece = R->getEndPath(*this, N))
Ted Kremenekbd7efa82008-04-17 23:44:37 +00001484 PD.push_back(Piece);
1485 else
1486 return;
Ted Kremenek7dc86642009-03-31 20:22:36 +00001487
1488 PathDiagnosticBuilder PDB(*this, ReportGraph.get(), R, BackMap.get(),
1489 getStateManager().getCodeDecl(),
Ted Kremenekbabdd7b2009-03-27 05:06:10 +00001490 getPathDiagnosticClient());
Ted Kremenekbd7efa82008-04-17 23:44:37 +00001491
Ted Kremenek7dc86642009-03-31 20:22:36 +00001492 switch (PDB.getGenerationScheme()) {
1493 case PathDiagnosticClient::Extensive:
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +00001494 GenerateExtensivePathDiagnostic(PD,PDB, N);
1495 break;
Ted Kremenek7dc86642009-03-31 20:22:36 +00001496 case PathDiagnosticClient::Minimal:
1497 GenerateMinimalPathDiagnostic(PD, PDB, N);
1498 break;
1499 }
Ted Kremenek7dc86642009-03-31 20:22:36 +00001500}
1501
Ted Kremenekcf118d42009-02-04 23:49:09 +00001502void BugReporter::Register(BugType *BT) {
1503 BugTypes = F.Add(BugTypes, BT);
Ted Kremenek76d90c82008-05-16 18:33:14 +00001504}
1505
Ted Kremenekcf118d42009-02-04 23:49:09 +00001506void BugReporter::EmitReport(BugReport* R) {
1507 // Compute the bug report's hash to determine its equivalence class.
1508 llvm::FoldingSetNodeID ID;
1509 R->Profile(ID);
Ted Kremenek61f3e052008-04-03 04:42:52 +00001510
Ted Kremenekcf118d42009-02-04 23:49:09 +00001511 // Lookup the equivance class. If there isn't one, create it.
1512 BugType& BT = R->getBugType();
1513 Register(&BT);
1514 void *InsertPos;
1515 BugReportEquivClass* EQ = BT.EQClasses.FindNodeOrInsertPos(ID, InsertPos);
1516
1517 if (!EQ) {
1518 EQ = new BugReportEquivClass(R);
1519 BT.EQClasses.InsertNode(EQ, InsertPos);
1520 }
1521 else
1522 EQ->AddReport(R);
Ted Kremenek61f3e052008-04-03 04:42:52 +00001523}
1524
Ted Kremenekcf118d42009-02-04 23:49:09 +00001525void BugReporter::FlushReport(BugReportEquivClass& EQ) {
1526 assert(!EQ.Reports.empty());
1527 BugReport &R = **EQ.begin();
Ted Kremenekd49967f2009-04-29 21:58:13 +00001528 PathDiagnosticClient* PD = getPathDiagnosticClient();
Ted Kremenekcf118d42009-02-04 23:49:09 +00001529
1530 // FIXME: Make sure we use the 'R' for the path that was actually used.
1531 // Probably doesn't make a difference in practice.
1532 BugType& BT = R.getBugType();
1533
Ted Kremenekd49967f2009-04-29 21:58:13 +00001534 llvm::OwningPtr<PathDiagnostic>
1535 D(new PathDiagnostic(R.getBugType().getName(),
Ted Kremenekda0e8422009-04-29 22:05:03 +00001536 !PD || PD->useVerboseDescription()
Ted Kremenekd49967f2009-04-29 21:58:13 +00001537 ? R.getDescription() : R.getShortDescription(),
1538 BT.getCategory()));
1539
Ted Kremenekcf118d42009-02-04 23:49:09 +00001540 GeneratePathDiagnostic(*D.get(), EQ);
Ted Kremenek072192b2008-04-30 23:47:44 +00001541
1542 // Get the meta data.
Ted Kremenek072192b2008-04-30 23:47:44 +00001543 std::pair<const char**, const char**> Meta = R.getExtraDescriptiveText();
Ted Kremenek3148eb42009-01-24 00:55:43 +00001544 for (const char** s = Meta.first; s != Meta.second; ++s) D->addMeta(*s);
Ted Kremenek75840e12008-04-18 01:56:37 +00001545
Ted Kremenek3148eb42009-01-24 00:55:43 +00001546 // Emit a summary diagnostic to the regular Diagnostics engine.
Ted Kremenek3148eb42009-01-24 00:55:43 +00001547 const SourceRange *Beg = 0, *End = 0;
1548 R.getRanges(*this, Beg, End);
1549 Diagnostic& Diag = getDiagnostic();
Ted Kremenekcf118d42009-02-04 23:49:09 +00001550 FullSourceLoc L(R.getLocation(), getSourceManager());
Ted Kremenekd90e7082009-02-07 22:36:41 +00001551 unsigned ErrorDiag = Diag.getCustomDiagID(Diagnostic::Warning,
1552 R.getDescription().c_str());
Ted Kremenek57202072008-07-14 17:40:50 +00001553
Ted Kremenek3148eb42009-01-24 00:55:43 +00001554 switch (End-Beg) {
Chris Lattner0a14eee2008-11-18 07:04:44 +00001555 default: assert(0 && "Don't handle this many ranges yet!");
1556 case 0: Diag.Report(L, ErrorDiag); break;
1557 case 1: Diag.Report(L, ErrorDiag) << Beg[0]; break;
1558 case 2: Diag.Report(L, ErrorDiag) << Beg[0] << Beg[1]; break;
1559 case 3: Diag.Report(L, ErrorDiag) << Beg[0] << Beg[1] << Beg[2]; break;
Ted Kremenek2f0e89e2008-04-18 22:56:53 +00001560 }
Ted Kremenek3148eb42009-01-24 00:55:43 +00001561
1562 // Emit a full diagnostic for the path if we have a PathDiagnosticClient.
1563 if (!PD)
1564 return;
1565
1566 if (D->empty()) {
Ted Kremenek1fbfd5b2009-03-06 23:58:11 +00001567 PathDiagnosticPiece* piece =
1568 new PathDiagnosticEventPiece(L, R.getDescription());
1569
Ted Kremenek3148eb42009-01-24 00:55:43 +00001570 for ( ; Beg != End; ++Beg) piece->addRange(*Beg);
1571 D->push_back(piece);
1572 }
1573
1574 PD->HandlePathDiagnostic(D.take());
Ted Kremenek61f3e052008-04-03 04:42:52 +00001575}
Ted Kremenek57202072008-07-14 17:40:50 +00001576
Ted Kremenek8c036c72008-09-20 04:23:38 +00001577void BugReporter::EmitBasicReport(const char* name, const char* str,
1578 SourceLocation Loc,
1579 SourceRange* RBeg, unsigned NumRanges) {
1580 EmitBasicReport(name, "", str, Loc, RBeg, NumRanges);
1581}
Ted Kremenekcf118d42009-02-04 23:49:09 +00001582
Ted Kremenek8c036c72008-09-20 04:23:38 +00001583void BugReporter::EmitBasicReport(const char* name, const char* category,
1584 const char* str, SourceLocation Loc,
1585 SourceRange* RBeg, unsigned NumRanges) {
1586
Ted Kremenekcf118d42009-02-04 23:49:09 +00001587 // 'BT' will be owned by BugReporter as soon as we call 'EmitReport'.
1588 BugType *BT = new BugType(name, category);
Chris Lattner0a14eee2008-11-18 07:04:44 +00001589 FullSourceLoc L = getContext().getFullLoc(Loc);
Ted Kremenekcf118d42009-02-04 23:49:09 +00001590 RangedBugReport *R = new DiagBugReport(*BT, str, L);
1591 for ( ; NumRanges > 0 ; --NumRanges, ++RBeg) R->addRange(*RBeg);
1592 EmitReport(R);
Ted Kremenek57202072008-07-14 17:40:50 +00001593}